1 diff --git a/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am b/Mono.Profiler/Mono.Profiler.Widgets/Makefile.am
2 index 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
9 -pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
10 +programfilesdir = $(pkglibdir)
11 +programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
13 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
15 diff --git a/Mono.Profiler/heap-snapshot-explorer/Makefile.am b/Mono.Profiler/heap-snapshot-explorer/Makefile.am
16 index 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+
23 -pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
24 +programfilesdir = $(pkglibdir)
25 +programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
27 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
29 diff --git a/Mono.Profiler/heap-snapshot-viewer/Makefile.am b/Mono.Profiler/heap-snapshot-viewer/Makefile.am
30 index 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+
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
43 diff --git a/Mono.Profiler/mprof-gui/Makefile.am b/Mono.Profiler/mprof-gui/Makefile.am
44 index 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
51 -pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
52 +programfilesdir = $(pkglibdir)
53 +programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
54 bin_SCRIPTS = emveepee
56 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
57 diff --git a/Mono.Profiler/profiler-decoder-library/Makefile.am b/Mono.Profiler/profiler-decoder-library/Makefile.am
58 index 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+
65 -pkglib_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
66 +programfilesdir = $(pkglibdir)
67 +programfiles_DATA = $(ASSEMBLY) $(ASSEMBLY_MDB)
69 CLEANFILES = $(ASSEMBLY) $(ASSEMBLY_MDB)
71 diff --git a/Mono.Profiler/profiler-file-decoder/Makefile.am b/Mono.Profiler/profiler-file-decoder/Makefile.am
72 index 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+
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
85 diff --git a/README b/README
86 index 3ad3752..a01a518 100644
89 @@ -23,3 +23,12 @@ automatically executed):
93 +Building on OSX with homebrew:
94 +------------------------------
96 +Have the following packages installed:
97 +autoconf pkg-config readline automake gettext glib intltool libtool
99 +Run autogen like this:
100 +PKG_CONFIG_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib/pkgconfig/ ./autogen.sh
102 diff --git a/configure.in b/configure.in
103 index 2a8870f..4771a2e 100644
107 -AC_INIT([mono-tools], [2.10])
108 +AC_INIT([mono-tools], [2.11])
109 AC_CONFIG_SRCDIR([README])
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
120 diff --git a/docbrowser/Makefile.am b/docbrowser/Makefile.am
121 index a1a2626..065c430 100644
122 --- a/docbrowser/Makefile.am
123 +++ b/docbrowser/Makefile.am
124 @@ -40,6 +40,7 @@ browser_sources = \
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 = \
134 $(srcdir)/Contributions.cs
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
141 diff --git a/docbrowser/browser.cs b/docbrowser/browser.cs
142 index 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) },
148 "Edit mdoc(5) XML documentation found within {PATH}.",
149 - v => RootTree.UncompiledHelpSources.Add (v) },
150 + v => RootTree.AddUncompiledSource (v) },
152 "Specify which HTML rendering {ENGINE} to use:\n" +
153 " " + string.Join ("\n ", engines) + "\n" +
154 @@ -119,6 +119,9 @@ class Driver {
156 List<string> topics = p.Parse (args);
158 + if (basedir == null)
159 + basedir = Directory.GetParent (System.Reflection.Assembly.GetExecutingAssembly ().Location).FullName;
162 Console.WriteLine ("Mono Documentation Browser");
163 Version ver = Assembly.GetExecutingAssembly ().GetName ().Version;
164 @@ -132,7 +135,7 @@ class Driver {
168 - if (mergeConfigFile != null) {
169 + /*if (mergeConfigFile != null) {
170 ArrayList targetDirs = new ArrayList ();
172 for (int i = 0; i < topics.Count; i++)
173 @@ -145,7 +148,7 @@ class Driver {
180 if (r != 0 || !show_gui)
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);
193 return; //There was a problem with the index
194 + searchResults.Add (r);
195 //insert the results in the tree
198 @@ -622,7 +627,7 @@ public class Browser {
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];
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)
210 SettingsHandler.Settings.preferred_font_size += 10;
211 - HelpSource.CssCode = null;
212 + //HelpSource.CssCode = null;
214 SettingsHandler.Save ();
216 void TextSmaller (object obj, EventArgs args)
218 SettingsHandler.Settings.preferred_font_size -= 10;
219 - HelpSource.CssCode = null;
220 + //HelpSource.CssCode = null;
222 SettingsHandler.Save ();
224 void TextNormal (object obj, EventArgs args)
226 SettingsHandler.Settings.preferred_font_size = 100;
227 - HelpSource.CssCode = null;
228 + //HelpSource.CssCode = null;
230 SettingsHandler.Save ();
232 @@ -733,6 +738,15 @@ public class Browser {
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).
241 + string[] urlParts = url.Split (':');
242 + if (urlParts [0].Length == 1)
243 + url = urlParts [0].ToUpper () + url.Substring (1);
245 Console.Error.WriteLine ("Trying: {0}", url);
247 string res = Browser.GetHtml (url, null, help_tree, out node);
248 @@ -785,8 +799,8 @@ public class Browser {
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)
263 + args.RetVal = true;
265 void on_print_activate (object sender, EventArgs e)
267 @@ -1691,7 +1706,7 @@ ExtLoop:
269 void OnOkClicked (object sender, EventArgs a)
271 - CommentService service = new CommentService();
272 + //CommentService service = new CommentService();
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];
280 - string url = n.URL;
281 + string url = n.PublicUrl;
285 @@ -2038,7 +2053,7 @@ public class TreeBrowser {
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);
294 @@ -2702,7 +2717,7 @@ public class Tab : Notebook {
295 string [] uSplit = EditingUtils.ParseEditUrl (edit_url);
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);
303 @@ -2711,6 +2726,49 @@ public class Tab : Notebook {
304 history.ActivateCurrent ();
307 + public static string GetNiceUrl (Node node) {
308 + if (node.Element.StartsWith("N:"))
309 + return node.Element;
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;
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;
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
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;
350 void OnCancelEdits (object sender, EventArgs a)
352 SetMode (Mode.Viewer);
353 @@ -2737,6 +2795,7 @@ public class Tab : Notebook {
355 StringWriter sw = new StringWriter ();
356 XmlWriter w = new XmlTextWriter (sw);
357 + var converter = new Monodoc.Generators.Html.Ecma2Html ();
360 edit_node.InnerXml = text_editor.Buffer.Text;
361 @@ -2750,7 +2809,7 @@ public class Tab : Notebook {
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);
370 diff --git a/docbrowser/editing.cs b/docbrowser/editing.cs
372 index 0000000..d7c1e32
374 +++ b/docbrowser/editing.cs
380 +// Ben Maurer (bmaurer@users.sourceforge.net)
382 +// (C) 2003 Ben Maurer
386 +using System.Collections;
387 +using System.Collections.Specialized;
391 +using System.Xml.Serialization;
392 +using System.Xml.XPath;
396 + public class EditingUtils {
398 + public static string FormatEditUri (string document_identifier, string xpath)
400 + return String.Format ("edit:{0}@{1}", HttpUtility.UrlEncode (document_identifier),
401 + HttpUtility.UrlEncode (xpath));
404 + public static string GetXPath (XPathNavigator n)
406 + switch (n.NodeType) {
407 + case XPathNodeType.Root: return "/";
408 + case XPathNodeType.Attribute: {
409 + string ret = "@" + n.Name;
411 + string s = GetXPath (n);
412 + return s + (s == "/" ? "" : "/") + ret;
415 + case XPathNodeType.Element: {
416 + string ret = n.Name;
418 + while (n.MoveToPrevious ()) {
419 + if (n.NodeType == XPathNodeType.Element && n.Name == ret)
422 + ret += "[" + i + "]";
423 + if (n.MoveToParent ()) {
424 + string s = GetXPath (n);
425 + return s + (s == "/" ? "" : "/") + ret;
430 + throw new Exception ("node type not supported for editing");
434 + public static XmlNode GetNodeFromUrl (string url, RootTree tree)
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]);
440 + string xp = uSplit [2];
441 + string id = uSplit [1];
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));
453 + throw new NotImplementedException("Don't know how to load " + url);
456 + return d.SelectSingleNode (xp);
460 + public static void SaveChange (string url, RootTree tree, XmlNode node, string node_url)
462 + /*string [] uSplit = ParseEditUrl (url);
464 + string xp = uSplit [2];
465 + string id = uSplit [1];
467 + if (uSplit[0].StartsWith("monodoc:///")) {
468 + int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
469 + HelpSource hs = tree.GetHelpSourceFromId (prov);
471 + changes.AddChange (hs.Name, hs.GetRealPath (id), xp, node, node_url);
473 + } else if (uSplit[0].StartsWith("file:")) {
474 + uSplit[0] = uSplit[0].Substring(5);
476 + XmlDocument d = new XmlDocument();
477 + d.PreserveWhitespace = true;
480 + XmlNode original = d.SelectSingleNode(xp);
481 + original.ParentNode.ReplaceChild(d.ImportNode(node, true), original);
485 + throw new NotImplementedException("Don't know how to save to " + url);
489 + public static void RemoveChange (string url, RootTree tree)
491 + /*string [] uSplit = ParseEditUrl (url);
493 + string xp = uSplit [2];
494 + string id = uSplit [1];
496 + if (uSplit[0].StartsWith("monodoc:///")) {
497 + int prov = int.Parse (uSplit [0].Substring("monodoc:///".Length));
498 + HelpSource hs = tree.GetHelpSourceFromId (prov);
500 + changes.RemoveChange (hs.Name, hs.GetRealPath (id), xp);
502 + } else if (uSplit[0].StartsWith("file:")) {
503 + //TODO: Not implemented
507 + public static void RenderEditPreview (string url, RootTree tree, XmlNode new_node, XmlWriter w)
509 + string [] uSplit = ParseEditUrl (url);
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);
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);
526 + public static string [] ParseEditUrl (string url)
528 + if (!url.StartsWith ("edit:"))
529 + throw new Exception ("wtf");
531 + string [] parts = url.Split ('@');
532 + if (parts.Length != 2)
533 + throw new Exception (String.Format ("invalid editing url {0}", parts.Length));
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];
544 + return new string [] {parts [0], parts [1], xp};
547 + public static void AccountForChanges (XmlDocument d, string doc_set, string real_file)
550 + FileChangeset fcs = changes.GetChangeset (doc_set, real_file);
554 + foreach (Change c in fcs.Changes) {
555 + // Filter out old changes
556 + if (c.FromVersion != RootTree.MonodocVersion)
559 + XmlNode old = d.SelectSingleNode (c.XPath);
561 + old.ParentNode.ReplaceChild (d.ImportNode (c.NewNode, true), old);
568 + public static GlobalChangeset changes = GlobalChangeset.Load ();
570 + static public GlobalChangeset GetChangesFrom (int starting_serial_id)
572 + return changes.GetFrom (starting_serial_id);
577 + public class GlobalChangeset {
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~");
583 + public static GlobalChangeset Load ()
586 + if (File.Exists (changeset_file))
587 + return LoadFromFile (changeset_file);
590 + return new GlobalChangeset ();
593 + public static GlobalChangeset LoadFromFile (string fileName)
595 + using (Stream s = File.OpenRead (fileName)) {
596 + return (GlobalChangeset) serializer.Deserialize (s);
600 + public void Save ()
602 + SettingsHandler.EnsureSettingsDirectory ();
605 + if (File.Exists(changeset_file)) // create backup copy
606 + File.Copy (changeset_file, changeset_backup_file, true);
608 + using (FileStream fs = File.Create (changeset_file)){
609 + serializer.Serialize (fs, this);
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);
616 + File.Delete (changeset_file); // if no backup, delete invalid changeset
620 + static void VerifyDirectoryExists (DirectoryInfo d) {
624 + VerifyDirectoryExists (d.Parent);
628 + [XmlElement ("DocSetChangeset", typeof (DocSetChangeset))]
629 + public ArrayList DocSetChangesets = new ArrayList ();
631 + public FileChangeset GetChangeset (string doc_set, string real_file)
633 + foreach (DocSetChangeset dscs in DocSetChangesets) {
634 + if (dscs.DocSet != doc_set)
637 + foreach (FileChangeset fcs in dscs.FileChangesets) {
638 + if (fcs.RealFile == real_file)
650 + foreach (DocSetChangeset dscs in DocSetChangesets){
651 + foreach (FileChangeset fcs in dscs.FileChangesets){
652 + count += fcs.Changes.Count;
660 + Change NewChange (string xpath, XmlNode new_node, string node_url)
662 + Change new_change = new Change ();
663 + new_change.XPath = xpath;
664 + new_change.NewNode = new_node;
665 + new_change.NodeUrl = node_url;
667 + Console.WriteLine ("New serial:" + SettingsHandler.Settings.SerialNumber);
668 + new_change.Serial = SettingsHandler.Settings.SerialNumber;
673 + public void AddChange (string doc_set, string real_file, string xpath, XmlNode new_node, string node_url)
675 + FileChangeset new_file_change_set;
676 + Change new_change = NewChange (xpath, new_node, node_url);
678 + if (real_file == null)
679 + throw new Exception ("Could not find real_file. Please talk to Miguel or Ben about this");
681 + foreach (DocSetChangeset dscs in DocSetChangesets) {
682 + if (dscs.DocSet != doc_set)
685 + foreach (FileChangeset fcs in dscs.FileChangesets) {
686 + if (fcs.RealFile != real_file)
689 + foreach (Change c in fcs.Changes) {
690 + if (c.XPath == xpath) {
691 + c.NewNode = new_node;
692 + c.Serial = SettingsHandler.Settings.SerialNumber;
697 + fcs.Changes.Add (new_change);
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);
710 + DocSetChangeset new_dcs = new DocSetChangeset ();
711 + new_dcs.DocSet = doc_set;
713 + new_file_change_set = new FileChangeset ();
714 + new_file_change_set.RealFile = real_file;
716 + new_file_change_set.Changes.Add (new_change);
717 + new_dcs.FileChangesets.Add (new_file_change_set);
718 + DocSetChangesets.Add (new_dcs);
721 + public void RemoveChange (string doc_set, string real_file, string xpath)
723 + if (real_file == null)
724 + throw new Exception ("Could not find real_file. Please talk to Miguel or Ben about this");
726 + for (int i = 0; i < DocSetChangesets.Count; i++) {
727 + DocSetChangeset dscs = DocSetChangesets [i] as DocSetChangeset;
728 + if (dscs.DocSet != doc_set)
731 + for (int j = 0; j < dscs.FileChangesets.Count; j++) {
732 + FileChangeset fcs = dscs.FileChangesets [j] as FileChangeset;
733 + if (fcs.RealFile != real_file)
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);
743 + if (fcs.Changes.Count == 0)
744 + dscs.FileChangesets.Remove (fcs);
747 + if (dscs.FileChangesets.Count == 0)
748 + DocSetChangesets.Remove (dscs);
752 + public GlobalChangeset GetFrom (int starting_serial_id)
754 + GlobalChangeset s = null;
756 + foreach (DocSetChangeset dscs in DocSetChangesets){
757 + object o = dscs.GetFrom (starting_serial_id);
761 + s = new GlobalChangeset ();
762 + s.DocSetChangesets.Add (o);
768 + public class DocSetChangeset {
769 + [XmlAttribute] public string DocSet;
771 + [XmlElement ("FileChangeset", typeof (FileChangeset))]
772 + public ArrayList FileChangesets = new ArrayList ();
774 + public DocSetChangeset GetFrom (int starting_serial_id)
776 + DocSetChangeset dsc = null;
778 + foreach (FileChangeset fcs in FileChangesets){
779 + object o = fcs.GetFrom (starting_serial_id);
783 + dsc = new DocSetChangeset ();
784 + dsc.DocSet = DocSet;
786 + dsc.FileChangesets.Add (o);
792 + public class FileChangeset {
793 + [XmlAttribute] public string RealFile;
795 + [XmlElement ("Change", typeof (Change))]
796 + public ArrayList Changes = new ArrayList ();
798 + public FileChangeset GetFrom (int starting_serial_id)
800 + FileChangeset fcs = null;
802 + foreach (Change c in Changes){
803 + if (c.Serial < starting_serial_id)
806 + fcs = new FileChangeset ();
807 + fcs.RealFile = RealFile;
809 + fcs.Changes.Add (c);
815 + public class Change {
816 + [XmlAttribute] public string XPath;
817 + [XmlAttribute] public int FromVersion = RootTree.MonodocVersion;
818 + [XmlAttribute] public string NodeUrl;
820 + public XmlNode NewNode;
824 + bool applied = false;
827 + // These are not a property, because we dont want them serialized;
828 + // Only used by the Admin Client.
830 + public bool Applied ()
835 + public void SetApplied (bool value)
842 + public class EditMerger {
843 + GlobalChangeset changeset;
844 + ArrayList targetDirs;
846 + public EditMerger (GlobalChangeset changeset, ArrayList targetDirs)
848 + this.changeset = changeset;
849 + this.targetDirs = targetDirs;
852 + public void Merge ()
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"))) {
863 + if (!merged) Console.WriteLine ("Could not merge docset {0}", dsc.DocSet);
867 + void Merge (DocSetChangeset dsc, string path)
869 + Console.WriteLine ("Merging changes in {0} ({1})", dsc.DocSet, path);
871 + foreach (FileChangeset fcs in dsc.FileChangesets) {
872 + if (File.Exists (Path.Combine (path, fcs.RealFile)))
875 + Console.WriteLine ("\tCould not find file {0}", Path.Combine (path, fcs.RealFile));
879 + void Merge (FileChangeset fcs, string path)
881 + XmlDocument d = new XmlDocument ();
882 + d.Load (Path.Combine (path, fcs.RealFile));
884 + foreach (Change c in fcs.Changes) {
885 + XmlNode old = d.SelectSingleNode (c.XPath);
887 + old.ParentNode.ReplaceChild (d.ImportNode (c.NewNode, true), old);
890 + d.Save (Path.Combine (path, fcs.RealFile));
895 diff --git a/docbrowser/monodoc.in b/docbrowser/monodoc.in
896 index 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@
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`
908 diff --git a/gendarme/AssemblyStaticInfo.cs b/gendarme/AssemblyStaticInfo.cs
909 index 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.")]
916 -[assembly: PermissionSet (SecurityAction.RequestMinimum, Unrestricted = true)]
917 [assembly: CLSCompliant (false)]
918 [assembly: ComVisible (false)]
921 -[assembly: AssemblyVersion ("2.10.0.0")]
922 +[assembly: AssemblyVersion ("2.11.0.0")]
924 diff --git a/gendarme/MIT.X11 b/gendarme/MIT.X11
925 index 8d90e9d..b3e59de 100644
926 --- a/gendarme/MIT.X11
927 +++ b/gendarme/MIT.X11
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
933 Permission is hereby granted, free of charge, to any person obtaining
934 diff --git a/gendarme/Makefile.am b/gendarme/Makefile.am
935 index 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
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
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
950 rm -rf gendarme.$(GENDARME_VERSION);
953 - wget http://www.ohloh.net/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
962 - scp $(USER)@upload.ohloh.net:gendarme/logs/upload.log .
965 diff --git a/gendarme/console/ConsoleRunner.cs b/gendarme/console/ConsoleRunner.cs
966 index 97afccb..bf9814c 100644
967 --- a/gendarme/console/ConsoleRunner.cs
968 +++ b/gendarme/console/ConsoleRunner.cs
971 using System.Collections.Generic;
972 using System.Diagnostics;
973 +using System.Globalization;
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;
986 private bool version;
987 + private bool console;
988 private List<string> assembly_names;
990 + static string [] SplitOptions (string value)
992 + return value.ToUpperInvariant ().Split (new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
995 // parse severity filter
996 // e.g. Audit,High+ == Audit, High and Critical
997 - void ParseSeverity ()
998 + bool ParseSeverity (string filter)
1000 SeverityBitmask.ClearAll ();
1001 - string [] options = severity_filter.ToUpperInvariant ().Split (',');
1002 - foreach (string option in options) {
1003 + foreach (string option in SplitOptions (filter)) {
1007 @@ -101,28 +104,26 @@ namespace Gendarme {
1008 SeverityBitmask.SetAll ();
1012 + string msg = String.Format (CultureInfo.CurrentCulture, "Unknown severity level '{0}'", option);
1013 + throw new OptionException (msg, "severity");
1016 char end = option [option.Length - 1];
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);
1024 SeverityBitmask.Set (severity);
1025 - Console.WriteLine ("Set {0} -> {1}", severity, SeverityBitmask);
1031 - void ParseConfidence ()
1032 + bool ParseConfidence (string filter)
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;
1041 @@ -151,7 +152,8 @@ namespace Gendarme {
1042 ConfidenceBitmask.SetAll ();
1046 + string msg = String.Format (CultureInfo.CurrentCulture, "Unknown confidence level '{0}'", option);
1047 + throw new OptionException (msg, "confidence");
1050 char end = option [option.Length - 1];
1051 @@ -163,48 +165,104 @@ namespace Gendarme {
1052 ConfidenceBitmask.Set (confidence);
1058 + static string ValidateInputFile (string option, string file)
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);
1067 + static string ValidateOutputFile (string option, string file)
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);
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);
1085 + if (msg.Length > 0)
1086 + throw new OptionException (msg, option);
1091 + static string ValidateRuleSet (string ruleSet)
1093 + if (String.IsNullOrEmpty (ruleSet)) {
1094 + throw new OptionException ("Missing rule set name", "set");
1099 + static int ValidateLimit (string limit)
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");
1106 + return defects_limit;
1109 byte Parse (string [] args)
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;
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 },
1141 - assembly_names = p.Parse (args);
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;
1149 + assembly_names = p.Parse (args);
1151 + catch (OptionException e) {
1152 + Console.WriteLine ("Error parsing option '{0}' : {1}", e.OptionName, e.Message);
1153 + Console.WriteLine ();
1157 // by default the runner will ignore Audit and Low severity defects
1158 - if (String.IsNullOrEmpty (severity_filter)) {
1160 SeverityBitmask.SetAll ();
1161 SeverityBitmask.Clear (Severity.Audit);
1162 SeverityBitmask.Clear (Severity.Low);
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);
1173 - ParseConfidence ();
1176 return (byte) ((assembly_names.Count > 0) ? 0 : 1);
1177 @@ -281,7 +339,7 @@ namespace Gendarme {
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)) {
1186 @@ -380,7 +438,7 @@ namespace Gendarme {
1187 private static string TimeToString (TimeSpan time)
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);
1193 return "<0.1 seconds";
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 ()));
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.");
1216 diff --git a/gendarme/console/Helpers.cs b/gendarme/console/Helpers.cs
1217 index c399452..3ef8361 100644
1218 --- a/gendarme/console/Helpers.cs
1219 +++ b/gendarme/console/Helpers.cs
1220 @@ -38,7 +38,7 @@ namespace Gendarme {
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);
1229 diff --git a/gendarme/console/IgnoreFileList.cs b/gendarme/console/IgnoreFileList.cs
1230 index acf0d1d..b714ded 100644
1231 --- a/gendarme/console/IgnoreFileList.cs
1232 +++ b/gendarme/console/IgnoreFileList.cs
1233 @@ -61,13 +61,13 @@ namespace Gendarme {
1235 private void Parse ()
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) {
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);
1252 @@ -87,19 +87,33 @@ namespace Gendarme {
1256 - private void ProcessLine (string line)
1257 + static string GetString (char [] buffer, int length)
1259 - if (line.Length < 1)
1260 + // skip the 'type' + ':' characters when looking for whitespace separator(s)
1262 + while (Char.IsWhiteSpace (buffer [start]) && (start < buffer.Length))
1266 + while (Char.IsWhiteSpace (buffer [end]) && (end >= start))
1269 + return new string (buffer, start, end - start);
1272 + private void ProcessLine (char [] buffer, int length)
1277 - switch (line [0]) {
1278 + switch (buffer [0]) {
1279 case '#': // comment
1282 - current_rule = line.Substring (line.LastIndexOf (' ') + 1);
1283 + current_rule = GetString (buffer, length);
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 {
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));
1299 - Add (methods, current_rule, line.Substring (2).Trim ());
1300 + Add (methods, current_rule, GetString (buffer, length));
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)));
1306 case '@': // include file
1307 - files.Push (line.Substring (2).Trim ());
1308 + files.Push (GetString (buffer, length));
1311 - Console.Error.WriteLine ("Bad ignore entry : '{0}'", line);
1312 + Console.Error.WriteLine ("Bad ignore entry : '{0}'", new string (buffer));
1316 @@ -148,14 +162,13 @@ namespace Gendarme {
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);
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);
1333 diff --git a/gendarme/console/Makefile.am b/gendarme/console/Makefile.am
1334 index 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)))
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)
1345 self-test: ../bin/gendarme.exe
1346 diff --git a/gendarme/console/Settings.cs b/gendarme/console/Settings.cs
1347 index 3ecafec..23b5429 100644
1348 --- a/gendarme/console/Settings.cs
1349 +++ b/gendarme/console/Settings.cs
1352 // Sebastien Pouliot <sebastien@ximian.com>
1354 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
1355 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
1357 // Permission is hereby granted, free of charge, to any person obtaining
1358 // a copy of this software and associated documentation files (the
1363 +using System.Globalization;
1365 using System.Reflection;
1366 using System.Collections.Generic;
1367 @@ -150,7 +151,8 @@ namespace Gendarme {
1369 private void OnValidationErrors (object sender, ValidationEventArgs args)
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)));
1376 private void ValidateXmlDocument ()
1377 @@ -228,7 +230,8 @@ namespace Gendarme {
1379 static Exception GetException (string message, string ruleName, string propertyName, string value)
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));
1387 diff --git a/gendarme/console/XmlResultWriter.cs b/gendarme/console/XmlResultWriter.cs
1388 index 3a5e0f4..3dcdff1 100644
1389 --- a/gendarme/console/XmlResultWriter.cs
1390 +++ b/gendarme/console/XmlResultWriter.cs
1395 +using System.Globalization;
1399 @@ -70,7 +71,7 @@ namespace Gendarme {
1401 writer.WriteStartDocument ();
1402 writer.WriteStartElement ("gendarme-output");
1403 - writer.WriteAttributeString ("date", DateTime.UtcNow.ToString ());
1404 + writer.WriteAttributeString ("date", DateTime.UtcNow.ToString (CultureInfo.InvariantCulture));
1407 protected override void Write ()
1408 diff --git a/gendarme/console/gendarme.csproj b/gendarme/console/gendarme.csproj
1409 index 4f70bf5..eefae5e 100755
1410 --- a/gendarme/console/gendarme.csproj
1411 +++ b/gendarme/console/gendarme.csproj
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
1417 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
1418 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
1446 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
1447 <DebugSymbols>true</DebugSymbols>
\r
1449 <DefineConstants>TRACE;DEBUG</DefineConstants>
\r
1450 <ErrorReport>prompt</ErrorReport>
\r
1451 <WarningLevel>4</WarningLevel>
\r
1452 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
1454 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
1455 <DebugType>pdbonly</DebugType>
\r
1457 <DefineConstants>TRACE;RELEASE</DefineConstants>
\r
1458 <ErrorReport>prompt</ErrorReport>
\r
1459 <WarningLevel>4</WarningLevel>
\r
1460 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
1463 <Reference Include="System" />
\r
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
1474 <None Include="ChangeLog" />
\r
1475 @@ -95,30 +102,53 @@
1476 <EmbeddedResource Include="gendarme.xsl" />
\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
1488 + <Install>false</Install>
\r
1489 </BootstrapperPackage>
\r
1490 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
1491 <Visible>False</Visible>
\r
1494 + <Install>false</Install>
\r
1495 </BootstrapperPackage>
\r
1496 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
1497 <Visible>False</Visible>
\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
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">
1513 - <Target Name="AfterBuild">
1515 + <Target Name="BeforeBuild">
\r
1518 + <Target Name="AfterBuild">
\r
1520 + SourceFiles="$(TargetDir)..\..\..\rules\rules.xml"
\r
1521 + DestinationFolder="$(TargetDir)"
\r
1522 + SkipUnchangedFiles="True"
\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
1534 <ProjectExtensions>
\r
1536 diff --git a/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs b/gendarme/framework/Gendarme.Framework.Engines/SuppressMessageEngine.cs
1537 index 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 {
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);
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)
1553 - if (ca.AttributeType.FullName != SuppressMessage)
1554 + if (!ca.AttributeType.IsNamed ("System.Diagnostics.CodeAnalysis", "SuppressMessageAttribute"))
1557 var arguments = ca.ConstructorArguments;
1558 @@ -200,7 +200,7 @@ namespace Gendarme.Framework.Engines {
1559 foreach (ModuleDefinition module in assembly.Modules) {
1561 foreach (TypeDefinition type in module.GetAllTypes ()) {
1562 - if (targets.TryGetValue (type.FullName, out rules))
1563 + if (targets.TryGetValue (type.GetFullName (), out rules))
1566 if (type.HasMethods) {
1567 @@ -213,11 +213,11 @@ namespace Gendarme.Framework.Engines {
1571 - private void ResolveMethod (IMetadataTokenProvider method)
1572 + private void ResolveMethod (MemberReference method)
1574 HashSet<string> rules;
1576 - string m = method.ToString ();
1577 + string m = method.GetFullName ();
1578 m = m.Substring (m.IndexOf (' ') + 1);
1580 if (targets.TryGetValue (m, out rules))
1581 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/Log.cs b/gendarme/framework/Gendarme.Framework.Helpers/Log.cs
1582 index 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;
1589 +using Gendarme.Framework.Rocks;
1591 namespace Gendarme.Framework.Helpers {
1593 @@ -83,9 +84,9 @@ namespace Gendarme.Framework.Helpers {
1596 [Conditional ("DEBUG")]
1597 - public static void WriteLine<T> (T category, MethodDefinition method)
1598 + public static void WriteLine<T> (T category, MemberReference member)
1600 - WriteLine (typeof (T).Name, method);
1601 + WriteLine (typeof (T).Name, member);
1604 // WriteLine (string)
1605 @@ -104,10 +105,15 @@ namespace Gendarme.Framework.Helpers {
1608 [Conditional ("DEBUG")]
1609 - public static void WriteLine (string category, MethodDefinition method)
1610 + public static void WriteLine (string category, MemberReference member)
1612 - if (IsEnabled (category))
1613 - Debug.WriteLine (new MethodPrinter (method).ToString ());
1614 + if (IsEnabled (category)) {
1615 + MethodDefinition md = (member as MethodDefinition);
1617 + Debug.WriteLine (new MethodPrinter (md).ToString ());
1619 + Debug.WriteLine (member.GetFullName ());
1624 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodPrinter.cs
1625 index 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;
1635 using Mono.Cecil.Cil;
1636 @@ -60,17 +61,28 @@ namespace Gendarme.Framework.Helpers {
1637 buffer.Append ("* ");
1639 buffer.Append (" ");
1640 - buffer.AppendFormat (" {0}: {1}", instr.Offset.ToString ("X4"),
1641 - instr.OpCode.Name);
1643 + buffer.Append (" ");
1644 + buffer.Append (instr.Offset.ToString ("X4", CultureInfo.InvariantCulture));
1645 + buffer.Append (": ");
1646 + buffer.Append (instr.OpCode.Name);
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));
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);
1670 + buffer.AppendLine ();
1673 if (EndsTryRegion (instr) != null)
1674 buffer.AppendLine ("} (Try)");
1675 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignature.cs
1676 index 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;
1683 +using Gendarme.Framework.Rocks;
1685 namespace Gendarme.Framework.Helpers {
1687 @@ -49,7 +50,7 @@ namespace Gendarme.Framework.Helpers {
1691 - // <seealso cref="Gendarme.Framework.Helpers.MethodSignatures"/>
1692 + /// <seealso cref="Gendarme.Framework.Helpers.MethodSignatures"/>
1693 public class MethodSignature {
1696 @@ -121,7 +122,7 @@ namespace Gendarme.Framework.Helpers {
1697 if (Name != null && method.Name != Name)
1700 - if (ReturnType != null && method.ReturnType.FullName != ReturnType)
1701 + if (ReturnType != null && !method.ReturnType.IsNamed (ReturnType))
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])) {
1714 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs b/gendarme/framework/Gendarme.Framework.Helpers/MethodSignatures.cs
1715 index 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;
1722 +using Gendarme.Framework.Rocks;
1724 namespace Gendarme.Framework.Helpers {
1726 @@ -120,19 +121,23 @@ namespace Gendarme.Framework.Helpers {
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"))
1734 IList<ParameterDefinition> pdc = method.Parameters;
1735 - if (pdc [0].ParameterType.FullName != "System.String")
1736 + if (!pdc [0].ParameterType.IsNamed ("System", "String"))
1739 TypeReference last = pdc [pdc.Count - 1].ParameterType;
1740 if (!last.IsByReference)
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)
1749 + string pt_name = last.Name;
1750 + return (String.Compare (pt_name, 0, mtype.Name, 0, pt_name.Length - 1, StringComparison.Ordinal) == 0);
1754 @@ -141,9 +146,9 @@ namespace Gendarme.Framework.Helpers {
1755 delegate (MethodReference method) {
1756 if (!method.HasParameters)
1758 - if (method.ReturnType.FullName != method.DeclaringType.FullName)
1759 + if (!method.ReturnType.IsNamed (method.DeclaringType.Namespace, method.DeclaringType.Name))
1761 - return (method.Parameters [0].ParameterType.FullName == "System.String");
1762 + return method.Parameters [0].ParameterType.IsNamed ("System", "String");
1766 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs b/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1767 index f7ceeac..6058fbe 100644
1768 --- a/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1769 +++ b/gendarme/framework/Gendarme.Framework.Helpers/OpCodeBitmask.cs
1774 +using System.Globalization;
1777 using Mono.Cecil.Cil;
1778 @@ -144,12 +145,12 @@ namespace Gendarme.Framework.Helpers {
1779 return Equals (obj as OpCodeBitmask);
1782 - public bool Equals (OpCodeBitmask set)
1783 + public bool Equals (OpCodeBitmask other)
1786 + if (other == null)
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]));
1794 public override int GetHashCode ()
1795 @@ -159,7 +160,8 @@ namespace Gendarme.Framework.Helpers {
1797 public override string ToString ()
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]);
1805 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryAnalysis.cs
1806 index 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;
1813 - public bool Equals (StoreSlot storeSlot)
1814 + public bool Equals (StoreSlot other)
1816 - return this == storeSlot;
1817 + return this == other;
1820 public override int GetHashCode ()
1821 @@ -182,40 +182,14 @@ namespace Gendarme.Framework.Helpers {
1825 - public bool Equals (InstructionWithLeave iwl)
1826 + public bool Equals (InstructionWithLeave other)
1828 - if (Instruction != iwl.Instruction)
1831 - if (LeaveStack == null)
1832 - return (iwl.LeaveStack == null);
1834 - if (iwl.LeaveStack == null)
1837 - if (LeaveStack.Length != iwl.LeaveStack.Length)
1840 - for (int i = 0; i < LeaveStack.Length; i++) {
1841 - if (LeaveStack [i] != iwl.LeaveStack [i])
1845 + return (Instruction == other.Instruction);
1848 public override int GetHashCode ()
1853 - hc ^= Instruction.GetHashCode ();
1854 - if (LeaveStack != null) {
1855 - foreach (Instruction ins in LeaveStack)
1856 - hc ^= ins.GetHashCode ();
1861 + return Instruction.GetHashCode ();
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);
1869 - int sequence = ((ParameterDefinition) ins.Operand).GetSequence ();
1870 + int sequence = ((ParameterDefinition) ins.Operand).Index + 1;
1871 if (!this.Method.HasThis)
1873 return new StoreSlot (StoreType.Argument, sequence);
1874 @@ -581,7 +555,7 @@ namespace Gendarme.Framework.Helpers {
1876 case Code.Starg_S: //store arg (not ref / out etc)
1878 - int sequence = ((ParameterDefinition) ins.Operand).GetSequence ();
1879 + int sequence = ((ParameterDefinition) ins.Operand).Index + 1;
1880 if (!this.Method.HasThis)
1882 return new StoreSlot (StoreType.Argument, sequence);
1883 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs b/gendarme/framework/Gendarme.Framework.Helpers/StackEntryUsageResult.cs
1884 index 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 {
1891 - public bool Equals (StackEntryUsageResult usageResult)
1892 + public bool Equals (StackEntryUsageResult other)
1894 - return (Instruction == usageResult.Instruction) && (StackOffset == usageResult.StackOffset);
1895 + return (Instruction == other.Instruction) && (StackOffset == other.StackOffset);
1898 public override int GetHashCode ()
1899 diff --git a/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs b/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs
1900 new file mode 100644
1901 index 0000000..3242474
1903 +++ b/gendarme/framework/Gendarme.Framework.Helpers/StreamLineReader.cs
1906 +// StreamLineReader - A StringReader-like class that avoid creating string
1909 +// Sebastien Pouliot <sebastien@ximian.com>
1911 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
1921 +// The above copyright notice and this permission notice shall be
1922 +// included in all copies or substantial portions of the Software.
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.
1936 +namespace Gendarme.Framework.Helpers {
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 {
1947 + public StreamLineReader (string fileName)
1949 + sr = new StreamReader (fileName);
1953 + public StreamLineReader (Stream stream)
1955 + sr = new StreamReader (stream);
1959 + void Initialize ()
1961 + buff = new char [4096];
1962 + max = n = buff.Length;
1965 + public bool EndOfStream {
1966 + get { return (n == max || max == 0) && sr.EndOfStream; }
1969 + public int ReadLine (char [] buffer, int index, int count)
1972 + throw new ObjectDisposedException ("StreamLineReader");
1973 + if (buffer == null)
1974 + throw new ArgumentNullException ("buffer");
1976 + throw new ArgumentOutOfRangeException ("index", "< 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");
1984 + while (len < count) {
1986 + max = sr.ReadBlock (buff, 0, buff.Length);
1987 + if (max == 0) break;
1990 + char c = buff [n++];
1995 + Array.Clear (buffer, len, buffer.Length - len);
1998 + buffer [index++] = c;
2006 + public void Dispose ()
2009 + GC.SuppressFinalize (this);
2012 + protected virtual void Dispose (bool disposing)
2023 + protected bool Disposed { get; private set; }
2027 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2028 index a1b2cfc..12c6345 100644
2029 --- a/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2030 +++ b/gendarme/framework/Gendarme.Framework.Rocks/CecilRocks.cs
2035 +using System.Collections.Generic;
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);
2044 + static Dictionary<MemberReference, string> full_name_cache = new Dictionary<MemberReference, string> ();
2047 + /// Get the string value of the MemberReference FullName property without the cost
2048 + /// of allocating a new string for each (or most) calls.
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)
2058 + return String.Empty;
2061 + if (!full_name_cache.TryGetValue (self, out full_name)) {
2062 + full_name = self.FullName;
2063 + full_name_cache.Add (self, full_name);
2070 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/CustomAttributeRocks.cs
2071 index 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 {
2076 public static class CustomAttributeRocks {
2078 - internal static string [] GeneratedCodeAttributes = {
2079 - "System.CodeDom.Compiler.GeneratedCodeAttribute",
2080 - "System.Runtime.CompilerServices.CompilerGeneratedAttribute"
2084 - /// Check if the custom attribute collection contains an attribute of a specified type.
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)
2093 - if (attributeTypeName == null)
2094 - throw new ArgumentNullException ("attributeTypeName");
2096 + if ((self == null) || !self.HasCustomAttributes)
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")) {
2111 - /// Check if the custom attribute collection contains any of the specified type.
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)
2119 - if (attributeTypeNames == null)
2120 - throw new ArgumentNullException ("attributeTypeNames");
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)
2132 @@ -99,17 +64,25 @@ namespace Gendarme.Framework.Rocks {
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)
2144 - if (attributeName == null)
2145 - throw new ArgumentNullException ("attributeName");
2146 + if (nameSpace == null)
2147 + throw new ArgumentNullException ("nameSpace");
2149 + throw new ArgumentNullException ("name");
2151 if ((self == null) || !self.HasCustomAttributes)
2153 - return self.CustomAttributes.ContainsType (attributeName);
2155 + foreach (CustomAttribute ca in self.CustomAttributes) {
2156 + if (ca.AttributeType.IsNamed (nameSpace, name))
2163 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/FieldRocks.cs
2164 index 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 {
2171 - if (field.HasCustomAttributes) {
2172 - if (field.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2175 + if (field.HasAnyGeneratedCodeAttribute ())
2178 return field.DeclaringType.IsGeneratedCode ();
2181 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2182 index 6c8aaf6..aef546a 100644
2183 --- a/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2184 +++ b/gendarme/framework/Gendarme.Framework.Rocks/InstructionRocks.cs
2189 +using System.Globalization;
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;
2200 case FlowControl.Call:
2201 IMethodSignature calledMethod = (IMethodSignature) self.Operand;
2202 @@ -310,7 +311,8 @@ namespace Gendarme.Framework.Rocks {
2203 case StackBehaviour.PopAll:
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);
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;
2219 throw new NotImplementedException ("Varpush not supported for this Instruction.");
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);
2227 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/MethodRocks.cs
2228 index 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 {
2233 public static class MethodRocks {
2235 + public static bool IsNamed (this MemberReference self, string nameSpace, string typeName, string methodName)
2237 + if (methodName == null)
2238 + throw new ArgumentNullException ("methodName");
2241 + return ((self.Name == methodName) && self.DeclaringType.IsNamed (nameSpace, typeName));
2245 /// Check if the MethodReference is defined as the entry point of it's assembly.
2247 @@ -76,7 +85,7 @@ namespace Gendarme.Framework.Rocks {
2250 return (self.HasThis && !self.HasParameters && (self.Name == "Finalize") &&
2251 - (self.ReturnType.FullName == "System.Void"));
2252 + self.ReturnType.IsNamed ("System", "Void"));
2256 @@ -91,10 +100,9 @@ namespace Gendarme.Framework.Rocks {
2259 MethodDefinition method = self.Resolve ();
2260 - if ((method != null) && method.HasCustomAttributes) {
2261 - if (method.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2264 + if (method.HasAnyGeneratedCodeAttribute ())
2267 return self.DeclaringType.IsGeneratedCode ();
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)
2279 - if (retval != md.ReturnType.FullName)
2281 - if (md.HasParameters && (pcount == 0))
2283 - IList<ParameterDefinition> ppdc = md.Parameters;
2284 - if (pcount != ppdc.Count)
2288 - for (int i = 0; i < pcount; i++) {
2289 - if (method.Parameters [i].ParameterType.FullName != ppdc [i].ParameterType.FullName) {
2295 + if (!method.CompareSignature (md))
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);
2303 - return type.Inherits ("System.EventArgs");
2304 + return type.Inherits ("System", "EventArgs");
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"));
2313 @@ -283,7 +274,7 @@ namespace Gendarme.Framework.Rocks {
2315 private static bool AreSameElementTypes (TypeReference a, TypeReference b)
2317 - return a.GetElementType ().FullName == b.GetElementType ().FullName;
2318 + return a.IsGenericParameter || b.IsGenericParameter || b.IsNamed (a.Namespace, a.Name);
2322 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2323 index 06a946c..3aad117 100644
2324 --- a/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2325 +++ b/gendarme/framework/Gendarme.Framework.Rocks/ModuleRocks.cs
2328 // Sebastien Pouliot <sebastien@ximian.com>
2330 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
2331 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
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 {
2339 - public static bool HasAnyTypeReference (this ModuleDefinition self, string [] typeNames)
2340 + static Dictionary<ModuleDefinition, IEnumerable<MemberReference>> member_ref_cache = new Dictionary<ModuleDefinition, IEnumerable<MemberReference>> ();
2343 + /// Check if any MemberReference, referenced by the current ModuleDefinition, satisfies the
2344 + /// specified predicate.
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)
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);
2366 + return refs.Any (predicate);
2369 + static Dictionary<ModuleDefinition, IEnumerable<TypeReference>> type_ref_cache = new Dictionary<ModuleDefinition, IEnumerable<TypeReference>> ();
2371 - foreach (var typeName in typeNames)
2372 - if (self.HasTypeReference (typeName))
2375 + /// Check if any TypeReference, referenced by the current ModuleDefinition, satisfies the
2376 + /// specified predicate.
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)
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);
2397 + return refs.Any (predicate);
2401 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/ParameterRocks.cs
2402 index 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)
2409 - if (self == null || !self.HasCustomAttributes)
2411 - return self.CustomAttributes.ContainsType ("System.ParamArrayAttribute");
2415 - /// Returns the sequence number as found in the metadata
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)
2424 - return self.Index + 1;
2425 + return self.HasAttribute ("System", "ParamArrayAttribute");
2429 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/PropertyRocks.cs
2430 index 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 {
2437 - if (self.HasCustomAttributes) {
2438 - if (self.CustomAttributes.ContainsAnyType (CustomAttributeRocks.GeneratedCodeAttributes))
2441 + if (self.HasAnyGeneratedCodeAttribute ())
2444 return self.DeclaringType.IsGeneratedCode ();
2447 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/TypeRocks.cs
2448 index 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 {
2455 - /// Check if a type reference collection contains a type of a specific name.
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)
2463 - if (typeName == null)
2464 - throw new ArgumentNullException ("typeName");
2468 - foreach (TypeReference type in self) {
2469 - if (type.FullName == typeName)
2476 - /// Check if a type reference collection contains any of the specified type names.
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)
2484 - if (typeNames == null)
2485 - throw new ArgumentNullException ("typeNames");
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)
2500 /// Returns the first MethodDefinition that satisfies a given MethodSignature.
2502 /// <param name="self">The TypeReference on which the extension method can be called.</param>
2503 @@ -177,7 +132,7 @@ namespace Gendarme.Framework.Rocks {
2505 if ((method.Attributes & attributes) != attributes)
2507 - if (returnType != null && method.ReturnType.FullName != returnType)
2508 + if (returnType != null && !method.ReturnType.IsNamed (returnType))
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;
2521 @@ -284,13 +239,16 @@ namespace Gendarme.Framework.Rocks {
2522 /// where the information resides could be unavailable. False is returned in this case.
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)
2533 - if (interfaceName == null)
2534 - throw new ArgumentNullException ("interfaceName");
2535 + if (nameSpace == null)
2536 + throw new ArgumentNullException ("nameSpace");
2538 + throw new ArgumentNullException ("name");
2542 @@ -299,23 +257,22 @@ namespace Gendarme.Framework.Rocks {
2543 return false; // not enough information available
2545 // special case, check if we implement ourselves
2546 - if (type.IsInterface && (type.FullName == interfaceName))
2547 + if (type.IsInterface && type.IsNamed (nameSpace, name))
2550 - return Implements (type, interfaceName, (interfaceName.IndexOf ('`') >= 0));
2551 + return Implements (type, nameSpace, name);
2554 - private static bool Implements (TypeDefinition type, string interfaceName, bool generic)
2555 + private static bool Implements (TypeDefinition type, string nameSpace, string iname)
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))
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))
2571 @@ -331,21 +288,23 @@ namespace Gendarme.Framework.Rocks {
2572 /// where the information resides could be unavailable.
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)
2582 - if (className == null)
2583 - throw new ArgumentNullException ("className");
2584 + if (nameSpace == null)
2585 + throw new ArgumentNullException ("nameSpace");
2587 + throw new ArgumentNullException ("name");
2591 TypeReference current = self.Resolve ();
2592 while (current != null) {
2593 - string fullname = current.FullName;
2594 - if (fullname == className)
2595 + if (current.IsNamed (nameSpace, name))
2597 - if (fullname == "System.Object")
2598 + if (current.IsNamed ("System", "Object"))
2601 TypeDefinition td = current.Resolve ();
2602 @@ -357,6 +316,70 @@ namespace Gendarme.Framework.Rocks {
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.
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)
2615 + if (nameSpace == null)
2616 + throw new ArgumentNullException ("nameSpace");
2618 + throw new ArgumentNullException ("name");
2622 + if (self.IsNested) {
2623 + int spos = name.LastIndexOf ('/');
2626 + // GetFullName could be optimized away but it's a fairly uncommon case
2627 + return (nameSpace + "." + name == self.GetFullName ());
2630 + return ((self.Namespace == nameSpace) && (self.Name == name));
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
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)
2642 + if (fullName == null)
2643 + throw new ArgumentNullException ("fullName");
2647 + if (self.IsNested) {
2648 + int spos = fullName.LastIndexOf ('/');
2651 + // FIXME: GetFullName could be optimized away but it's a fairly uncommon case
2652 + return (fullName == self.GetFullName ());
2655 + int dpos = fullName.LastIndexOf ('.');
2656 + string nspace = self.Namespace;
2657 + if (dpos != nspace.Length)
2660 + if (String.CompareOrdinal (nspace, 0, fullName, 0, dpos) != 0)
2663 + string name = self.Name;
2664 + if (fullName.Length - dpos - 1 != name.Length)
2666 + return (String.CompareOrdinal (name, 0, fullName, dpos + 1, fullName.Length - dpos - 1) == 0);
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 {
2677 - return self.Inherits ("System.Attribute");
2678 + return self.Inherits ("System", "Attribute");
2682 @@ -387,13 +410,11 @@ namespace Gendarme.Framework.Rocks {
2683 if (null == type || type.BaseType == null)
2686 - switch (type.BaseType.FullName) {
2687 - case "System.Delegate":
2688 - case "System.MulticastDelegate":
2691 + if (type.BaseType.Namespace != "System")
2695 + string name = type.BaseType.Name;
2696 + return ((name == "Delegate") || (name == "MulticastDelegate"));
2700 @@ -410,7 +431,7 @@ namespace Gendarme.Framework.Rocks {
2701 if ((type == null) || !type.IsEnum || !type.HasCustomAttributes)
2704 - return type.HasAttribute ("System.FlagsAttribute");
2705 + return type.HasAttribute ("System", "FlagsAttribute");
2709 @@ -423,9 +444,11 @@ namespace Gendarme.Framework.Rocks {
2713 - string full_name = self.FullName;
2714 - return ((full_name == "System.Single") ||
2715 - (full_name == "System.Double"));
2716 + if (self.Namespace != "System")
2719 + string name = self.Name;
2720 + return ((name == "Single") || (name == "Double"));
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 ())
2733 @@ -471,14 +494,11 @@ namespace Gendarme.Framework.Rocks {
2737 - switch (self.FullName) {
2738 - case "System.IntPtr":
2739 - case "System.UIntPtr":
2740 - case "System.Runtime.InteropServices.HandleRef":
2744 + if (self.Namespace == "System") {
2745 + string name = self.Name;
2746 + return ((name == "IntPtr") || (name == "UIntPtr"));
2748 + return self.IsNamed ("System.Runtime.InteropServices", "HandleRef");
2752 diff --git a/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs b/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2753 index 6749ebd..73e03e4 100644
2754 --- a/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2755 +++ b/gendarme/framework/Gendarme.Framework.Rocks/VariableDefinitionRocks.cs
2757 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2760 -using Mono.Cecil.Cil;
2762 +using System.Globalization;
2763 +using Mono.Cecil.Cil;
2765 namespace Gendarme.Framework.Rocks {
2767 @@ -53,7 +54,7 @@ namespace Gendarme.Framework.Rocks {
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);
2776 diff --git a/gendarme/framework/Gendarme.Framework.csproj b/gendarme/framework/Gendarme.Framework.csproj
2777 index f9976af..ff5851b 100755
2778 --- a/gendarme/framework/Gendarme.Framework.csproj
2779 +++ b/gendarme/framework/Gendarme.Framework.csproj
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
2785 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
2786 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
2810 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
2811 <DebugSymbols>true</DebugSymbols>
\r
2813 <ErrorReport>prompt</ErrorReport>
\r
2814 <WarningLevel>3</WarningLevel>
\r
2816 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
2818 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
2819 <DebugType>pdbonly</DebugType>
\r
2821 <ErrorReport>prompt</ErrorReport>
\r
2822 <WarningLevel>4</WarningLevel>
\r
2824 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
2827 <Reference Include="System" />
\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
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
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
2859 + <Install>false</Install>
\r
2860 </BootstrapperPackage>
\r
2861 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
2862 <Visible>False</Visible>
\r
2865 + <Install>false</Install>
\r
2866 </BootstrapperPackage>
\r
2867 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
2868 <Visible>False</Visible>
\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
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
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.
2887 diff --git a/gendarme/framework/Gendarme.Framework/Symbols.cs b/gendarme/framework/Gendarme.Framework/Symbols.cs
2888 index 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;
2895 - private static string AlmostEqualTo = new string (new char [] { '\u2248' });
2896 + private const string AlmostEqualTo = "\u2248";
2898 private static Instruction ExtractFirst (TypeDefinition type)
2900 @@ -55,7 +55,7 @@ namespace Gendarme.Framework {
2902 private static Instruction ExtractFirst (MethodDefinition method)
2904 - if ((method == null) || !method.HasBody)
2905 + if ((method == null) || !method.HasBody || method.Body.Instructions.Count == 0)
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 {
2911 MethodDefinition method = (location as MethodDefinition);
2913 - return (method.DeclaringType as TypeDefinition);
2914 + return method.DeclaringType;
2916 FieldDefinition field = (location as FieldDefinition);
2918 - return (field.DeclaringType as TypeDefinition);
2919 + return field.DeclaringType;
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)
2927 - string sline = (line == PdbHiddenLine) ? "unavailable" : line.ToString ();
2928 + string sline = (line == PdbHiddenLine) ? "unavailable" : line.ToString (CultureInfo.InvariantCulture);
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);
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;
2940 // TypeDefinition, FieldDefinition
2941 diff --git a/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs b/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2942 index e40e34c..4c76f63 100644
2943 --- a/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2944 +++ b/gendarme/framework/Gendarme.Framework/ThreadModelAttribute.cs
2949 +using System.Globalization;
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 ()
2956 if (AllowsEveryCaller)
2957 - return string.Format ("{0} | AllowEveryCaller", Model);
2958 + return String.Format (CultureInfo.InvariantCulture, "{0} | AllowEveryCaller", Model);
2960 return Model.ToString ();
2962 @@ -96,9 +97,9 @@ namespace Gendarme.Framework {
2966 - public bool Equals (ThreadModelAttribute rhs)
2967 + public bool Equals (ThreadModelAttribute other)
2969 - return this == rhs;
2970 + return this == other;
2973 public static bool operator== (ThreadModelAttribute lhs, ThreadModelAttribute rhs)
2974 diff --git a/gendarme/framework/Makefile.am b/gendarme/framework/Makefile.am
2975 index 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)
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)
2994 framework_test_sources = \
2995 @@ -108,14 +109,14 @@ framework_test_sources = \
2996 framework_test_build_sources = $(addprefix $(srcdir)/Test/, $(framework_test_sources))
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)
3004 test: Test.Framework.dll
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
3010 self-test: $(framework_SCRIPTS)
3011 mono --debug ../bin/gendarme.exe $(framework_SCRIPTS)
3012 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/AssemblyRocksTest.cs
3013 index 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 {
3019 [ExpectedException (typeof (ArgumentNullException))]
3020 - public void HasAttribute_Null ()
3021 + public void HasAttribute_Namespace_Null ()
3023 - assembly.HasAttribute (null);
3024 + assembly.HasAttribute (null, "a");
3028 + [ExpectedException (typeof (ArgumentNullException))]
3029 + public void HasAttribute_Name_Null ()
3031 + assembly.HasAttribute ("a", null);
3035 public void HasAttribute ()
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");
3044 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/CustomAttributeRocksTest.cs
3045 index 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 {
3051 [ExpectedException (typeof (ArgumentNullException))]
3052 - public void Contains_Null ()
3054 - Collection<CustomAttribute> cac = new Collection<CustomAttribute> ();
3055 - cac.ContainsType ((string) null);
3059 - public void Contains ()
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");
3068 - [ExpectedException (typeof (ArgumentNullException))]
3069 - public void ContainsAny_Null ()
3071 - Collection<CustomAttribute> cac = new Collection<CustomAttribute> ();
3072 - cac.ContainsAnyType (null);
3076 - public void ContainsAny ()
3077 + public void HasAttribute_Namespace_Null ()
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",
3084 - "System.ICloneable"
3085 - }), "NUnit.Framework.TestFixtureAttribute");
3086 - Assert.IsFalse (cac.ContainsAnyType (new string[] {}), "NUnit.Framework.TestFixture");
3087 + type.HasAttribute (null, "a");
3091 [ExpectedException (typeof (ArgumentNullException))]
3092 - public void HasAttribute_Null ()
3093 + public void HasAttribute_Name_Null ()
3095 TypeDefinition type = assembly.MainModule.GetType ("Test.Framework.Rocks.CustomAttributeRocksTest");
3096 - type.HasAttribute (null);
3097 + type.HasAttribute ("a", null);
3101 public void HasAttribute ()
3103 TypeDefinition type = null;
3104 - Assert.IsFalse (type.HasAttribute ("NUnit.Framework.TestFixtureAttribute"), "null-type");
3105 + Assert.IsFalse (type.HasAttribute ("NUnit.Framework", "TestFixtureAttribute"), "null-type");
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");
3115 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/FieldRocksTest.cs
3116 index 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 {
3122 [ExpectedException (typeof (ArgumentNullException))]
3123 - public void HasAttribute_Null ()
3124 + public void HasAttribute_Namespace_Null ()
3126 - GetField ("assembly").HasAttribute (null);
3127 + GetField ("assembly").HasAttribute (null, "a");
3131 + [ExpectedException (typeof (ArgumentNullException))]
3132 + public void HasAttribute_Name_Null ()
3134 + GetField ("assembly").HasAttribute ("a", null);
3138 public void HasAttribute ()
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");
3147 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/MethodRocksTest.cs
3148 index 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 {
3154 [ExpectedException (typeof (ArgumentNullException))]
3155 - public void HasAttribute_Null ()
3156 + public void HasAttribute_Namespace_Null ()
3158 MethodDefinition method = GetMethod ("FixtureSetUp");
3159 - method.HasAttribute ((string) null);
3160 + method.HasAttribute (null, "a");
3164 + [ExpectedException (typeof (ArgumentNullException))]
3165 + public void HasAttribute_Name_Null ()
3167 + MethodDefinition method = GetMethod ("FixtureSetUp");
3168 + method.HasAttribute ("a", null);
3172 public void HasAttribute ()
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");
3182 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/RocksTest.cs
3183 index 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 () { }
3191 + public abstract class NestedNestedPublicType {
3195 protected abstract class NestedProtectedType {
3196 diff --git a/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs b/gendarme/framework/Test/Gendarme.Framework.Rocks/TypeRocksTest.cs
3197 index 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 {
3203 [ExpectedException (typeof (ArgumentNullException))]
3204 - public void HasAttribute_Null ()
3205 + public void HasAttribute_Namespace_Null ()
3207 - GetType (String.Empty).HasAttribute (null);
3208 + GetType (String.Empty).HasAttribute (null, "a");
3212 + [ExpectedException (typeof (ArgumentNullException))]
3213 + public void HasAttribute_Name_Null ()
3215 + GetType (String.Empty).HasAttribute ("a", null);
3219 public void HasAttribute ()
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");
3235 @@ -204,51 +211,65 @@ namespace Test.Framework.Rocks {
3238 [ExpectedException (typeof (ArgumentNullException))]
3239 - public void Implements_Null ()
3240 + public void Implements_Namespace_Null ()
3242 + GetType (String.Empty).Implements (null, "a");
3246 + [ExpectedException (typeof (ArgumentNullException))]
3247 + public void Implements_Name_Null ()
3249 - GetType (String.Empty).Implements (null);
3250 + GetType (String.Empty).Implements ("a", null);
3254 public void Implements ()
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");
3271 [ExpectedException (typeof (ArgumentNullException))]
3272 - public void Inherits_Null ()
3273 + public void Inherits_Namespace_Null ()
3275 - GetType (String.Empty).Inherits (null);
3276 + GetType (String.Empty).Inherits (null, "a");
3280 + [ExpectedException (typeof (ArgumentNullException))]
3281 + public void Inherits_Name_Null ()
3283 + GetType (String.Empty).Inherits ("a", null);
3287 public void Inherits ()
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");
3300 public void Inherits_FromAnotherAssembly ()
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");
3310 public void Inherits_Itself ()
3312 TypeDefinition type = GetType (String.Empty);
3313 - Assert.IsTrue (type.Inherits (type.FullName), "itself");
3314 + Assert.IsTrue (type.Inherits (type.Namespace, type.Name), "itself");
3318 @@ -322,6 +343,50 @@ namespace Test.Framework.Rocks {
3322 + public void IsNamed ()
3324 + string name = "Test.Framework.Rocks.PublicType";
3325 + TypeDefinition type = assembly.MainModule.GetType (name);
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"));
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"));
3337 + public void IsNamedNestedType ()
3339 + string name = "Test.Framework.Rocks.PublicType/NestedPublicType";
3340 + TypeDefinition type = assembly.MainModule.GetType (name);
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"));
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"));
3350 + Assert.IsFalse (type.IsNamed ("Test.Framework.Rocks", "NestedPublicType"));
3351 + Assert.IsFalse (type.IsNamed ("", "NestedPublicType"));
3355 + public void IsNamedDoubleNestedType ()
3357 + string name = "Test.Framework.Rocks.PublicType/NestedPublicType/NestedNestedPublicType";
3358 + TypeDefinition type = assembly.MainModule.GetType (name);
3360 + Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks.PublicType/NestedPublicType/NestedNestedPublicType"));
3362 + Assert.IsTrue (type.IsNamed ("Test.Framework.Rocks", "PublicType/NestedPublicType/NestedNestedPublicType"));
3366 public void IsVisible ()
3368 string name = "Test.Framework.Rocks.PublicType";
3369 diff --git a/gendarme/man/gendarme.1.in b/gendarme/man/gendarme.1.in
3370 index 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'.
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.
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.
3385 Save the report, formatted as HTML, to the specified file.
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).
3392 .I "--ignore ignore-file"
3393 Do not report defects listed in the specified file.
3395 diff --git a/gendarme/mono-options.ignore b/gendarme/mono-options.ignore
3396 index 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
3403 +R: Gendarme.Rules.Globalization.PreferStringComparisonOverrideRule
3404 +M: System.String NDesk.Options.OptionSet::GetArgumentName(System.Int32,System.Int32,System.String)
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)
3415 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3416 index 3b2ba33..dc43d09 100644
3417 --- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3418 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidAssemblyVersionMismatchRule.cs
3423 +using System.Globalization;
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 {
3431 - static bool VersionTryParse (string input, out Version result)
3434 - if (String.IsNullOrEmpty (input))
3438 - result = new Version (input);
3441 - catch (ArgumentException) {
3442 - // also cover ArgumentOutOfRangeException
3444 - catch (FormatException) {
3446 - catch (OverflowException) {
3451 public RuleResult CheckAssembly (AssemblyDefinition assembly)
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)
3458 - if (ca.AttributeType.FullName != "System.Reflection.AssemblyFileVersionAttribute")
3459 + if (!ca.AttributeType.IsNamed ("System.Reflection", "AssemblyFileVersionAttribute"))
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);
3468 @@ -127,9 +107,11 @@ namespace Gendarme.Rules.BadPractice {
3469 else if (assembly_version.Revision == file_version.Revision)
3470 return RuleResult.Success;
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;
3481 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3482 index 777cc02..87d00c2 100644
3483 --- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3484 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidCallingProblematicMethodsRule.cs
3489 -using System.Reflection;
3490 +using System.Globalization;
3491 using System.Collections.Generic;
3492 +using System.Reflection;
3495 using Mono.Cecil.Cil;
3496 @@ -100,22 +101,22 @@ namespace Gendarme.Rules.BadPractice {
3497 public AvoidCallingProblematicMethodsRule ()
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);
3527 private static bool OperandIsNonPublic (BindingFlags operand)
3528 @@ -166,7 +167,8 @@ namespace Gendarme.Rules.BadPractice {
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);
3538 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs
3539 new file mode 100644
3540 index 0000000..26394d9
3542 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidNullCheckWithAsOperatorRule.cs
3545 +// Gendarme.Rules.BadPractice.AvoidNullCheckWithAsOperatorRule
3548 +// Sebastien Pouliot <sebastien@ximian.com>
3550 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
3560 +// The above copyright notice and this permission notice shall be
3561 +// included in all copies or substantial portions of the Software.
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.
3575 +using Mono.Cecil.Cil;
3577 +using Gendarme.Framework;
3578 +using Gendarme.Framework.Engines;
3579 +using Gendarme.Framework.Helpers;
3580 +using Gendarme.Framework.Rocks;
3582 +namespace Gendarme.Rules.BadPractice {
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.
3592 + /// public string AsString (object obj)
3594 + /// return (o == null) ? null : o as string;
3601 + /// public string AsString (object obj)
3603 + /// return (o as string);
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 {
3613 + OpCodeBitmask mask = new OpCodeBitmask (0x100000, 0x10000000000000, 0x0, 0x0);
3615 + static bool CheckFalseBranch (Instruction ins)
3617 + Instruction next = ins.Next;
3618 + if (!next.Is (ins.Previous.OpCode.Code))
3621 + if (!(ins.Operand as Instruction).Is (Code.Ldnull))
3624 + return CheckIsinst (next.Next);
3627 + static bool CheckTrueBranch (Instruction ins)
3629 + if (!ins.Next.Is (Code.Ldnull))
3632 + Instruction br = (ins.Operand as Instruction);
3633 + if (ins.Previous.OpCode.Code != br.OpCode.Code)
3636 + return CheckIsinst (br.Next);
3639 + static bool CheckIsinst (Instruction ins)
3641 + if (!ins.Is (Code.Isinst))
3643 + return (ins.Next.OpCode.FlowControl != FlowControl.Cond_Branch);
3646 + public RuleResult CheckMethod (MethodDefinition method)
3648 + // rule only applies to methods with IL...
3649 + if (!method.HasBody)
3650 + return RuleResult.DoesNotApply;
3652 + // and when the IL contains both a isinst and ldnull
3653 + if (!mask.IsSubsetOf (OpCodeEngine.GetBitmask (method)))
3654 + return RuleResult.DoesNotApply;
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);
3663 + case Code.Brtrue_S:
3665 + detected = CheckTrueBranch (ins);
3669 + Runner.Report (method, ins, Severity.Medium, Confidence.Normal);
3672 + return Runner.CurrentRuleResult;
3675 + public void Bitmask ()
3677 + OpCodeBitmask mask = new OpCodeBitmask ();
3678 + mask.Set (Code.Isinst);
3679 + mask.Set (Code.Ldnull);
3680 + Console.WriteLine (mask);
3685 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3686 index 0831682..c18be47 100644
3687 --- a/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3688 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/AvoidVisibleConstantFieldRule.cs
3690 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3693 +using System.Globalization;
3696 using Mono.Cecil.Cil;
3698 @@ -80,11 +82,12 @@ namespace Gendarme.Rules.BadPractice {
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"))
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);
3714 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewExceptionWithoutThrowingRule.cs
3715 index 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 {
3720 MethodReference constructor = (MethodReference) ins.Operand;
3722 - if (!constructor.DeclaringType.Inherits ("System.Exception"))
3723 + if (!constructor.DeclaringType.Inherits ("System", "Exception"))
3726 // quick check to save resources
3727 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CheckNewThreadWithoutStartRule.cs
3728 index 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 {
3735 - private const string Thread = "System.Threading.Thread";
3737 public override void Initialize (IRunner runner)
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");
3753 @@ -141,11 +141,11 @@ namespace Gendarme.Rules.BadPractice {
3755 MethodReference constructor = (MethodReference) ins.Operand;
3757 - if (constructor.DeclaringType.FullName != Thread)
3758 + if (!constructor.DeclaringType.IsNamed ("System.Threading", "Thread"))
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"))
3767 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/CloneMethodShouldNotReturnNullRule.cs
3768 index 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 {
3775 - private const string ICloneable = "System.ICloneable";
3777 public override void Initialize (IRunner runner)
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");
3793 @@ -90,7 +90,7 @@ namespace Gendarme.Rules.BadPractice {
3794 return RuleResult.DoesNotApply;
3796 // where the type implements ICloneable
3797 - if (!method.DeclaringType.Implements (ICloneable))
3798 + if (!method.DeclaringType.Implements ("System", "ICloneable"))
3799 return RuleResult.DoesNotApply;
3801 // call base class to detect if the method can return null
3802 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3803 index d3758bb..7f47cf5 100644
3804 --- a/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3805 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/ConstructorShouldNotCallVirtualMethodsRule.cs
3809 using System.Collections.Generic;
3810 +using System.Globalization;
3814 @@ -177,7 +178,7 @@ namespace Gendarme.Rules.BadPractice {
3817 parameters += mr.Parameters.Count;
3818 - if (mr.ReturnType.FullName != "System.Void")
3819 + if (!mr.ReturnType.IsNamed ("System", "Void"))
3823 @@ -196,7 +197,7 @@ namespace Gendarme.Rules.BadPractice {
3824 if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
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))
3832 @@ -216,12 +217,14 @@ namespace Gendarme.Rules.BadPractice {
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))
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);
3848 stack.Push (method_name);
3849 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DisableDebuggingCodeRule.cs
3850 index 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 {
3857 - private const string ConditionalAttribute = "System.Diagnostics.ConditionalAttribute";
3858 - private const string Console = "System.Console";
3860 // note: there can be multiple [Conditional] attribute on a method
3861 private static bool HasConditionalAttributeForDebugging (IList<CustomAttribute> cac)
3863 @@ -101,7 +98,7 @@ namespace Gendarme.Rules.BadPractice {
3864 // any attribute without arguments can be skipped
3865 if (!ca.HasConstructorArguments)
3867 - if (ca.AttributeType.FullName == ConditionalAttribute) {
3868 + if (ca.AttributeType.IsNamed ("System.Diagnostics", "ConditionalAttribute")) {
3869 switch (ca.ConstructorArguments [0].Value as string) {
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");
3883 @@ -152,8 +151,12 @@ namespace Gendarme.Rules.BadPractice {
3886 // ... to System.Console ...
3887 - MethodReference mr = (ins.Operand as MethodReference);
3888 - if (mr.DeclaringType.FullName != Console)
3889 + MethodReference mr = ins.Operand as MethodReference;
3894 + if (!mr.DeclaringType.IsNamed ("System", "Console"))
3897 // ... Write* methods
3898 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs
3899 new file mode 100644
3900 index 0000000..4b387df
3902 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotDecreaseVisibilityRule.cs
3905 +// Gendarme.Rules.BadPractice.DoNotDecreaseVisibilityRule
3908 +// Sebastien Pouliot <sebastien@ximian.com>
3910 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
3919 +// The above copyright notice and this permission notice shall be included in
3920 +// all copies or substantial portions of the Software.
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
3932 +using Gendarme.Framework;
3933 +using Gendarme.Framework.Rocks;
3935 +namespace Gendarme.Rules.BadPractice {
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>.
3946 + /// public class Base {
3947 + /// public void Public ()
3952 + /// public class BadInheritor : Base {
3953 + /// private new void Public ()
3960 + /// Good example (do not hide):
3962 + /// public class Inheritor : Base {
3967 + /// Good example (sealed type):
3969 + /// public sealed class Inheritor : Base {
3970 + /// private new void Public ()
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 {
3981 + static bool IsHiding (MethodDefinition method, TypeReference type)
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)
3992 + if (name != md.Name)
3994 + if (method.CompareSignature (md))
3999 + return IsHiding (method, type.DeclaringType);
4002 + public RuleResult CheckMethod (MethodDefinition method)
4004 + if (!method.IsPrivate || method.IsFinal)
4005 + return RuleResult.DoesNotApply;
4007 + TypeDefinition type = method.DeclaringType;
4008 + if (type.IsSealed)
4009 + return RuleResult.DoesNotApply;
4011 + // we got a private, non-final, method in an unsealed type
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;
4018 + // are we're hiding something ?
4019 + if (method.IsHideBySig && !IsHiding (method, type.BaseType))
4020 + return RuleResult.Success;
4022 + Runner.Report (method, Severity.High, Confidence.Normal);
4023 + return RuleResult.Failure;
4028 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotForgetNotImplementedMethodsRule.cs
4029 index 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)
4035 MethodReference ctor = (MethodReference) inst.Operand;
4036 - if ("System.NotImplementedException" != ctor.DeclaringType.FullName)
4037 + if (!ctor.DeclaringType.IsNamed ("System", "NotImplementedException"))
4039 if (inst.Next.OpCode.Code != Code.Throw)
4041 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseEnumIsAssignableFromRule.cs
4042 index 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 {
4049 - return type.FullName == "System.Enum";
4050 + return type.IsNamed ("System", "Enum");
4053 static bool IsCallToTypeIsAssignableFrom (Instruction instruction)
4054 @@ -124,10 +124,7 @@ namespace Gendarme.Rules.BadPractice {
4055 if (operand.Name != name)
4058 - if (operand.DeclaringType.FullName != "System.Type")
4062 + return operand.DeclaringType.IsNamed ("System", "Type");
4065 static bool IsCall (OpCode opcode)
4066 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/DoNotUseGetInterfaceToCheckAssignabilityRule.cs
4067 index 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")
4074 - if (!call.DeclaringType.Inherits ("System.Type")) // not a sealed type
4075 + if (!call.DeclaringType.Inherits ("System", "Type")) // not a sealed type
4078 // check for a null compare
4079 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj b/gendarme/rules/Gendarme.Rules.BadPractice/Gendarme.Rules.BadPractice.csproj
4080 index 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
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
4088 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
4089 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
4118 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
4119 <DebugSymbols>true</DebugSymbols>
\r
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
4126 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
4127 <DebugType>pdbonly</DebugType>
\r
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
4135 <Reference Include="System" />
\r
4137 <Name>Gendarme.Framework</Name>
\r
4138 </ProjectReference>
\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
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.
4160 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/GetEntryAssemblyMayReturnNullRule.cs
4161 index 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 {
4168 - private const string Assembly = "System.Reflection.Assembly";
4170 public override void Initialize (IRunner runner)
4172 base.Initialize (runner);
4173 @@ -81,13 +79,20 @@ namespace Gendarme.Rules.BadPractice {
4174 // GetEntryAssembly will work inside executables
4175 e.CurrentAssembly.EntryPoint == null &&
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);
4189 + static bool IsGetEntryAssembly (MemberReference method)
4191 + return method.IsNamed ("System.Reflection", "Assembly", "GetEntryAssembly");
4194 public RuleResult CheckMethod (MethodDefinition method)
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) {
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);
4206 + if (IsGetEntryAssembly (current.Operand as MethodReference))
4207 + Runner.Report (method, current, Severity.Medium, Confidence.Total);
4211 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am b/gendarme/rules/Gendarme.Rules.BadPractice/Makefile.am
4212 index 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
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 = \
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 \
4246 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/ObsoleteMessagesShouldNotBeEmptyRule.cs
4247 index 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 {
4254 - private const string ObsoleteAttribute = "System.ObsoleteAttribute";
4256 public override void Initialize (IRunner runner)
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");
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"))
4280 // note: we don't have to check fields since they cannot be used
4281 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/OnlyUseDisposeForIDisposableTypesRule.cs
4282 index 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 {
4287 Log.WriteLine (this);
4288 Log.WriteLine (this, "----------------------------------");
4289 - Log.WriteLine (this, type.FullName);
4290 + Log.WriteLine (this, type);
4292 - if (!type.Implements ("System.IDisposable")) {
4293 + if (!type.Implements ("System", "IDisposable")) {
4294 Log.WriteLine (this, "type does not implement IDisposable");
4296 foreach (MethodDefinition method in type.Methods.Where (m => m.Name == "Dispose"))
4297 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4298 index 5c16da9..c6cbebc 100644
4299 --- a/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4300 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/PreferEmptyInstanceOverNullRule.cs
4305 +using System.Globalization;
4308 using Mono.Cecil.Cil;
4309 @@ -146,9 +147,9 @@ namespace Gendarme.Rules.BadPractice {
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");
4319 if (!string_return_type && !array_return_type && !ienumerable_return_type)
4320 return RuleResult.DoesNotApply;
4321 @@ -158,7 +159,7 @@ namespace Gendarme.Rules.BadPractice {
4323 protected override void Report (MethodDefinition method, Instruction ins)
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);
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";
4339 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferParamsArrayForVariableArgumentsRule.cs
4340 index 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 {
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");
4354 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferSafeHandleRule.cs
4355 index 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)
4361 foreach (FieldDefinition field in type.Fields) {
4362 - string name = field.FieldType.FullName;
4363 - if (name == "System.IntPtr" || name == "System.UIntPtr")
4365 + TypeReference ftype = field.FieldType;
4366 + if (ftype.Namespace == "System") {
4367 + string name = ftype.Name;
4368 + if ((name == "IntPtr") || (name == "UIntPtr"))
4374 @@ -212,7 +215,7 @@ namespace Gendarme.Rules.BadPractice {
4376 Log.WriteLine (this);
4377 Log.WriteLine (this, "----------------------------------");
4378 - Log.WriteLine (this, type.FullName);
4379 + Log.WriteLine (this, type);
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
4387 - if (type.Implements ("System.IDisposable"))
4388 + if (type.Implements ("System", "IDisposable"))
4389 confidence = (Confidence) ((int) confidence - 1);
4391 Log.WriteLine (this, "'{0}' is an IntPtr.", field.Name);
4392 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/PreferTryParseRule.cs
4393 index 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)
4399 bool present = false;
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))
4408 - if (!HasTryParseMethod (mr.DeclaringType.Resolve ()))
4409 + TypeDefinition declaringType = mr.DeclaringType.Resolve();
4410 + if (declaringType != null && !HasTryParseMethod(declaringType))
4413 // if inside a try (catch/finally) block then...
4414 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/README.md b/gendarme/rules/Gendarme.Rules.BadPractice/README.md
4415 new file mode 100644
4416 index 0000000..dc0fb44
4418 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/README.md
4420 +# Gendarme.Rules.BadPractice Rules
4422 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.BadPractice(git)]] pages.
4427 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
4429 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs b/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs
4430 new file mode 100644
4431 index 0000000..65f9d50
4433 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/Test/AvoidNullCheckWithAsOperatorTest.cs
4436 +// Unit Tests for AvoidNullCheckWithAsOperatorRule
4439 +// Sebastien Pouliot <sebastien@ximian.com>
4441 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
4451 +// The above copyright notice and this permission notice shall be
4452 +// included in all copies or substantial portions of the Software.
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.
4464 +using Gendarme.Rules.BadPractice;
4466 +using NUnit.Framework;
4467 +using Test.Rules.Definitions;
4468 +using Test.Rules.Fixtures;
4470 +namespace Test.Rules.BadPractice {
4473 + public class AvoidNullCheckWithAsOperatorTest : MethodRuleTestFixture<AvoidNullCheckWithAsOperatorRule> {
4475 + string AsString_Bad1a (object obj)
4477 + return obj == null ? null : obj as string;
4480 + string AsString_Bad1b (object obj)
4483 + return obj as string;
4487 + string AsString_Bad2a (object obj)
4489 + return obj != null ? obj as string : null;
4492 + string AsString_Bad2b (object obj)
4496 + return obj as string;
4499 + string AsString_Good (object obj)
4501 + return obj as string;
4504 + string AsString_Good2 (string message, object obj)
4506 + if (message == null)
4507 + throw new ArgumentNullException ("message");
4508 + Console.WriteLine (message);
4509 + return obj as string;
4512 + string AsString_Good3 (string message, object obj)
4514 + if (message == null)
4516 + Console.WriteLine (message);
4517 + return obj as string;
4520 + void LocalsBad1a ()
4523 + string a = o == null ? null : o as string;
4524 + Console.WriteLine (a);
4527 + void LocalsBad2a ()
4530 + string a = o != null ? o as string : null;
4531 + Console.WriteLine (a);
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)
4538 + if (value == null)
4541 + if (value is Type || value is SimpleMethods)
4544 + return value.ToString ();
4548 + public void DoesNotApply ()
4550 + AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
4551 + AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
4552 + // no ldnull instruction
4553 + AssertRuleDoesNotApply<AvoidNullCheckWithAsOperatorTest> ("AsString_Good");
4554 + AssertRuleDoesNotApply<AvoidNullCheckWithAsOperatorTest> ("AsString_Good2");
4558 + public void Success ()
4560 + AssertRuleSuccess<AvoidNullCheckWithAsOperatorTest> ("AsString_Good3");
4561 + AssertRuleSuccess<AvoidNullCheckWithAsOperatorTest> ("ConvertValue");
4565 + public void Failure ()
4567 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad1a");
4568 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad1b");
4569 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad2a");
4570 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("AsString_Bad2b");
4572 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("LocalsBad1a");
4573 + AssertRuleFailure<AvoidNullCheckWithAsOperatorTest> ("LocalsBad2a");
4577 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs b/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs
4578 new file mode 100644
4579 index 0000000..9bafda7
4581 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/Test/DoNotDecreaseVisibilityTest.cs
4584 +// Tests.Rules.BadPractice.DoNotDecreaseVisibilityTest
4587 +// Sebastien Pouliot <sebastien@ximian.com>
4589 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
4598 +// The above copyright notice and this permission notice shall be included in
4599 +// all copies or substantial portions of the Software.
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
4612 +using Gendarme.Rules.BadPractice ;
4614 +using NUnit.Framework;
4615 +using Test.Rules.Fixtures;
4616 +using Test.Rules.Helpers;
4617 +using Test.Rules.Definitions;
4619 +namespace Test.Rules.BadPractice {
4622 + public class DoNotDecreaseVisibilityTest : MethodRuleTestFixture<DoNotDecreaseVisibilityRule> {
4624 + public class TestCase {
4626 + public class Base {
4627 + public void Public ()
4631 + protected bool Protected (int x)
4636 + internal int Internal ()
4641 + private float Private (float f)
4647 + public class BadInheritor : Base {
4648 + private new void Public ()
4652 + private new bool Protected (int x)
4657 + private new int Internal ()
4662 + private new float Private (float f)
4668 + public class NoInheritance {
4669 + private new void Public ()
4673 + private new bool Protected (int x)
4678 + private new int Internal ()
4683 + private new float Private (float f)
4689 + // c# cannot seal the method without making it an override
4690 + // and an override cannot change visibility
4692 + public class FinalInheritor : Base {
4693 + private new sealed void Public ()
4697 + private new sealed bool Protected (int x)
4702 + private new sealed int Internal ()
4707 + private new float Private (float f)
4713 + public sealed class Sealed : Base {
4714 + private new void Public ()
4718 + private new bool Protected (int x)
4723 + private new int Internal ()
4728 + private new float Private (float f)
4734 + public class StaticCtor {
4735 + static StaticCtor ()
4740 + public class StaticCtorInheritor : StaticCtor {
4741 + static StaticCtorInheritor ()
4748 + public void DoesNotApply ()
4751 + AssertRuleDoesNotApply<TestCase.Base> ("Public");
4752 + AssertRuleDoesNotApply<TestCase.Base> ("Protected");
4753 + AssertRuleDoesNotApply<TestCase.Base> ("Internal");
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");
4762 + AssertRuleDoesNotApply<TestCase.Sealed> ("Public");
4763 + AssertRuleDoesNotApply<TestCase.Sealed> ("Protected");
4764 + AssertRuleDoesNotApply<TestCase.Sealed> ("Internal");
4765 + AssertRuleDoesNotApply<TestCase.Sealed> ("Private");
4769 + public void Good ()
4771 + AssertRuleSuccess<TestCase.Base> ("Private");
4773 + AssertRuleSuccess<TestCase.NoInheritance> ("Public");
4774 + AssertRuleSuccess<TestCase.NoInheritance> ("Protected");
4775 + AssertRuleSuccess<TestCase.NoInheritance> ("Internal");
4776 + AssertRuleSuccess<TestCase.NoInheritance> ("Private");
4778 + AssertRuleSuccess<TestCase.BadInheritor> ("Internal");
4779 + AssertRuleSuccess<TestCase.BadInheritor> ("Private");
4781 + AssertRuleSuccess<TestCase.StaticCtor> (".cctor");
4782 + AssertRuleSuccess<TestCase.StaticCtorInheritor> (".cctor");
4786 + public void Bad ()
4788 + AssertRuleFailure<TestCase.BadInheritor> ("Public");
4789 + AssertRuleFailure<TestCase.BadInheritor> ("Protected");
4793 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj b/gendarme/rules/Gendarme.Rules.BadPractice/Test/Tests.Rules.BadPractice.csproj
4794 index 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
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
4802 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
4803 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
4832 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
4833 <DebugSymbols>true</DebugSymbols>
\r
4835 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
4836 <ErrorReport>prompt</ErrorReport>
\r
4837 <WarningLevel>4</WarningLevel>
\r
4838 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
4840 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
4841 <DebugType>pdbonly</DebugType>
\r
4843 <DefineConstants>TRACE</DefineConstants>
\r
4844 <ErrorReport>prompt</ErrorReport>
\r
4845 <WarningLevel>4</WarningLevel>
\r
4846 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
4849 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
4852 <Folder Include="Properties\" />
\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
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.
4874 diff --git a/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs b/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4875 index 655298f..2c8be6f 100644
4876 --- a/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4877 +++ b/gendarme/rules/Gendarme.Rules.BadPractice/UseFileOpenOnlyWithFileAccessRule.cs
4881 using System.Collections.Generic;
4882 +using System.Globalization;
4885 using Mono.Cecil.Cil;
4886 @@ -68,9 +69,19 @@ namespace Gendarme.Rules.BadPractice {
4887 [EngineDependency (typeof (OpCodeEngine))]
4888 public class UseFileOpenOnlyWithFileAccessRule : Rule, IMethodRule {
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)
4895 + base.Initialize (runner);
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");
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;
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);
4932 return Runner.CurrentRuleResult;
4933 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DecorateThreadsRule.cs
4934 index 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;
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);
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 ()
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);
4976 @@ -299,7 +303,7 @@ namespace Gendarme.Rules.Concurrency {
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);
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) {
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);
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);
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}.",
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);
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);
5029 + string mesg = String.Format (CultureInfo.InvariantCulture,
5030 + "{0} delegate cannot be bound to {1} {2} method.",
5031 + callerModel, targetModel, target.Name);
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);
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;
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);
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"))
5067 @@ -523,7 +531,8 @@ namespace Gendarme.Rules.Concurrency {
5068 anonymous_entry_points.Add (method);
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);
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);
5086 Log.WriteLine (this, "Defect: {0}", mesg);
5087 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5088 index 2ddb7ac..7c91ad5 100644
5089 --- a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5090 +++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnThisOrTypesRule.cs
5095 +using System.Globalization;
5098 using Mono.Cecil.Cil;
5099 @@ -108,23 +109,26 @@ namespace Gendarme.Rules.Concurrency {
5101 switch (ins.OpCode.Code) {
5104 + if (!method.IsStatic)
5109 - ParameterDefinition pd = (ins.Operand as ParameterDefinition);
5110 - if ((pd == null) || (pd.GetSequence () != 0))
5112 + if (!method.IsStatic) {
5113 + ParameterDefinition pd = (ins.Operand as ParameterDefinition);
5114 + if ((pd == null) || (pd.Index == 0))
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;
5125 if ((mr.Name == "GetTypeFromHandle") && (mr.DeclaringType.Name == "Type")) {
5127 - msg = String.Format (LockType, (ins.Previous.Operand as TypeReference).Name);
5128 + msg = String.Format (CultureInfo.InvariantCulture, LockType, (ins.Previous.Operand as TypeReference).Name);
5130 msg = mr.ToString ();
5132 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5133 index fe730aa..57c3b84 100644
5134 --- a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5135 +++ b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotLockOnWeakIdentityObjectsRule.cs
5140 +using System.Globalization;
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 {
5148 - private static string [] unsealed_types = new string[] {
5149 - "System.MarshalByRefObject",
5150 - "System.OutOfMemoryException",
5151 - "System.Reflection.MemberInfo",
5152 - "System.Reflection.ParameterInfo"
5154 + static bool IsWeakSealedType (TypeReference type)
5156 + switch (type.Namespace) {
5158 + string name = type.Name;
5159 + return ((name == "String") || (name == "ExecutionEngineException") || (name == "StackOverflowException"));
5160 + case "System.Threading":
5161 + return (type.Name == "Thread");
5167 + static string InheritFromWeakType (TypeReference type, string nameSpace, string name)
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);
5175 public override void Analyze (MethodDefinition method, MethodReference enter, Instruction ins)
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 {
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);
5200 - foreach (string unsealed in unsealed_types) {
5201 - if (!type.Inherits (unsealed))
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 ());
5208 + string msg = InheritFromWeakType (type, "System", "MarshalByRefObject");
5209 + if (msg.Length > 0) {
5210 + Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5213 + msg = InheritFromWeakType (type, "System", "OutOfMemoryException");
5214 + if (msg.Length > 0) {
5215 + Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5218 + msg = InheritFromWeakType (type, "System.Reflection", "MemberInfo");
5219 + if (msg.Length > 0) {
5220 + Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5223 + msg = InheritFromWeakType (type, "System.Reflection", "ParameterInfo");
5224 + if (msg.Length > 0) {
5225 Runner.Report (method, call, Severity.High, Confidence.Normal, msg);
5231 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoNotUseThreadStaticWithInstanceFieldsRule.cs
5232 index 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 {
5239 - private const string ThreadStaticAttribute = "System.ThreadStaticAttribute";
5241 public RuleResult CheckType (TypeDefinition type)
5243 if (!type.HasFields || type.IsEnum)
5244 return RuleResult.DoesNotApply;
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);
5252 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DontUseLockedRegionOutsideMethodRule.cs
5253 index 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);
5263 /// Monitor.Exit (mutex);
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");
5279 @@ -157,9 +160,9 @@ namespace Gendarme.Rules.Concurrency {
5283 - if (IsMonitorMethod (m, "Enter")) {
5284 + if (m.IsNamed ("System.Threading", "Monitor", "Enter")) {
5286 - } else if (IsMonitorMethod (m, "Exit")) {
5287 + } else if (m.IsNamed ("System.Threading", "Monitor", "Exit")) {
5291 @@ -170,13 +173,5 @@ namespace Gendarme.Rules.Concurrency {
5292 Runner.Report (method, Severity.High, Confidence.Normal);
5293 return RuleResult.Failure;
5296 - //FIXME: copied from DoubleCheckLockingRule, we need to share this
5297 - private static bool IsMonitorMethod (MemberReference method, string methodName)
5299 - if (method.Name != methodName)
5301 - return (method.DeclaringType.FullName == "System.Threading.Monitor");
5305 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/DoubleCheckLockingRule.cs
5306 index 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");
5320 @@ -213,7 +215,7 @@ namespace Gendarme.Rules.Concurrency {
5322 if (method.Name != methodName)
5324 - if (method.DeclaringType.FullName != "System.Threading.Monitor")
5325 + if (!method.DeclaringType.IsNamed ("System.Threading", "Monitor"))
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.
5329 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj b/gendarme/rules/Gendarme.Rules.Concurrency/Gendarme.Rules.Concurrency.csproj
5330 index 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
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
5338 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
5339 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
5363 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
5364 <DebugSymbols>true</DebugSymbols>
\r
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
5371 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
5372 <DebugType>pdbonly</DebugType>
\r
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
5380 <Reference Include="System" />
\r
5382 <None Include="ChangeLog" />
\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
5394 + <Install>false</Install>
\r
5395 </BootstrapperPackage>
\r
5396 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
5397 <Visible>False</Visible>
\r
5400 + <Install>false</Install>
\r
5401 </BootstrapperPackage>
\r
5402 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
5403 <Visible>False</Visible>
\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
5414 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
5415 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/LockAnalyzerRule.cs
5416 index 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");
5432 @@ -68,14 +70,8 @@ namespace Gendarme.Rules.Concurrency {
5434 foreach (Instruction ins in method.Body.Instructions) {
5435 MethodReference mr = ins.GetMethod ();
5438 - if (mr.DeclaringType.FullName != "System.Threading.Monitor")
5440 - if (mr.Name != "Enter")
5443 - Analyze (method, mr, ins);
5444 + if (mr.IsNamed ("System.Threading", "Monitor", "Enter"))
5445 + Analyze (method, mr, ins);
5447 return Runner.CurrentRuleResult;
5449 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5450 index e614973..843c9b8 100644
5451 --- a/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5452 +++ b/gendarme/rules/Gendarme.Rules.Concurrency/ProtectCallToEventDelegatesRule.cs
5457 +using System.Globalization;
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);
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);
5477 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/README.md b/gendarme/rules/Gendarme.Rules.Concurrency/README.md
5478 new file mode 100644
5479 index 0000000..3da4dc8
5481 +++ b/gendarme/rules/Gendarme.Rules.Concurrency/README.md
5483 +# Gendarme.Rules.Concurrency Rules
5485 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Concurrency(git)]] pages.
5490 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
5492 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ReviewLockUsedOnlyForOperationsOnVariablesRule.cs
5493 index 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");
5509 @@ -154,9 +156,7 @@ namespace Gendarme.Rules.Concurrency {
5512 MethodReference method = (ins.Operand as MethodReference);
5513 - if (method == null)
5515 - if ((method.Name != "Enter") || (method.DeclaringType.FullName != "System.Threading.Monitor"))
5516 + if (!method.IsNamed ("System.Threading", "Monitor", "Enter"))
5518 return (parametersCount == method.Parameters.Count);
5520 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs b/gendarme/rules/Gendarme.Rules.Concurrency/Test/DoNotLockOnThisOrTypesTest.cs
5521 index 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 {
5528 + static bool TryEnter (object obj)
5531 + Console.WriteLine ();
5537 public void StaticType ()
5539 AssertRuleFailure<DoNotLockOnThisOrTypesTest> ("StaticLockType", 1);
5540 AssertRuleFailure<DoNotLockOnThisOrTypesTest> ("StaticLockTypes", 2);
5541 + AssertRuleSuccess<DoNotLockOnThisOrTypesTest> ("TryEnter");
5544 object instance_locker = new object ();
5545 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj b/gendarme/rules/Gendarme.Rules.Concurrency/Test/Tests.Rules.Concurrency.csproj
5546 index 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
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
5554 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
5555 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
5579 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
5580 <DebugSymbols>true</DebugSymbols>
\r
5582 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
5583 <ErrorReport>prompt</ErrorReport>
\r
5584 <WarningLevel>4</WarningLevel>
\r
5585 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
5587 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
5588 <DebugType>pdbonly</DebugType>
\r
5590 <DefineConstants>TRACE</DefineConstants>
\r
5591 <ErrorReport>prompt</ErrorReport>
\r
5592 <WarningLevel>4</WarningLevel>
\r
5593 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
5596 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
5598 </ProjectReference>
\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
5610 + <Install>false</Install>
\r
5611 </BootstrapperPackage>
\r
5612 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
5613 <Visible>False</Visible>
\r
5616 + <Install>false</Install>
\r
5617 </BootstrapperPackage>
\r
5618 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
5619 <Visible>False</Visible>
\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
5630 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
5631 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs b/gendarme/rules/Gendarme.Rules.Concurrency/ThreadRocks.cs
5632 index 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 {
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;
5644 diff --git a/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs b/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5645 index 686855d..9fa400f 100644
5646 --- a/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5647 +++ b/gendarme/rules/Gendarme.Rules.Concurrency/WriteStaticFieldFromInstanceMethodRule.cs
5652 +using System.Globalization;
5655 using Mono.Cecil.Cil;
5656 @@ -76,8 +77,6 @@ namespace Gendarme.Rules.Concurrency {
5657 [EngineDependency (typeof (OpCodeEngine))]
5658 public class WriteStaticFieldFromInstanceMethodRule : Rule, IMethodRule {
5660 - private const string ThreadStaticAttribute = "System.ThreadStaticAttribute";
5662 static bool CheckField (FieldReference field)
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"))
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);
5685 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5686 index d13758b..d75246e 100644
5687 --- a/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5688 +++ b/gendarme/rules/Gendarme.Rules.Correctness/AttributeStringLiteralsShouldParseCorrectlyRule.cs
5691 using System.Collections;
5692 using System.Collections.Generic;
5693 +using System.Globalization;
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;
5701 - // FIXME : FX4 Version.TryParse @ http://msdn.microsoft.com/en-us/library/system.version.tryparse.aspx
5702 - static bool TryParseVersion (string version)
5705 - new Version (version);
5708 - catch (FormatException) {
5711 - catch (ArgumentException) {
5716 - // FIXME : FX4 Guid.TryParse @ http://msdn.microsoft.com/en-us/library/system.guid.tryparse.aspx
5717 - static bool TryParseGuid (string guid)
5723 - catch (FormatException) {
5728 void CheckParametersAndValues (IMetadataTokenProvider provider, IMethodSignature constructor, IList<CustomAttributeArgument> arguments)
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")) {
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);
5745 @@ -125,14 +100,15 @@ namespace Gendarme.Rules.Correctness {
5746 Contains (parameter.Name, "urn")) {
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);
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);
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);
5764 @@ -203,3 +179,4 @@ namespace Gendarme.Rules.Correctness {
5769 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidCodeWithSideEffectsInConditionalCodeRule.cs
5770 index 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;
5776 using System.Collections.Generic;
5777 +using System.Globalization;
5779 namespace Gendarme.Rules.Correctness {
5781 @@ -114,7 +115,8 @@ namespace Gendarme.Rules.Correctness {
5783 string name = Mutates (method, ins);
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);
5791 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidConstructorsInStaticTypesRule.cs
5792 index 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 {
5799 - if (type.BaseType.FullName == "System.Object")
5800 + if (type.BaseType.IsNamed ("System", "Object"))
5803 return IsAllStatic (type.BaseType.Resolve ());
5804 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidFloatingPointEqualityRule.cs
5805 index 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 {
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);
5817 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/AvoidMethodsWithSideEffectsInConditionalCodeRule.cs
5818 index 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;
5824 using System.Collections.Generic;
5825 +using System.Globalization;
5827 namespace Gendarme.Rules.Correctness {
5829 @@ -157,7 +158,8 @@ namespace Gendarme.Rules.Correctness {
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);
5839 @@ -207,7 +209,7 @@ namespace Gendarme.Rules.Correctness {
5840 if (!attr.HasConstructorArguments)
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;
5848 @@ -258,7 +260,7 @@ namespace Gendarme.Rules.Correctness {
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;
5857 @@ -274,7 +276,7 @@ namespace Gendarme.Rules.Correctness {
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")
5865 // Contract methods (skip namespace)
5866 @@ -282,10 +284,10 @@ namespace Gendarme.Rules.Correctness {
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))
5874 - if (type_name.StartsWith ("System.Comparison`1"))
5875 + if (type_name.StartsWith ("System.Comparison`1", StringComparison.Ordinal))
5878 // delegate invocation
5879 @@ -317,7 +319,7 @@ namespace Gendarme.Rules.Correctness {
5880 static bool HasPureAttribute (IList<CustomAttribute> attrs)
5882 foreach (CustomAttribute attr in attrs) {
5883 - if (attr.AttributeType.FullName.Contains ("PureAttribute")) {
5884 + if (attr.AttributeType.Name == "PureAttribute") {
5888 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/BadRecursiveInvocationRule.cs
5889 index 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)
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))
5904 @@ -134,7 +133,7 @@ namespace Gendarme.Rules.Correctness {
5905 ParameterDefinition param = (ParameterDefinition) insn.Operand;
5906 if (method.IsStatic)
5908 - return (param.GetSequence () == paramNum);
5909 + return (param.Index == paramNum - 1);
5913 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/CheckParametersNullityInVisibleMethodsRule.cs
5914 index 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)
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)
5928 // was there a null check done before ?
5929 @@ -146,7 +146,7 @@ namespace Gendarme.Rules.Correctness {
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))
5937 Instruction next = ins.Next;
5938 @@ -158,21 +158,21 @@ namespace Gendarme.Rules.Correctness {
5939 nc = next.OpCode.Code;
5942 - has_null_check.Set (parameter.GetSequence ());
5943 + has_null_check.Set (parameter.Index);
5947 if (null_compare.Get (nc)) {
5948 - has_null_check.Set (parameter.GetSequence ());
5949 + has_null_check.Set (parameter.Index);
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);
5964 @@ -204,7 +204,7 @@ namespace Gendarme.Rules.Correctness {
5966 ParameterDefinition p = pi.GetParameter (method);
5968 - has_null_check.Set (p.GetSequence ());
5969 + has_null_check.Set (p.Index);
5973 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
5974 new file mode 100644
5975 index 0000000..442572e
5977 +++ b/gendarme/rules/Gendarme.Rules.Correctness/DeclareEventsExplicitlyRule.cs
5980 +// Gendarme.Rules.Correctness.DeclareEventsExplicitlyRule
5983 +// Sebastien Pouliot <sebastien@ximian.com>
5985 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
5995 +// The above copyright notice and this permission notice shall be
5996 +// included in all copies or substantial portions of the Software.
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.
6009 +using Gendarme.Framework;
6011 +namespace Gendarme.Rules.Correctness {
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.
6021 + /// public class EventLess {
6022 + /// public static EventHandler<EventArgs> MyEvent;
6029 + /// public class Event {
6030 + /// public static event EventHandler<EventArgs> MyEvent;
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 {
6039 + static bool LookForEvent (MemberReference field, TypeDefinition type)
6041 + string fname = field.Name;
6042 + foreach (EventDefinition evnt in type.Events) {
6043 + if (fname == evnt.Name)
6049 + public RuleResult CheckType (TypeDefinition type)
6051 + if (!type.HasFields || type.IsEnum)
6052 + return RuleResult.DoesNotApply;
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")
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);
6071 + return Runner.CurrentRuleResult;
6075 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6076 index 576fff2..7152176 100644
6077 --- a/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6078 +++ b/gendarme/rules/Gendarme.Rules.Correctness/DisposableFieldsShouldBeDisposedRule.cs
6082 using System.Collections.Generic;
6083 +using System.Globalization;
6086 using Mono.Cecil.Cil;
6087 @@ -116,7 +117,7 @@ namespace Gendarme.Rules.Correctness {
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;
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)
6100 - if (fieldType.Implements ("System.IDisposable"))
6101 + if (fieldType.Implements ("System", "IDisposable"))
6102 disposeableFields.Add (field);
6105 @@ -177,10 +178,10 @@ namespace Gendarme.Rules.Correctness {
6106 private void CheckBaseDispose (TypeDefinition type, MethodDefinition implicitDisposeMethod, MethodDefinition explicitDisposeMethod)
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"))
6117 //we just check for Dispose() here
6118 @@ -196,7 +197,7 @@ namespace Gendarme.Rules.Correctness {
6122 - private void CheckIfBaseDisposeIsCalled (MethodDefinition method, MethodDefinition baseMethod)
6123 + private void CheckIfBaseDisposeIsCalled (MethodDefinition method, MemberReference baseMethod)
6127 @@ -215,7 +216,7 @@ namespace Gendarme.Rules.Correctness {
6128 if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt)
6130 MethodReference calledMethod = (MethodReference) call.Operand;
6131 - if (calledMethod.ToString () != baseMethod.ToString ())
6132 + if (calledMethod.GetFullName () != baseMethod.GetFullName ())
6136 @@ -223,7 +224,7 @@ namespace Gendarme.Rules.Correctness {
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);
6145 @@ -256,7 +257,8 @@ namespace Gendarme.Rules.Correctness {
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);
6155 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6156 index a788d00..64172e6 100644
6157 --- a/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6158 +++ b/gendarme/rules/Gendarme.Rules.Correctness/DoNotRoundIntegersRule.cs
6163 +using System.Globalization;
6166 using Mono.Cecil.Cil;
6168 using Gendarme.Framework;
6169 +using Gendarme.Framework.Engines;
6170 +using Gendarme.Framework.Helpers;
6171 using Gendarme.Framework.Rocks;
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)
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.
6185 @@ -63,10 +66,10 @@ namespace Gendarme.Rules.Correctness {
6189 - /// <remarks>This rule is available since Gendarme 2.0</remarks>
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 {
6196 static TypeReference GetType (Instruction ins, MethodDefinition method)
6197 @@ -105,8 +108,8 @@ namespace Gendarme.Rules.Correctness {
6198 if (rv.IsFloatingPoint ())
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"))
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;
6212 + // exclude methods that don't have calls
6213 + if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
6214 + return RuleResult.DoesNotApply;
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"))
6222 Instruction value = null;
6223 @@ -171,7 +178,8 @@ namespace Gendarme.Rules.Correctness {
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);
6232 return Runner.CurrentRuleResult;
6233 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/DontCompareWithNaNRule.cs
6234 index 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.";
6241 - private static string[] FloatingPointTypes = { "System.Single", "System.Double" };
6243 - public override void Initialize (IRunner runner)
6245 - base.Initialize (runner);
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);
6256 private static bool CheckPrevious (IList<Instruction> il, int index)
6258 for (int i = index; i >= 0; i--) {
6259 @@ -143,7 +128,7 @@ namespace Gendarme.Rules.Correctness {
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);
6268 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6269 index 14c0c33..6d1c73d 100644
6270 --- a/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6271 +++ b/gendarme/rules/Gendarme.Rules.Correctness/EnsureLocalDisposalRule.cs
6275 // Cedric Vivier <cedricv@neonux.com>
6276 +// Sebastien Pouliot <sebastien@ximian.com>
6278 // Copyright (C) 2008 Cedric Vivier
6279 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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
6286 using System.Collections.Generic;
6287 +using System.Globalization;
6290 using Mono.Cecil.Cil;
6291 @@ -115,7 +118,7 @@ namespace Gendarme.Rules.Correctness {
6292 public sealed class EnsureLocalDisposalRule : Rule, IMethodRule {
6294 OpCodeBitmask callsAndNewobjBitmask = BuildCallsAndNewobjOpCodeBitmask ();
6295 - HashSet<Instruction> suspectLocals = new HashSet<Instruction> ();
6296 + Bitmask<ulong> locals = new Bitmask<ulong> ();
6298 static bool IsDispose (MethodReference call)
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");
6308 - return method.ReturnType.Implements ("System.IDisposable");
6309 + return method.ReturnType.Implements ("System", "IDisposable");
6312 - static bool AreBothInstructionsInSameTryFinallyBlock (MethodBody body, Instruction a, Instruction b)
6313 + static bool IsSetter (MethodReference m)
6317 + MethodDefinition md = m.Resolve ();
6319 + return m.Name.StartsWith ("set_", StringComparison.Ordinal);
6320 + return md.IsSetter;
6323 + static bool IsInsideFinallyBlock (MethodDefinition method, Instruction ins)
6325 + MethodBody body = method.Body;
6326 + if (!body.HasExceptionHandlers)
6329 foreach (ExceptionHandler eh in body.ExceptionHandlers) {
6330 if (eh.HandlerType != ExceptionHandlerType.Finally)
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)
6340 - static Instruction LocalTraceBack (IMethodSignature method, Instruction ins)
6341 + void Clear (MethodDefinition method, Instruction ins)
6343 - ins = ins.TraceBack (method);
6344 - while (ins != null) {
6345 - if (ins.IsLoadLocal () || ins.IsStoreLocal ())
6347 - ins = ins.TraceBack (method);
6348 + VariableDefinition v = ins.GetVariable (method);
6350 + locals.Clear ((ulong) v.Index);
6353 + void CheckForReturn (MethodDefinition method, Instruction ins)
6355 + if (ins.IsLoadLocal ())
6356 + Clear (method, ins);
6359 + void CheckForOutParameters (MethodDefinition method, Instruction ins)
6361 + Instruction iref = ins.TraceBack (method);
6364 + ParameterDefinition p = iref.GetParameter (method);
6365 + if ((p != null) && p.IsOut) {
6366 + ins = ins.Previous;
6367 + if (ins.IsLoadLocal ())
6368 + Clear (method, ins);
6373 - Instruction FindRelatedSuspectLocal (MethodDefinition method, Instruction ins)
6374 + void CheckDisposeCalls (MethodDefinition method, Instruction ins)
6376 - ins = LocalTraceBack (method, ins);
6380 - int index = ins.GetVariable (method).Index;
6381 - foreach (var local in suspectLocals) {
6382 - if (local.GetVariable (method).Index == index)
6384 + Instruction instance = ins.TraceBack (method);
6385 + if (instance == null)
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);
6397 + locals.Clear (index);
6402 - static bool IsSetter (MethodReference m)
6403 + bool CheckCallsToOtherInstances (MethodDefinition method, Instruction ins, MethodReference call)
6406 + Instruction p = ins.TraceBack (method, 0);
6407 + if (p.Is (Code.Ldarg_0))
6409 - MethodDefinition md = m.Resolve ();
6411 - return m.Name.StartsWith ("set_", StringComparison.Ordinal);
6412 - return md.IsSetter;
6414 + if (call.HasParameters) {
6415 + for (int i = 1; i <= call.Parameters.Count; i++) {
6416 + p = ins.TraceBack (method, -i);
6417 + Clear (method, p);
6423 + void CheckReassignment (MethodDefinition method, Instruction ins)
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);
6433 + locals.Set (index);
6437 public RuleResult CheckMethod (MethodDefinition method)
6438 @@ -193,36 +248,42 @@ namespace Gendarme.Rules.Correctness {
6439 return RuleResult.DoesNotApply;
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;
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);
6454 - suspectLocals.Clear ();
6455 + locals.ClearAll ();
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;
6464 + if (return_idisposable)
6465 + CheckForReturn (method, ins.Previous);
6467 + case Code.Stind_Ref:
6468 + CheckForOutParameters (method, ins);
6471 + if (!callsAndNewobjBitmask.Get (code))
6476 MethodReference call = (MethodReference) ins.Operand;
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);
6485 - suspectLocals.Remove (local);
6487 + CheckDisposeCalls (method, ins);
6491 + if (call.HasThis && (code != Code.Newobj)) {
6492 + if (!CheckCallsToOtherInstances (method, ins, call))
6496 if (!DoesReturnDisposable (call))
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))
6506 - ReportCall (method, ins, call);
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);
6515 - //even if an IDisposable, it isn't stored in a local
6516 - if (nextInstruction.IsStoreLocal ())
6517 - suspectLocals.Add (nextInstruction);
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);
6524 + ReportNonDisposedLocals (method);
6526 return Runner.CurrentRuleResult;
6529 + void ReportNonDisposedLocals (MethodDefinition method)
6531 + for (ulong i = 0; i < 64; i++) {
6532 + if (!locals.Get (i))
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);
6541 static bool IsFluentLike (MethodReference method)
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))
6551 - return (method.HasParameters && rtype == method.Parameters [0].ParameterType.FullName);
6552 + return (method.HasParameters && method.Parameters [0].ParameterType.IsNamed (nspace, name));
6555 void ReportCall (MethodDefinition method, Instruction ins, MethodReference call)
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);
6564 @@ -275,8 +343,8 @@ namespace Gendarme.Rules.Correctness {
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);
6574 static OpCodeBitmask BuildCallsAndNewobjOpCodeBitmask ()
6575 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/FloatComparisonRule.cs
6576 index 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 {
6583 - private static string[] FloatingPointTypes = { "System.Single", "System.Double" };
6585 public override void Initialize (IRunner runner)
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 ();
6599 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj b/gendarme/rules/Gendarme.Rules.Correctness/Gendarme.Rules.Correctness.csproj
6600 index 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
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
6608 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
6609 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
6633 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
6634 <DebugSymbols>true</DebugSymbols>
\r
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
6641 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
6642 <DebugType>pdbonly</DebugType>
\r
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
6650 <Reference Include="System" />
\r
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
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
6674 + <Install>false</Install>
\r
6675 </BootstrapperPackage>
\r
6676 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
6677 <Visible>False</Visible>
\r
6680 + <Install>false</Install>
\r
6681 </BootstrapperPackage>
\r
6682 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
6683 <Visible>False</Visible>
\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
6694 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
6695 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am b/gendarme/rules/Gendarme.Rules.Correctness/Makefile.am
6696 index 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
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
6733 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/MethodCanBeMadeStaticRule.cs
6734 index 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 {
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;
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;
6755 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6756 index f545495..92b5753 100644
6757 --- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6758 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectArgumentsToFormattingMethodsRule.cs
6764 -using System.Resources;
6765 using System.Collections;
6766 using System.Collections.Generic;
6767 +using System.Globalization;
6769 +using System.Resources;
6772 using Mono.Cecil.Cil;
6773 @@ -115,7 +116,7 @@ namespace Gendarme.Rules.Correctness {
6775 IList<Resource> resources = ad.MainModule.Resources;
6776 foreach (EmbeddedResource resource in resources)
6777 - if (resourceClassName.Equals (resource.Name))
6778 + if (resourceClassName == resource.Name)
6782 @@ -131,7 +132,7 @@ namespace Gendarme.Rules.Correctness {
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)
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))
6801 // String.Format (IFormatProvider, string, object[]) -> formatPosition = 1
6802 - if (pdc [0].ParameterType.FullName != "System.String")
6803 + if (!pdc [0].ParameterType.IsNamed ("System", "String"))
6807 @@ -266,12 +267,19 @@ namespace Gendarme.Rules.Correctness {
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);
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);
6829 public RuleResult CheckMethod (MethodDefinition method)
6830 @@ -289,7 +297,7 @@ namespace Gendarme.Rules.Correctness {
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);
6839 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6840 index 89eb1e8..ebaa25e 100644
6841 --- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6842 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideCorrectRegexPatternRule.cs
6847 +using System.Globalization;
6850 using Mono.Cecil.Cil;
6851 @@ -91,20 +92,23 @@ namespace Gendarme.Rules.Correctness {
6853 static OpCodeBitmask callsAndNewobjBitmask = BuildCallsAndNewobjOpCodeBitmask ();
6855 - const string RegexClass = "System.Text.RegularExpressions.Regex";
6856 - const string ValidatorClass = "System.Configuration.RegexStringValidator";
6858 public override void Initialize (IRunner runner)
6860 base.Initialize (runner);
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");
6884 @@ -127,7 +131,7 @@ namespace Gendarme.Rules.Correctness {
6885 return CheckPattern (method, ins, (string) ld.Operand, confidence);
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"))
6891 return CheckPattern (method, ins, null, confidence);
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);
6903 @@ -161,8 +166,9 @@ namespace Gendarme.Rules.Correctness {
6905 if (!call.HasParameters)
6907 - string tname = call.DeclaringType.FullName;
6908 - if (tname != RegexClass && tname != ValidatorClass)
6910 + TypeReference type = call.DeclaringType;
6911 + if (!type.IsNamed ("System.Text.RegularExpressions", "Regex") && !type.IsNamed ("System.Configuration", "RegexStringValidator"))
6914 MethodDefinition mdef = call.Resolve ();
6915 @@ -174,8 +180,8 @@ namespace Gendarme.Rules.Correctness {
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));
6924 CheckArguments (method, ins, ld);
6926 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6927 index 68d4cb4..770e78d 100644
6928 --- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6929 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXPathExpressionRule.cs
6934 +using System.Globalization;
6936 using System.Xml.XPath;
6938 @@ -74,10 +75,6 @@ namespace Gendarme.Rules.Correctness {
6939 [EngineDependency (typeof (OpCodeEngine))]
6940 public sealed class ProvideValidXPathExpressionRule : Rule, IMethodRule {
6942 - const string XmlNodeClass = "System.Xml.XmlNode";
6943 - const string XPathNavigatorClass = "System.Xml.XPath.XPathNavigator";
6944 - const string XPathExpressionClass = "System.Xml.XPath.XPathExpression";
6946 public override void Initialize (IRunner runner)
6948 base.Initialize (runner);
6949 @@ -105,7 +102,7 @@ namespace Gendarme.Rules.Correctness {
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);
6958 @@ -124,7 +121,8 @@ namespace Gendarme.Rules.Correctness {
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);
6968 @@ -137,11 +135,11 @@ namespace Gendarme.Rules.Correctness {
6969 switch (mref.Name) {
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));
6977 - if (mref.DeclaringType.FullName == XmlNodeClass)
6978 + if (mref.DeclaringType.IsNamed ("System.Xml", "XmlNode"))
6979 CheckString (method, ins, -1);
6982 @@ -150,7 +148,7 @@ namespace Gendarme.Rules.Correctness {
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);
6991 @@ -158,8 +156,8 @@ namespace Gendarme.Rules.Correctness {
6993 void CheckXPathNavigatorString (MethodDefinition method, Instruction ins, MethodReference mref)
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);
7002 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7003 index 921e71a..36e7c64 100644
7004 --- a/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7005 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ProvideValidXmlStringRule.cs
7009 using System.Collections.Generic;
7010 +using System.Globalization;
7012 using System.Xml.XPath;
7014 @@ -77,10 +78,6 @@ namespace Gendarme.Rules.Correctness {
7015 [EngineDependency (typeof (OpCodeEngine))]
7016 public sealed class ProvideValidXmlStringRule : Rule, IMethodRule {
7018 - const string XmlDocumentClass = "System.Xml.XmlDocument";
7019 - const string XmlNodeClass = "System.Xml.XmlNode";
7020 - const string XPathNavigatorClass = "System.Xml.XPath.XPathNavigator";
7022 public override void Initialize (IRunner runner)
7024 base.Initialize (runner);
7025 @@ -108,7 +105,7 @@ namespace Gendarme.Rules.Correctness {
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);
7034 @@ -127,7 +124,8 @@ namespace Gendarme.Rules.Correctness {
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);
7044 @@ -139,13 +137,13 @@ namespace Gendarme.Rules.Correctness {
7046 switch (mref.Name) {
7048 - if (mref.DeclaringType.FullName == XmlDocumentClass)
7049 + if (mref.DeclaringType.IsNamed ("System.Xml", "XmlDocument"))
7050 CheckString (method, ins, -1);
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);
7060 @@ -154,8 +152,8 @@ namespace Gendarme.Rules.Correctness {
7061 case "InsertBefore":
7062 IList<ParameterDefinition> pdc = mref.Parameters;
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);
7071 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/README.md b/gendarme/rules/Gendarme.Rules.Correctness/README.md
7072 new file mode 100644
7073 index 0000000..b7a8fc5
7075 +++ b/gendarme/rules/Gendarme.Rules.Correctness/README.md
7077 +# Gendarme.Rules.Correctness Rules
7079 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Correctness(git)]] pages.
7084 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
7086 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7087 index 79b290b..272f86e 100644
7088 --- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7089 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewDoubleAssignmentRule.cs
7094 +using System.Globalization;
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;
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);
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;
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;
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);
7125 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewInconsistentIdentityRule.cs
7126 index 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 {
7131 private void GetMethods (TypeReference type)
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 {
7140 Log.WriteLine (this);
7141 Log.WriteLine (this, "------------------------------------");
7142 - Log.WriteLine (this, type.FullName);
7143 + Log.WriteLine (this, type);
7146 if (methods.Count > 0) {
7147 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7148 index 5d359cc..127d7c7 100644
7149 --- a/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7150 +++ b/gendarme/rules/Gendarme.Rules.Correctness/ReviewSelfAssignmentRule.cs
7155 +using System.Globalization;
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);
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 ());
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);
7189 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/ReviewUseOfInt64BitsToDoubleRule.cs
7190 index 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);
7197 - private const string BitConverter = "System.BitConverter";
7199 public override void Initialize (IRunner runner)
7201 base.Initialize (runner);
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);
7218 + static bool IsInt64BitsToDouble (MemberReference method)
7220 + return method.IsNamed ("System", "BitConverter", "Int64BitsToDouble");
7223 public RuleResult CheckMethod (MethodDefinition method)
7225 if (!method.HasBody)
7226 @@ -106,10 +112,7 @@ namespace Gendarme.Rules.Correctness {
7227 if (ins.OpCode.FlowControl != FlowControl.Call)
7230 - MethodReference mr = (ins.Operand as MethodReference);
7231 - if (mr.Name != "Int64BitsToDouble")
7233 - if (mr.DeclaringType.FullName != BitConverter)
7234 + if (!IsInt64BitsToDouble (ins.Operand as MethodReference))
7237 // if the previous call convert a value into a long (int64)
7238 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/BadRecursiveInvocationTest.cs
7239 index 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 {
7244 AssertRuleSuccess<BadRec> ("StaticGoodOverload", new Type [] { typeof (object) });
7249 + public virtual void SetProperty (string name, object value)
7251 + Console.WriteLine ("{0}: {1}", name, value);
7254 + internal virtual void SetProperty (string name, object [] args)
7256 + SetProperty (name, args [0]);
7261 + public void ArrayOverload ()
7263 + AssertRuleSuccess<Array> ("SetProperty", new Type [] { typeof (string), typeof (object[]) });
7267 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs
7268 new file mode 100644
7269 index 0000000..8de18ab
7271 +++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/DeclareEventsExplicitlyTest.cs
7274 +// Unit tests for DeclareEventsExplicitlyRule
7277 +// Sebastien Pouliot <sebastien@ximian.com>
7279 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
7289 +// The above copyright notice and this permission notice shall be
7290 +// included in all copies or substantial portions of the Software.
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.
7303 +using Gendarme.Rules.Correctness;
7304 +using NUnit.Framework;
7306 +using Test.Rules.Definitions;
7307 +using Test.Rules.Fixtures;
7309 +namespace Tests.Rules.Correctness {
7312 + public class DeclareEventsExplicitlyTest : TypeRuleTestFixture<DeclareEventsExplicitlyRule> {
7314 + struct StructInstanceCorrect {
7315 + public event EventHandler<EventArgs> MyEvent;
7318 + struct StructInstanceIncorrect {
7319 + public EventHandler<EventArgs> MyEvent;
7322 + class GenericClassStaticCorrect {
7323 + public static event EventHandler<EventArgs> MyEvent;
7326 + class GenericClassStaticIncorect {
7327 + public static EventHandler<EventArgs> MyEvent;
7328 + public event EventHandler<EventArgs> MyEvent2;
7332 + public void DoesNotApply ()
7334 + AssertRuleDoesNotApply (SimpleTypes.Class);
7335 + AssertRuleDoesNotApply (SimpleTypes.Enum);
7336 + // interface cannot define fields
7337 + AssertRuleDoesNotApply (SimpleTypes.Interface);
7341 + public void Success ()
7343 + AssertRuleSuccess<StructInstanceCorrect> ();
7344 + AssertRuleSuccess<GenericClassStaticCorrect> ();
7348 + public void Failure ()
7350 + AssertRuleFailure<StructInstanceIncorrect> (1);
7351 + AssertRuleFailure<GenericClassStaticIncorect> (1);
7355 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/EnsureLocalDisposalTest.cs
7356 index 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 {
7361 StreamReader StreamReader { get; set; }
7363 - string DoesNotApply1 () { //no call/newobj/stloc
7364 + string DoesNotApply1 ()
7366 + //no call/newobj/stloc
7370 - StreamReader DoesNotApply2 () { //returns IDisposable
7371 - var sr = new StreamReader ("bar.xml");
7375 string Success0 () {
7376 var o = new object ();
7377 return o.ToString ();
7378 @@ -214,12 +211,6 @@ namespace Test.Rules.Correctness {
7382 - public void DoesNotApply2 ()
7384 - AssertRuleDoesNotApply<DisposalCases> ("DoesNotApply2");
7388 public void Success0 ()
7390 AssertRuleSuccess<DisposalCases> ("Success0");
7391 @@ -300,7 +291,7 @@ namespace Test.Rules.Correctness {
7393 public void Failure3 ()
7395 - AssertRuleFailure<DisposalCases> ("Failure3", 2);
7396 + AssertRuleFailure<DisposalCases> ("Failure3", 1);
7400 @@ -382,11 +373,71 @@ namespace Test.Rules.Correctness {
7402 public void FluentApi ()
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");
7412 + // adapted (without locals variants) from https://bugzilla.novell.com/show_bug.cgi?id=666403
7414 + void OutParameter1 (out StreamReader stream)
7416 + var new_stream = new StreamReader ("baz.xml"); //out param
7417 + stream = new_stream;
7420 + bool OutParameter2 (out StreamReader stream)
7422 + stream = new StreamReader ("baz.xml"); //out param, no locals
7427 + public void OutParameters ()
7429 + AssertRuleSuccess<EnsureLocalDisposalTest> ("OutParameter1");
7430 + AssertRuleSuccess<EnsureLocalDisposalTest> ("OutParameter2");
7433 + class SomeClassThatContainsADisposableProperty {
7434 + public StreamReader Reader { get; set; }
7437 + void OtherInstanceProperty1 (SomeClassThatContainsADisposableProperty someObj)
7439 + var reader = new StreamReader ("foobaz.xml");
7440 + someObj.Reader = reader; //property in param
7443 + void OtherInstanceProperty2 (SomeClassThatContainsADisposableProperty someObj)
7445 + someObj.Reader = new StreamReader ("foobaz.xml"); //property in param, no locals
7449 + public void OtherInstance ()
7451 + AssertRuleSuccess<EnsureLocalDisposalTest> ("OtherInstanceProperty1");
7452 + AssertRuleSuccess<EnsureLocalDisposalTest> ("OtherInstanceProperty2");
7455 + StreamReader ReturnIDisposable1 ()
7457 + var ret = new StreamReader ("baz.xml"); //return value
7461 + StreamReader ReturnIDisposable2 ()
7463 + return new StreamReader ("baz.xml"); //return value, no locals
7467 + public void ReturnValue ()
7469 + // csc 10 (without /o optimize) will fail this as it introduce extra compiler generated locals
7471 + AssertRuleSuccess<EnsureLocalDisposalTest> ("ReturnIDisposable1");
7473 + AssertRuleSuccess<EnsureLocalDisposalTest> ("ReturnIDisposable2");
7477 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/Resource.Designer.cs
7478 index 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
7482 -//------------------------------------------------------------------------------
7483 +//------------------------------------------------------------------------------
7485 // This code was generated by a tool.
7486 -// Runtime Version:2.0.50727.4927
7487 +// Runtime Version:4.0.30319.1
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 {
7500 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj b/gendarme/rules/Gendarme.Rules.Correctness/Test/Tests.Rules.Correctness.csproj
7501 index 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
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
7509 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
7510 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
7534 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
7535 <DebugSymbols>true</DebugSymbols>
\r
7537 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
7538 <ErrorReport>prompt</ErrorReport>
\r
7539 <WarningLevel>4</WarningLevel>
\r
7540 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
7542 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
7543 <DebugType>pdbonly</DebugType>
\r
7545 <DefineConstants>TRACE</DefineConstants>
\r
7546 <ErrorReport>prompt</ErrorReport>
\r
7547 <WarningLevel>4</WarningLevel>
\r
7548 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
7551 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
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
7561 @@ -119,14 +124,33 @@
7562 </ProjectReference>
\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
7574 + <Install>false</Install>
\r
7575 </BootstrapperPackage>
\r
7576 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
7577 <Visible>False</Visible>
\r
7580 + <Install>false</Install>
\r
7581 </BootstrapperPackage>
\r
7582 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
7583 <Visible>False</Visible>
\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
7595 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
7596 new file mode 100644
7597 index 0000000..077889c
7599 +++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
7602 +// Unit tests for TypesWithDisposableFieldsShouldBeDisposableRule
7605 +// Andreas Noever <andreas.noever@gmail.com>
7606 +// Sebastien Pouliot <sebastien@ximian.com>
7608 +// (C) 2008 Andreas Noever
7609 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
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:
7619 +// The above copyright notice and this permission notice shall be
7620 +// included in all copies or substantial portions of the Software.
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.
7633 +using Gendarme.Rules.Correctness;
7635 +using NUnit.Framework;
7636 +using Test.Rules.Definitions;
7637 +using Test.Rules.Fixtures;
7639 +namespace Test.Rules.Correctness {
7641 + class Disposable : IDisposable {
7642 + public void Dispose ()
7644 + throw new NotImplementedException ();
7648 + class NoDisposeableFields {
7653 + class DisposeableFieldsImplementsIDisposeable : IDisposable {
7657 + public DisposeableFieldsImplementsIDisposeable ()
7659 + B = new Disposable ();
7662 + public void Dispose ()
7664 + throw new NotImplementedException ();
7668 + class DisposeableFieldsImplementsIDisposeableCorrectly : IDisposable {
7672 + public DisposeableFieldsImplementsIDisposeableCorrectly ()
7674 + B = new Disposable ();
7677 + public void Dispose ()
7679 + B.Dispose (); // not really correct but Dispose is called :)
7683 + class DisposeableFieldsExplicit : IDisposable {
7687 + void IDisposable.Dispose ()
7689 + throw new NotImplementedException ();
7693 + abstract class DisposeableFieldsImplementsIDisposeableAbstract : IDisposable {
7696 + public void Dispose (object asd) { B.Dispose (); }
7697 + public abstract void Dispose ();
7700 + abstract class DisposeableFieldsImplementsIDisposeableAbstractAssigned : IDisposable {
7704 + protected DisposeableFieldsImplementsIDisposeableAbstractAssigned ()
7706 + B = new Disposable ();
7709 + public abstract void Dispose ();
7712 + public class DisposeableFieldsNeverAssigned : ICloneable {
7716 + public object Clone ()
7718 + throw new NotImplementedException ();
7722 + public class DisposeableFieldsNullAssigned : ICloneable {
7726 + public DisposeableFieldsNullAssigned ()
7732 + public object Clone ()
7734 + throw new NotImplementedException ();
7738 + public class DisposeableFieldsAssigned : ICloneable {
7742 + public DisposeableFieldsAssigned ()
7745 + B = new Disposable ();
7748 + public object Clone ()
7750 + throw new NotImplementedException ();
7754 + class DisposeableFieldsReferenced : ICloneable {
7758 + public DisposeableFieldsReferenced (Disposable instance)
7764 + public object Clone ()
7766 + throw new NotImplementedException ();
7770 + class DisposeableFieldsArray : ICloneable {
7774 + public object Clone ()
7776 + throw new NotImplementedException ();
7780 + class DisposeableFieldsArrayAssigned : ICloneable {
7784 + public object Clone ()
7786 + // the array itself is not not IDisposable
7787 + B = new Disposable [10];
7793 + class DisposeableFieldsArrayMembers : ICloneable {
7797 + public object Clone ()
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 ();
7808 + struct StructWithDisposeableFields {
7812 + public StructWithDisposeableFields (object obj)
7815 + a = new Disposable ();
7819 + class DisposeableStaticFieldsArray {
7821 + static Disposable [] B;
7823 + static DisposeableStaticFieldsArray ()
7825 + B = new Disposable [1];
7826 + B [0] = new Disposable ();
7830 + // test case from https://bugzilla.novell.com/show_bug.cgi?id=671029
7832 + interface ISession : IDisposable {
7833 + void Query (string s);
7836 + class SomeRepository {
7838 + public SomeRepository (ISession session)
7840 + this.session = session;
7842 + public void DoSomeQuery ()
7844 + session.Query ("whatever");
7850 + public class TypesWithDisposableFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithDisposableFieldsShouldBeDisposableRule> {
7853 + public void DoesNotApply ()
7855 + AssertRuleDoesNotApply (SimpleTypes.Delegate);
7856 + AssertRuleDoesNotApply (SimpleTypes.Enum);
7857 + AssertRuleDoesNotApply (SimpleTypes.Interface);
7858 + AssertRuleDoesNotApply (SimpleTypes.Structure);
7862 + public void TestNoDisposeableFields ()
7864 + AssertRuleSuccess<NoDisposeableFields> ();
7868 + public void TestDisposeableFieldsImplementsIDisposeable ()
7870 + AssertRuleSuccess<DisposeableFieldsImplementsIDisposeable> ();
7871 + AssertRuleSuccess<DisposeableFieldsImplementsIDisposeableCorrectly> ();
7875 + public void TestDisposeableFieldsExplicit ()
7877 + AssertRuleSuccess<DisposeableFieldsExplicit> ();
7881 + public void TestDisposeableFieldsImplementsIDisposeableAbstract ()
7883 + AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstract> (1);
7884 + AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstractAssigned> (2);
7888 + public void TestDisposeableFields ()
7890 + AssertRuleSuccess<DisposeableFieldsNeverAssigned> ();
7891 + AssertRuleSuccess<DisposeableFieldsNullAssigned> ();
7892 + AssertRuleSuccess<DisposeableFieldsReferenced> ();
7893 + AssertRuleFailure<DisposeableFieldsAssigned> (1);
7897 + public void TestDisposeableFieldsArray ()
7899 + AssertRuleSuccess<DisposeableFieldsArray> ();
7900 + AssertRuleSuccess<DisposeableFieldsArrayAssigned> ();
7901 + AssertRuleFailure<DisposeableFieldsArrayMembers> (1);
7905 + public void TestStructWithDisposeableFields ()
7907 + AssertRuleDoesNotApply<StructWithDisposeableFields> ();
7911 + public void TestDisposeableStaticFieldsArray ()
7913 + AssertRuleSuccess<DisposeableStaticFieldsArray> ();
7917 + public void Bug671029 ()
7919 + AssertRuleSuccess<SomeRepository> ();
7923 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
7924 new file mode 100644
7925 index 0000000..b66fcbf
7927 +++ b/gendarme/rules/Gendarme.Rules.Correctness/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
7930 +// Unit tests for TypesWithNativeFieldsShouldBeDisposableRule
7933 +// Andreas Noever <andreas.noever@gmail.com>
7934 +// Sebastien Pouliot <sebastien@ximian.com>
7936 +// (C) 2008 Andreas Noever
7937 +// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
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:
7947 +// The above copyright notice and this permission notice shall be
7948 +// included in all copies or substantial portions of the Software.
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.
7960 +using System.Runtime.InteropServices;
7962 +using Gendarme.Rules.Correctness;
7964 +using NUnit.Framework;
7965 +using Test.Rules.Definitions;
7966 +using Test.Rules.Fixtures;
7968 +namespace Test.Rules.Design {
7970 + class NoNativeFields {
7975 + class NativeFieldsImplementsIDisposeable : IDisposable {
7979 + public void Dispose ()
7981 + throw new NotImplementedException ();
7985 + class NativeFieldsExplicit : IDisposable {
7989 + void IDisposable.Dispose ()
7991 + throw new NotImplementedException ();
7996 + class NativeFieldsIntPtr : ICloneable {
8000 + public object Clone ()
8002 + throw new NotImplementedException ();
8006 + class NativeFieldsIntPtrAssigned : ICloneable {
8010 + public NativeFieldsIntPtrAssigned ()
8015 + public object Clone ()
8017 + throw new NotImplementedException ();
8021 + class NativeFieldsIntPtrAllocated : ICloneable {
8025 + public NativeFieldsIntPtrAllocated ()
8027 + B = Marshal.AllocCoTaskMem (1);
8030 + public object Clone ()
8032 + throw new NotImplementedException ();
8036 + class NativeFieldsUIntPtr : ICloneable {
8040 + public object Clone ()
8042 + throw new NotImplementedException ();
8046 + class NativeFieldsUIntPtrAssigned : ICloneable {
8050 + public NativeFieldsUIntPtrAssigned ()
8052 + B = (UIntPtr) 0x1f00;
8055 + public object Clone ()
8057 + throw new NotImplementedException ();
8061 + class NativeFieldsUIntPtrAllocated : ICloneable {
8065 + [DllImport ("liberty")]
8066 + extern static UIntPtr Alloc (int x);
8068 + public NativeFieldsUIntPtrAllocated ()
8073 + public object Clone ()
8075 + throw new NotImplementedException ();
8079 + class NativeFieldsHandleRef : ICloneable {
8083 + public object Clone ()
8085 + throw new NotImplementedException ();
8089 + class NativeFieldsHandleRefAssigned : ICloneable {
8093 + public NativeFieldsHandleRefAssigned ()
8095 + GCHandle handle = GCHandle.Alloc (A, GCHandleType.Pinned);
8096 + B = new HandleRef (handle, handle.AddrOfPinnedObject ());
8099 + public object Clone ()
8101 + throw new NotImplementedException ();
8105 + class NativeFieldsHandleRefAllocatedElsewhere: ICloneable {
8109 + HandleRef GetHandleReference ()
8111 + return new HandleRef (A, IntPtr.Zero);
8114 + public NativeFieldsHandleRefAllocatedElsewhere ()
8116 + // fxcop does not trigger on this (or similar cases)
8117 + B = GetHandleReference ();
8120 + public object Clone ()
8122 + throw new NotImplementedException ();
8126 + abstract class AbstractNativeFields : IDisposable {
8130 + public abstract void Dispose ();
8133 + abstract class AbstractNativeFields2 : IDisposable {
8137 + public abstract void Dispose ();
8140 + void IDisposable.Dispose ()
8142 + throw new NotImplementedException ();
8146 + class NativeFieldsArray : ICloneable {
8150 + public object Clone ()
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);
8161 + struct StructWithNativeFields {
8164 + public HandleRef c;
8167 + class NativeStaticFieldsArray {
8169 + static UIntPtr [] B;
8173 + public class TypesWithNativeFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithNativeFieldsShouldBeDisposableRule> {
8176 + public void DoesNotApply ()
8178 + AssertRuleDoesNotApply (SimpleTypes.Delegate);
8179 + AssertRuleDoesNotApply (SimpleTypes.Enum);
8180 + AssertRuleDoesNotApply (SimpleTypes.Interface);
8181 + AssertRuleDoesNotApply (SimpleTypes.Structure);
8185 + public void TestNoNativeFields ()
8187 + AssertRuleSuccess<NoNativeFields> ();
8191 + public void TestNativeFieldsImplementsIDisposeable ()
8193 + AssertRuleSuccess<NativeFieldsImplementsIDisposeable> ();
8197 + public void TestNativeFieldsExplicit ()
8199 + AssertRuleSuccess<NativeFieldsExplicit> ();
8203 + public void TestNativeFieldsIntPtr ()
8205 + AssertRuleSuccess<NativeFieldsIntPtr> ();
8206 + AssertRuleSuccess<NativeFieldsIntPtrAssigned> ();
8207 + AssertRuleFailure<NativeFieldsIntPtrAllocated> (1);
8211 + public void TestNativeFieldsUIntPtr ()
8213 + AssertRuleSuccess<NativeFieldsUIntPtr> ();
8214 + AssertRuleSuccess<NativeFieldsUIntPtrAssigned> ();
8215 + AssertRuleFailure<NativeFieldsUIntPtrAllocated> (1);
8219 + public void TestNativeFieldsHandleRef ()
8221 + AssertRuleSuccess<NativeFieldsHandleRef> ();
8222 + AssertRuleSuccess<NativeFieldsHandleRefAssigned> ();
8223 + AssertRuleFailure<NativeFieldsHandleRefAllocatedElsewhere> (1);
8227 + public void TestAbstractNativeFields ()
8229 + AssertRuleFailure<AbstractNativeFields> (1);
8230 + AssertRuleFailure<AbstractNativeFields2> (1);
8234 + public void TestNativeFieldsArray ()
8236 + AssertRuleFailure<NativeFieldsArray> (1);
8240 + public void TestStructWithNativeFields ()
8242 + AssertRuleDoesNotApply<StructWithNativeFields> ();
8246 + public void TestNativeStaticFieldsArray ()
8248 + AssertRuleSuccess<NativeStaticFieldsArray> ();
8253 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs
8254 new file mode 100644
8255 index 0000000..247d01a
8257 +++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesShouldBeDisposableBaseRule.cs
8260 +// Gendarme.Rules.Correctness.TypesShouldBeDisposableBaseRule
8263 +// Andreas Noever <andreas.noever@gmail.com>
8264 +// Sebastien Pouliot <sebastien@ximian.com>
8266 +// (C) 2008 Andreas Noever
8267 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
8277 +// The above copyright notice and this permission notice shall be
8278 +// included in all copies or substantial portions of the Software.
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.
8289 +using System.Collections.Generic;
8293 +using Gendarme.Framework;
8294 +using Gendarme.Framework.Helpers;
8295 +using Gendarme.Framework.Rocks;
8297 +namespace Gendarme.Rules.Correctness {
8299 + public abstract class TypesShouldBeDisposableBaseRule : Rule, ITypeRule {
8301 + protected TypesShouldBeDisposableBaseRule ()
8303 + FieldCandidates = new HashSet<FieldDefinition> ();
8306 + protected HashSet<FieldDefinition> FieldCandidates { get; private set; }
8308 + protected abstract string AbstractTypeMessage { get; }
8309 + protected abstract string TypeMessage { get; }
8310 + protected abstract string AbstractDisposeMessage { get; }
8312 + static bool IsAbstract (MethodDefinition method)
8314 + return ((method != null) && (method.IsAbstract));
8317 + protected abstract void CheckMethod (MethodDefinition method, bool abstractWarning);
8319 + protected abstract bool FieldTypeIsCandidate (TypeDefinition type);
8321 + public RuleResult CheckType (TypeDefinition type)
8323 + // that will cover interfaces, delegates too
8324 + if (!type.HasFields)
8325 + return RuleResult.DoesNotApply;
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;
8331 + MethodDefinition explicitDisposeMethod = null;
8332 + MethodDefinition implicitDisposeMethod = null;
8334 + bool abstractWarning = false;
8336 + if (type.Implements ("System", "IDisposable")) {
8337 + implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
8338 + explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
8340 + if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
8341 + abstractWarning = true;
8343 + return RuleResult.Success;
8347 + FieldCandidates.Clear ();
8349 + foreach (FieldDefinition field in type.Fields) {
8350 + // we can't dispose static fields in IDisposable
8351 + if (field.IsStatic)
8353 + TypeDefinition fieldType = field.FieldType.GetElementType ().Resolve ();
8354 + if (fieldType == null)
8356 + if (FieldTypeIsCandidate (fieldType))
8357 + FieldCandidates.Add (field);
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);
8368 + // Warn about possible confusion if the Dispose methods are abstract
8369 + if (IsAbstract (implicitDisposeMethod))
8370 + Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
8372 + return Runner.CurrentRuleResult;
8375 + public void Bitmask ()
8377 + OpCodeBitmask mask = new OpCodeBitmask ();
8378 + mask.Set (Code.Stfld);
8379 + mask.Set (Code.Stelem_Ref);
8380 + Console.WriteLine (mask);
8386 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs
8387 new file mode 100644
8388 index 0000000..1731951
8390 +++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithDisposableFieldsShouldBeDisposableRule.cs
8393 +// Gendarme.Rules.Correctness.TypesWithDisposableFieldsShouldBeDisposableRule
8396 +// Andreas Noever <andreas.noever@gmail.com>
8397 +// Sebastien Pouliot <sebastien@ximian.com>
8399 +// (C) 2008 Andreas Noever
8400 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
8410 +// The above copyright notice and this permission notice shall be
8411 +// included in all copies or substantial portions of the Software.
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.
8423 +using Mono.Cecil.Cil;
8425 +using Gendarme.Framework;
8426 +using Gendarme.Framework.Engines;
8427 +using Gendarme.Framework.Helpers;
8428 +using Gendarme.Framework.Rocks;
8430 +namespace Gendarme.Rules.Correctness {
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.
8440 + /// class DoesNotImplementIDisposable {
8441 + /// IDisposable field;
8444 + /// class AbstractDispose : IDisposable {
8445 + /// IDisposable field;
8447 + /// // the field should be disposed in the type that declares it
8448 + /// public abstract void Dispose ();
8455 + /// class Dispose : IDisposable {
8456 + /// IDisposable field;
8458 + /// public void Dispose ()
8460 + /// field.Dispose ();
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 {
8472 + static OpCodeBitmask StoreFieldBitmask = new OpCodeBitmask (0x0, 0x400000000000000, 0x80000000, 0x0);
8474 + protected override string AbstractTypeMessage {
8475 + get { return "Field implement IDisposable. Type should implement a non-abstract Dispose() method"; }
8478 + protected override string TypeMessage {
8479 + get { return "Field implement IDisposable. Type should implement a Dispose() method"; }
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."; }
8486 + protected override void CheckMethod (MethodDefinition method, bool abstractWarning)
8488 + if ((method == null) || !method.HasBody)
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))
8496 + foreach (Instruction ins in method.Body.Instructions) {
8497 + if (!ins.Is (Code.Newobj))
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;
8510 + if (field != null && FieldCandidates.Contains (field)) {
8511 + Runner.Report (field, Severity.High, Confidence.High,
8512 + abstractWarning ? AbstractTypeMessage : TypeMessage);
8517 + protected override bool FieldTypeIsCandidate (TypeDefinition type)
8519 + // enums and primitives don't implement IDisposable
8520 + if ((type == null) || type.IsEnum || type.IsPrimitive)
8523 + return type.Implements ("System", "IDisposable");
8528 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs
8529 new file mode 100644
8530 index 0000000..1273a75
8532 +++ b/gendarme/rules/Gendarme.Rules.Correctness/TypesWithNativeFieldsShouldBeDisposableRule.cs
8535 +// Gendarme.Rules.Correctness.TypesWithNativeFieldsShouldBeDisposableRule
8538 +// Andreas Noever <andreas.noever@gmail.com>
8539 +// Sebastien Pouliot <sebastien@ximian.com>
8541 +// (C) 2008 Andreas Noever
8542 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
8552 +// The above copyright notice and this permission notice shall be
8553 +// included in all copies or substantial portions of the Software.
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.
8565 +using Mono.Cecil.Cil;
8567 +using Gendarme.Framework;
8568 +using Gendarme.Framework.Engines;
8569 +using Gendarme.Framework.Helpers;
8570 +using Gendarme.Framework.Rocks;
8572 +namespace Gendarme.Rules.Correctness {
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>.
8581 + /// public class DoesNotImplementIDisposable {
8585 + /// abstract public class AbstractDispose : IDisposable {
8588 + /// // the field should be disposed in the type that declares it
8589 + /// public abstract void Dispose ();
8596 + /// public class Dispose : IDisposable {
8597 + /// IDisposable field;
8599 + /// public void Dispose ()
8601 + /// UnmanagedFree (field);
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 {
8613 + static OpCodeBitmask StoreFieldBitmask = new OpCodeBitmask (0x0, 0x400000000000000, 0x80000000, 0x0);
8615 + protected override string AbstractTypeMessage {
8616 + get { return "Field is native. Type should implement a non-abstract Dispose() method"; }
8619 + protected override string TypeMessage {
8620 + get { return "Field is native. Type should implement a Dispose() method"; }
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."; }
8627 + protected override void CheckMethod (MethodDefinition method, bool abstractWarning)
8629 + if ((method == null) || !method.HasBody)
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))
8637 + foreach (Instruction ins in method.Body.Instructions) {
8638 + MethodReference mr = (ins.Operand as MethodReference);
8639 + if (mr == null || mr.DeclaringType.IsNative ())
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;
8655 + if (field != null && FieldCandidates.Contains (field)) {
8656 + Runner.Report (field, Severity.High, Confidence.High,
8657 + abstractWarning ? AbstractTypeMessage : TypeMessage);
8662 + protected override bool FieldTypeIsCandidate (TypeDefinition type)
8664 + return ((type != null) && type.IsNative ());
8668 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/UseNoInliningWithGetCallingAssemblyRule.cs
8669 index 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 {
8676 - private const string Assembly = "System.Reflection.Assembly";
8678 public override void Initialize (IRunner runner)
8680 base.Initialize (runner);
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);
8696 + static bool IsGetCallingAssembly (MemberReference method)
8698 + return method.IsNamed ("System.Reflection", "Assembly", "GetCallingAssembly");
8701 static bool IsCallToGetCallingAssembly (Instruction instruction)
8703 var code = instruction.OpCode.Code;
8704 if (code != Code.Call && code != Code.Callvirt)
8707 - var method = instruction.Operand as MethodReference;
8708 - if (method == null)
8711 - return method.Name == "GetCallingAssembly"
8712 - && method.DeclaringType.FullName == Assembly;
8713 + return IsGetCallingAssembly (instruction.GetMethod ());
8716 public RuleResult CheckMethod (MethodDefinition method)
8717 diff --git a/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs b/gendarme/rules/Gendarme.Rules.Correctness/UseValueInPropertySetterRule.cs
8718 index 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);
8725 - if (pd.GetSequence () == 1) // value
8726 + if (pd.Index == 0) // value
8727 return RuleResult.Success;
8730 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidDeclaringCustomDelegatesRule.cs
8731 index 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 {
8738 - /// This rule will fire if custom delegates are defined when either pre-defined
8739 - /// <code>Action</code>, <code>Action<T[,...]></code> or <code>Func<[Tx,...]TResult></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<T[,...]></code> or <code>Func<[Tx,...]TResult></code> could have been used.
8745 /// Bad example (without return value):
8746 @@ -68,32 +67,10 @@ namespace Gendarme.Rules.Design.Generic {
8747 /// private Func<int,string,int> func_delegate;
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 {
8756 - private int MaxParameter = 4; // NET_2_0
8758 - public override void Initialize (IRunner runner)
8760 - base.Initialize (runner);
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;
8769 - } else if (runtime >= TargetRuntime.Net_2_0) {
8777 + public class AvoidDeclaringCustomDelegatesRule : GenericsBaseRule, ITypeRule {
8779 static string[] ActionMessage = {
8780 "Replace with Action()",
8781 @@ -157,7 +134,7 @@ namespace Gendarme.Rules.Design.Generic {
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;
8789 use_structure = true;
8790 @@ -170,7 +147,7 @@ namespace Gendarme.Rules.Design.Generic {
8794 - string msg = (invoke.ReturnType.FullName == "System.Void") ? ActionMessage [n] : FuncMessage [n];
8795 + string msg = invoke.ReturnType.IsNamed ("System", "Void") ? ActionMessage [n] : FuncMessage [n];
8797 msg += " and use a structure to hold all your parameters into <T>.";
8798 Runner.Report (type, severity, Confidence.High, msg);
8799 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidExcessiveParametersOnGenericTypesRule.cs
8800 index 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 {
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.
8813 @@ -53,11 +54,12 @@ namespace Gendarme.Rules.Design.Generic {
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 {
8826 public RuleResult CheckType (TypeDefinition type)
8828 if (!type.IsClass || !type.HasGenericParameters || !type.IsVisible ())
8829 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8830 index b369332..18d21eb 100644
8831 --- a/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8832 +++ b/gendarme/rules/Gendarme.Rules.Design.Generic/AvoidMethodWithUnusedGenericTypeRule.cs
8837 +using System.Globalization;
8841 @@ -75,50 +76,37 @@ namespace Gendarme.Rules.Design.Generic {
8845 - /// <remarks>This rule is available since Gendarme 2.2</remarks>
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 {
8853 - public override void Initialize (IRunner runner)
8855 - base.Initialize (runner);
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);
8863 + public class AvoidMethodWithUnusedGenericTypeRule : GenericsBaseRule, IMethodRule {
8865 - static bool FindGenericType (IGenericInstance git, string fullname)
8866 + static bool FindGenericType (IGenericInstance git, string nameSpace, string name)
8868 foreach (object o in git.GenericArguments) {
8869 - if (IsGenericParameter (o, fullname))
8870 + if (IsGenericParameter (o, nameSpace, name))
8873 GenericInstanceType inner = (o as GenericInstanceType);
8874 - if ((inner != null) && (FindGenericType (inner, fullname)))
8875 + if ((inner != null) && (FindGenericType (inner, nameSpace, name)))
8881 - static bool IsGenericParameter (object obj, string fullname)
8882 + static bool IsGenericParameter (object obj, string nameSpace, string name)
8884 - GenericParameter gp = (obj as GenericParameter);
8885 - return ((gp != null) && (gp.FullName == fullname));
8886 + return (obj as GenericParameter).IsNamed (nameSpace, name);
8889 - static bool IsGenericType (MemberReference type, string fullname)
8890 + static bool IsGenericType (TypeReference type, string nspace, string name)
8892 - if (type.FullName == fullname)
8893 + if (type.IsNamed (nspace, name))
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))
8901 // handle things like ICollection<T>
8902 @@ -126,7 +114,7 @@ namespace Gendarme.Rules.Design.Generic {
8906 - return FindGenericType (git, fullname);
8907 + return FindGenericType (git, nspace, name);
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;
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)) {
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;
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);
8939 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotDeclareStaticMembersOnGenericTypesRule.cs
8940 index 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 {
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.
8954 /// public class BadClass<T> {
8955 - /// public static string member () {
8956 + /// public static string Member () {
8960 @@ -48,16 +49,16 @@ namespace Gendarme.Rules.Design.Generic {
8963 /// public class GoodClass<T> {
8964 - /// public string member () {
8965 + /// public string Member () {
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)
8979 if (!type.IsClass || !type.HasGenericParameters || !type.IsVisible ())
8980 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeGenericListsRule.cs
8981 index 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 {
8988 - /// A type has an externally visible member that is, returns, or has a signature containing a
8989 - /// System.Collections.Generic.List<T>.
8990 + /// A type has an externally visible member that is, returns or has a signature containing a
8991 + /// <c>System.Collections.Generic.List<T></c>.
8995 @@ -56,17 +56,17 @@ namespace Gendarme.Rules.Design.Generic {
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";
9008 private static bool IsList (TypeReference type)
9010 return type.Namespace == "System.Collections.Generic" &&
9011 - type.Name.StartsWith (List);
9012 + type.Name.StartsWith (List, StringComparison.Ordinal);
9015 private void CheckField (FieldReference field)
9016 @@ -80,9 +80,7 @@ namespace Gendarme.Rules.Design.Generic {
9017 if (!IsList (property.PropertyType))
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);
9027 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/DoNotExposeNestedGenericSignaturesRule.cs
9028 index 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<List<int>></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<T></c> this specific case is ignored by the rule.
9036 + /// <c>System.Nullable<T></c> this specific case is ignored by the rule.
9040 @@ -63,23 +63,11 @@ namespace Gendarme.Rules.Design.Generic {
9044 - /// <remarks>This rule is available since Gendarme 2.4</remarks>
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 {
9052 - public override void Initialize (IRunner runner)
9054 - base.Initialize (runner);
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);
9062 + public class DoNotExposeNestedGenericSignaturesRule : GenericsBaseRule, IMethodRule {
9064 static Severity? Check (TypeReference type)
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"))
9073 // FIXME: we should look at ignoring LINQ queries too, because it
9074 // too pretty much hides the complexity of nested generics
9075 diff --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
9076 index 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
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
9084 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
9085 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
9114 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
9115 <DebugSymbols>true</DebugSymbols>
\r
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
9122 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
9123 <DebugType>pdbonly</DebugType>
\r
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
9131 <Reference Include="System" />
\r
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
9141 <Name>Gendarme.Framework</Name>
\r
9142 </ProjectReference>
\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
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.
9164 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs
9165 new file mode 100644
9166 index 0000000..12be75c
9168 +++ b/gendarme/rules/Gendarme.Rules.Design.Generic/GenericsBaseRule.cs
9171 +// Gendarme.Rules.Design.Generic.GenericBaseRule
9174 +// Sebastien Pouliot <sebastien@ximian.com>
9176 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
9186 +// The above copyright notice and this permission notice shall be
9187 +// included in all copies or substantial portions of the Software.
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.
9201 +using Gendarme.Framework;
9203 +namespace Gendarme.Rules.Design.Generic {
9205 + public abstract class GenericsBaseRule : Rule {
9207 + public override void Initialize (IRunner runner)
9209 + base.Initialize (runner);
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);
9220 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/ImplementGenericCollectionInterfacesRule.cs
9221 index 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 {
9228 - /// This rule checks for types which implement the non-generic IEnumerable interface but
9229 - /// not the IEnumerable<T> 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<T></code> interface. Implementing the generic version
9233 + /// of <code>System.IEnumerable</code> avoids casts, and possibly boxing, when iterating the collection.
9237 @@ -64,23 +64,11 @@ namespace Gendarme.Rules.Design.Generic {
9241 - /// <remarks>Before Gendarme 2.2 this rule was part of Gendarme.Rules.Design assembly.</remarks>
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 {
9249 - public override void Initialize (IRunner runner)
9251 - base.Initialize (runner);
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);
9259 + public class ImplementGenericCollectionInterfacesRule : GenericsBaseRule, ITypeRule {
9261 public RuleResult CheckType (TypeDefinition type)
9263 @@ -93,15 +81,15 @@ namespace Gendarme.Rules.Design.Generic {
9264 return RuleResult.DoesNotApply;
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;
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;
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);
9281 return Runner.CurrentRuleResult;
9282 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am b/gendarme/rules/Gendarme.Rules.Design.Generic/Makefile.am
9283 index 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
9294 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/PreferGenericsOverRefObjectRule.cs
9295 index 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 {
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.
9307 @@ -61,23 +61,11 @@ namespace Gendarme.Rules.Design.Generic {
9311 - /// <remarks>This rule is available since Gendarme 2.2</remarks>
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 {
9319 - public override void Initialize (IRunner runner)
9321 - base.Initialize (runner);
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);
9329 + public class PreferGenericsOverRefObjectRule : GenericsBaseRule, IMethodRule {
9331 public RuleResult CheckMethod (MethodDefinition method)
9333 @@ -86,11 +74,11 @@ namespace Gendarme.Rules.Design.Generic {
9334 return RuleResult.DoesNotApply;
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;
9341 foreach (ParameterDefinition parameter in method.Parameters) {
9342 - if (parameter.ParameterType.FullName != "System.Object&")
9343 + if (!parameter.ParameterType.IsNamed ("System", "Object&"))
9346 // suggest using generics
9347 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/README.md b/gendarme/rules/Gendarme.Rules.Design.Generic/README.md
9348 new file mode 100644
9349 index 0000000..f7ce631
9351 +++ b/gendarme/rules/Gendarme.Rules.Design.Generic/README.md
9353 +# Gendarme.Rules.Design.Generic Rules
9355 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Generic(git)]] pages.
9360 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
9362 diff --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
9363 index 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
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
9371 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
9372 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
9401 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
9402 <DebugSymbols>true</DebugSymbols>
\r
9404 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
9405 <ErrorReport>prompt</ErrorReport>
\r
9406 <WarningLevel>4</WarningLevel>
\r
9407 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
9409 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
9410 <DebugType>pdbonly</DebugType>
\r
9412 <DefineConstants>TRACE</DefineConstants>
\r
9413 <ErrorReport>prompt</ErrorReport>
\r
9414 <WarningLevel>4</WarningLevel>
\r
9415 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
9418 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
9421 <Folder Include="Properties\" />
\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
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.
9443 diff --git a/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs b/gendarme/rules/Gendarme.Rules.Design.Generic/UseGenericEventHandlerRule.cs
9444 index 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 {
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<TEventArgs></c>.
9453 + /// This rule fires if an assembly defines a delegate which can be
9454 + /// replaced by <c>System.EventHandler<TEventArgs></c>.
9458 @@ -57,23 +57,11 @@ namespace Gendarme.Rules.Design.Generic {
9459 /// public event EventHandler<AuthenticityEventArgs> CheckedAuthenticity;
9462 - /// <remarks>This rule is available since Gendarme 2.2</remarks>
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 {
9470 - public override void Initialize (IRunner runner)
9472 - base.Initialize (runner);
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);
9480 + public class UseGenericEventHandlerRule : GenericsBaseRule, ITypeRule {
9482 public RuleResult CheckType (TypeDefinition type)
9484 @@ -86,7 +74,7 @@ namespace Gendarme.Rules.Design.Generic {
9486 return RuleResult.DoesNotApply;
9488 - if (invoke.ReturnType.FullName != "System.Void")
9489 + if (!invoke.ReturnType.IsNamed ("System", "Void"))
9490 return RuleResult.Success;
9492 if (!invoke.HasParameters)
9493 @@ -95,9 +83,9 @@ namespace Gendarme.Rules.Design.Generic {
9494 IList<ParameterDefinition> pdc = invoke.Parameters;
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;
9504 Runner.Report (type, Severity.Medium, Confidence.High);
9505 diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs b/gendarme/rules/Gendarme.Rules.Design.Linq/AvoidExtensionMethodOnSystemObjectRule.cs
9506 index 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");
9523 @@ -92,7 +95,7 @@ namespace Gendarme.Rules.Design.Linq {
9524 if (!method.HasParameters)
9527 - return method.HasAttribute ("System.Runtime.CompilerServices.ExtensionAttribute");
9528 + return method.HasAttribute ("System.Runtime.CompilerServices", "ExtensionAttribute");
9531 public RuleResult CheckMethod (MethodDefinition method)
9532 @@ -100,7 +103,7 @@ namespace Gendarme.Rules.Design.Linq {
9533 if (!IsExtension (method))
9534 return RuleResult.DoesNotApply;
9536 - if (method.Parameters [0].ParameterType.FullName != "System.Object")
9537 + if (!method.Parameters [0].ParameterType.IsNamed ("System", "Object"))
9538 return RuleResult.Success;
9540 Runner.Report (method, Severity.High, Confidence.High);
9541 diff --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
9542 index 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
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
9550 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
9551 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
9580 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
9581 <DebugSymbols>true</DebugSymbols>
\r
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
9588 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
9589 <DebugType>pdbonly</DebugType>
\r
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
9597 <Reference Include="System" />
\r
9599 <Name>Gendarme.Framework</Name>
\r
9600 </ProjectReference>
\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
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
9622 diff --git a/gendarme/rules/Gendarme.Rules.Design.Linq/README.md b/gendarme/rules/Gendarme.Rules.Design.Linq/README.md
9623 new file mode 100644
9624 index 0000000..d80660c
9626 +++ b/gendarme/rules/Gendarme.Rules.Design.Linq/README.md
9628 +# Gendarme.Rules.Design.Linq Rules
9630 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.Linq(git)]] pages.
9635 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
9637 diff --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
9638 index 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
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
9646 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
9647 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
9676 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
9677 <DebugSymbols>true</DebugSymbols>
\r
9679 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
9680 <ErrorReport>prompt</ErrorReport>
\r
9681 <WarningLevel>4</WarningLevel>
\r
9682 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
9684 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
9685 <DebugType>pdbonly</DebugType>
\r
9687 <DefineConstants>TRACE</DefineConstants>
\r
9688 <ErrorReport>prompt</ErrorReport>
\r
9689 <WarningLevel>4</WarningLevel>
\r
9690 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
9693 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
9696 <Folder Include="Properties\" />
\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
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.
9718 diff --git a/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs b/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9719 index df472de..cc037aa 100644
9720 --- a/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9721 +++ b/gendarme/rules/Gendarme.Rules.Design/AttributeArgumentsShouldHaveAccessorsRule.cs
9725 using System.Collections.Generic;
9726 +using System.Globalization;
9730 @@ -106,11 +107,18 @@ namespace Gendarme.Rules.Design {
9732 // look through getters
9733 allProperties.Clear ();
9734 - foreach (PropertyDefinition property in type.Properties) {
9735 - if (property.GetMethod != null) {
9736 - allProperties.Add (property.Name);
9738 + TypeDefinition t = type;
9739 + // Walk up the inheritance tree so that inherited properties are counted
9742 + foreach (PropertyDefinition property in t.Properties) {
9743 + if (property.GetMethod != null) {
9744 + allProperties.Add (property.Name);
9748 + t = t.BaseType != null ? t.BaseType.Resolve () : null;
9749 + } while (t != null && !t.IsNamed ("System", "Attribute"));
9751 // look through parameters
9752 foreach (MethodDefinition constructor in type.Methods) {
9753 @@ -119,9 +127,11 @@ namespace Gendarme.Rules.Design {
9755 foreach (ParameterDefinition param in constructor.Parameters) {
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)
9767 diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9768 index 0641913..9932c47 100644
9769 --- a/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9770 +++ b/gendarme/rules/Gendarme.Rules.Design/AvoidPublicInstanceFieldsRule.cs
9775 +using System.Globalization;
9779 @@ -89,11 +90,13 @@ namespace Gendarme.Rules.Design {
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);
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);
9796 diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9797 index 2e86234..b8828e9 100644
9798 --- a/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9799 +++ b/gendarme/rules/Gendarme.Rules.Design/AvoidRefAndOutParametersRule.cs
9804 +using System.Globalization;
9807 using Gendarme.Framework;
9808 @@ -139,7 +140,7 @@ namespace Gendarme.Rules.Design {
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)) {
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);
9827 diff --git a/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs b/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9828 index 138b556..76f590a 100644
9829 --- a/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9830 +++ b/gendarme/rules/Gendarme.Rules.Design/AvoidSmallNamespaceRule.cs
9833 using System.Collections.Generic;
9834 using System.ComponentModel;
9835 +using System.Globalization;
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));
9849 diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9850 index 342218f..ddcb92a 100644
9851 --- a/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9852 +++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderAddingInterfaceRule.cs
9856 using System.Collections.Generic;
9857 +using System.Globalization;
9861 @@ -143,7 +144,8 @@ namespace Gendarme.Rules.Design {
9862 if (HasConstraints (type))
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));
9871 @@ -165,7 +167,7 @@ namespace Gendarme.Rules.Design {
9874 //type already publicly says it implements the interface
9875 - if (type.Implements (iface.FullName))
9876 + if (type.Implements (iface.Namespace, iface.Name))
9879 foreach (MethodDefinition m in mdc) {
9880 diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9881 index 453fc23..e5ffcfc 100644
9882 --- a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9883 +++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingFieldToNullableRule.cs
9888 +using System.Globalization;
9892 @@ -75,7 +76,7 @@ namespace Gendarme.Rules.Design {
9894 static bool IsHasField (FieldReference fd, ref string prefix, ref string suffix)
9896 - if (fd.FieldType.FullName != "System.Boolean")
9897 + if (!fd.FieldType.IsNamed ("System", "Boolean"))
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.",
9910 Runner.Report (fd, Severity.Low, Confidence.Low, s);
9912 @@ -140,7 +143,7 @@ namespace Gendarme.Rules.Design {
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))
9921 diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderConvertingMethodToPropertyRule.cs
9922 index 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)
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 ();
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);
9946 diff --git a/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs b/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9947 index d6a5691..d024c20 100644
9948 --- a/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9949 +++ b/gendarme/rules/Gendarme.Rules.Design/ConsiderUsingStaticTypeRule.cs
9952 // Sebastien Pouliot <sebastien@ximian.com>
9954 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9955 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
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 {
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>.
9970 @@ -51,7 +51,7 @@ namespace Gendarme.Rules.Design {
9975 + /// Good example (targetting CLR 2.0 and later):
9977 /// public static class Class {
9978 /// public static void Method ()
9979 @@ -60,22 +60,22 @@ namespace Gendarme.Rules.Design {
9984 + /// Good example (targetting CLR 1.x):
9986 + /// public sealed class Class {
9987 + /// public static void Method ()
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 {
10000 - public override void Initialize (IRunner runner)
10002 - base.Initialize (runner);
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);
10011 static bool IsAllStatic (TypeDefinition type)
10013 if (type.HasMethods) {
10014 @@ -99,31 +99,15 @@ namespace Gendarme.Rules.Design {
10018 - static int GetMethodCount (TypeDefinition type)
10020 - if (!type.HasMethods)
10025 - foreach (var method in type.Methods) {
10026 - if (!method.IsConstructor)
10033 public RuleResult CheckType (TypeDefinition type)
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;
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;
10049 if (IsAllStatic (type)) {
10050 diff --git a/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
10051 index 82386a2..d6cf62b 100644
10052 --- a/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
10053 +++ b/gendarme/rules/Gendarme.Rules.Design/DeclareEventHandlersCorrectlyRule.cs
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 {
10064 private bool CheckReturnVoid (IMetadataTokenProvider eventType, IMethodSignature invoke)
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"))
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);
10078 @@ -112,14 +114,16 @@ namespace Gendarme.Rules.Design {
10079 IList<ParameterDefinition> pdc = invoke.Parameters;
10080 int count = pdc.Count;
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);
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");
10099 @@ -129,10 +133,12 @@ namespace Gendarme.Rules.Design {
10101 private bool CheckParameterName (IMetadataTokenProvider eventType, ParameterReference invokeParameter, string expectedName)
10103 - if (String.Compare (invokeParameter.Name, expectedName) == 0)
10104 + if (invokeParameter.Name == expectedName)
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);
10114 @@ -189,9 +195,9 @@ namespace Gendarme.Rules.Design {
10118 - private bool CheckGenericDelegate (MemberReference type)
10119 + private bool CheckGenericDelegate (TypeReference type)
10121 - if (type.FullName == "System.EventHandler`1")
10122 + if (type.IsNamed ("System", "EventHandler`1"))
10125 Runner.Report (type, Severity.Medium, Confidence.High, "Generic delegates should use EventHandler<TEventArgs>");
10126 diff --git a/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs b/gendarme/rules/Gendarme.Rules.Design/DisposableTypesShouldHaveFinalizerRule.cs
10127 index 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;
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;
10138 // no problem is a finalizer is found
10139 diff --git a/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs b/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs
10140 new file mode 100644
10141 index 0000000..37c7b8c
10143 +++ b/gendarme/rules/Gendarme.Rules.Design/DoNotDeclareSettersOnCollectionPropertiesRule.cs
10146 +// Gendarme.Rules.Design.DoNotDeclareSettersOnCollectionPropertiesRule
10149 +// Sebastien Pouliot <sebastien@ximian.com>
10151 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
10160 +// The above copyright notice and this permission notice shall be included in
10161 +// all copies or substantial portions of the Software.
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
10173 +using Gendarme.Framework;
10174 +using Gendarme.Framework.Rocks;
10176 +namespace Gendarme.Rules.Design {
10179 + /// The rule detect <c>System.Collections.ICollection</c> and
10180 + /// <c>System.Collections.Generic.ICollection<T></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.
10189 + /// public class Holder {
10190 + /// public string Name { get; set; }
10191 + /// public ICollection<string> List { get; set; }
10194 + /// public static Holder Copy (Holder h)
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);
10206 + /// Good example:
10208 + /// public class Holder {
10209 + /// List<string> list;
10211 + /// public Holder ()
10213 + /// list = new List<string> ();
10216 + /// public string Name { get; set; }
10218 + /// public ICollection<string> List {
10219 + /// get { return list; }
10223 + /// public static Holder Copy (Holder h)
10225 + /// Holder copy = new Holder ();
10226 + /// copy.Name = h.Name;
10227 + /// copy.List.AddRange (h.List);
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 {
10237 + static bool IsICollection (TypeReference type)
10239 + if (type.Implements ("System.Collections", "ICollection"))
10242 + return type.Implements ("System.Collections.Generic", "ICollection`1");
10245 + static bool IsSpecialCase (TypeReference type)
10247 + return type.Inherits ("System.Security", "PermissionSet");
10250 + public RuleResult CheckType (TypeDefinition type)
10252 + if (!type.HasProperties || !type.IsVisible ())
10253 + return RuleResult.DoesNotApply;
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 ()))
10261 + TypeReference ptype = pd.PropertyType;
10262 + if (IsICollection (ptype) && !IsSpecialCase (ptype))
10263 + Runner.Report (setter, Severity.Medium, Confidence.High);
10265 + return Runner.CurrentRuleResult;
10269 diff --git a/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs b/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10270 index 7f45898..33d8fce 100644
10271 --- a/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10272 +++ b/gendarme/rules/Gendarme.Rules.Design/EnsureSymmetryForOverloadedOperatorsRule.cs
10276 using System.Collections.Generic;
10277 +using System.Globalization;
10280 using Gendarme.Framework;
10281 @@ -124,7 +125,7 @@ namespace Gendarme.Rules.Design {
10282 return; //both are defined
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);
10290 diff --git a/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/EnumeratorsShouldBeStronglyTypedRule.cs
10291 index 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 {
10298 + private MethodSignature [] Empty = { };
10299 + private static string [] Current = { "Current" };
10301 protected override MethodSignature [] GetMethods ()
10303 - return new MethodSignature [] { };
10307 protected override string [] GetProperties ()
10309 - return new string [] { "Current" };
10313 protected override string InterfaceName {
10314 - get { return "System.Collections.IEnumerator"; }
10315 + get { return "IEnumerator"; }
10318 + protected override string InterfaceNamespace {
10319 + get { return "System.Collections"; }
10322 override public RuleResult CheckType (TypeDefinition type)
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;
10340 TypeDefinition td = baseType.Resolve ();
10342 baseType = td.BaseType;
10343 diff --git a/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs b/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10344 index 13460c2..3d2da47 100644
10345 --- a/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10346 +++ b/gendarme/rules/Gendarme.Rules.Design/EnumsShouldUseInt32Rule.cs
10351 +using System.Globalization;
10355 @@ -89,33 +90,36 @@ namespace Gendarme.Rules.Design {
10359 - string value_type = null;
10360 + TypeReference ftype = null;
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;
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) {
10383 + return RuleResult.Success;
10384 + // some are bad choice (when possible) but usable by all CLS compliant languages
10388 severity = Severity.High;
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;
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;
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;
10408 diff --git a/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj b/gendarme/rules/Gendarme.Rules.Design/Gendarme.Rules.Design.csproj
10409 index 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
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
10417 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
10418 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
10447 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
10448 <DebugSymbols>true</DebugSymbols>
\r
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
10455 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
10456 <DebugType>pdbonly</DebugType>
\r
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
10464 <Reference Include="System" />
\r
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
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
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.
10498 diff --git a/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs b/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10499 index 14e555f..c1e01c5 100644
10500 --- a/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10501 +++ b/gendarme/rules/Gendarme.Rules.Design/ImplementEqualsAndGetHashCodeInPairRule.cs
10506 +using System.Globalization;
10510 @@ -99,13 +100,13 @@ namespace Gendarme.Rules.Design {
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);
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);
10526 diff --git a/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs b/gendarme/rules/Gendarme.Rules.Design/ImplementIComparableCorreclyRule.cs
10527 index 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")
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;
10542 diff --git a/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/ListsAreStronglyTypedRule.cs
10543 index 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
10552 + public class ListsAreStronglyTypedRule : StronglyTypedRule, ITypeRule {
10554 + private static string [] Item = new string [] { "Item" };
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);
10564 + private static MethodSignature [] Signatures = {
10572 protected override MethodSignature [] GetMethods ()
10574 - return new MethodSignature[] {
10581 + return Signatures;
10584 protected override string [] GetProperties ()
10586 - return new string [] { "Item" };
10590 protected override string InterfaceName {
10591 - get { return "System.Collections.IList"; }
10592 + get { return "IList"; }
10595 + protected override string InterfaceNamespace {
10596 + get { return "System.Collections"; }
10600 diff --git a/gendarme/rules/Gendarme.Rules.Design/Makefile.am b/gendarme/rules/Gendarme.Rules.Design/Makefile.am
10601 index 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
10638 diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithAttributeRule.cs
10639 index 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 {
10644 abstract public class MarkAssemblyWithAttributeRule : Rule, IAssemblyRule {
10646 + abstract protected string AttributeNamespace { get; }
10647 abstract protected string AttributeName { get; }
10649 abstract protected Severity Severity { get; }
10650 @@ -47,7 +48,7 @@ namespace Gendarme.Rules.Design {
10651 if (!assembly.HasCustomAttributes)
10652 return RuleResult.DoesNotApply;
10654 - if (assembly.HasAttribute (AttributeName))
10655 + if (assembly.HasAttribute (AttributeNamespace, AttributeName))
10656 return RuleResult.Success;
10658 Runner.Report (assembly, Severity, Confidence.Total);
10659 diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithCLSCompliantRule.cs
10660 index 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 {
10667 + protected override string AttributeNamespace {
10668 + get { return "System"; }
10671 protected override string AttributeName {
10672 - get { return "System.CLSCompliantAttribute"; }
10673 + get { return "CLSCompliantAttribute"; }
10676 protected override Severity Severity {
10677 diff --git a/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Design/MarkAssemblyWithComVisibleRule.cs
10678 index 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 {
10685 + protected override string AttributeNamespace {
10686 + get { return "System.Runtime.InteropServices"; }
10689 protected override string AttributeName {
10690 - get { return "System.Runtime.InteropServices.ComVisibleAttribute"; }
10691 + get { return "ComVisibleAttribute"; }
10694 protected override Severity Severity {
10695 diff --git a/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/MissingAttributeUsageOnCustomAttributeRule.cs
10696 index 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 {
10703 - private const string AttributeUsageAttribute = "System.AttributeUsageAttribute";
10705 public RuleResult CheckType (TypeDefinition type)
10707 // rule applies only to attributes
10708 if (!type.IsAttribute ())
10709 return RuleResult.DoesNotApply;
10711 - if (type.HasAttribute (AttributeUsageAttribute)) // it's ok
10712 + if (type.HasAttribute ("System", "AttributeUsageAttribute")) // it's ok
10713 return RuleResult.Success;
10715 Runner.Report (type, Severity.High, Confidence.Total);
10716 diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferIntegerOrStringForIndexersRule.cs
10717 index 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;
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
10731 - Runner.Report (parameter, Severity.Medium, Confidence.Total);
10733 + TypeReference ptype = parameter.ParameterType;
10734 + bool ok = (ptype.Namespace == "System");
10736 + switch (ptype.Name) {
10740 + case "Object": // tolerable in some circumstances
10748 + Runner.Report (parameter, Severity.Medium, Confidence.Total);
10750 return Runner.CurrentRuleResult;
10752 diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferUriOverStringRule.cs
10753 index 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;
10759 using System.Collections.Generic;
10760 +using System.Globalization;
10762 namespace Gendarme.Rules.Design {
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]))
10771 index += token.Length;
10773 @@ -110,10 +111,10 @@ namespace Gendarme.Rules.Design {
10774 private static bool IsUri (string memberName)
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)
10782 - if (url_enders.Contains (char.ToLower (memberName [index + 2])))
10783 + if (url_enders.Contains(Char.ToLower(memberName[index + 2], CultureInfo.InvariantCulture)))
10787 @@ -159,7 +160,7 @@ namespace Gendarme.Rules.Design {
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"))
10795 var methodParams = method.Parameters;
10796 diff --git a/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs b/gendarme/rules/Gendarme.Rules.Design/PreferXmlAbstractionsRule.cs
10797 index 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 {
10804 - const string XmlDocumentClass = "System.Xml.XmlDocument";
10805 - const string XPathDocumentClass = "System.Xml.XPath.XPathDocument";
10806 - const string XmlNodeClass = "System.Xml.XmlNode";
10808 public override void Initialize (IRunner runner)
10810 base.Initialize (runner);
10811 @@ -119,7 +115,7 @@ namespace Gendarme.Rules.Design {
10812 return RuleResult.DoesNotApply;
10814 MethodReturnType mrt = method.MethodReturnType;
10815 - if (IsSpecificXmlType (mrt.ReturnType.FullName))
10816 + if (IsSpecificXmlType (mrt.ReturnType))
10817 Runner.Report (mrt, GetSeverity (method), Confidence.High);
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
10824 - if (IsSpecificXmlType (parameter.ParameterType.FullName))
10825 + if (IsSpecificXmlType (parameter.ParameterType))
10826 Runner.Report (parameter, GetSeverity (method), Confidence.High);
10829 @@ -135,9 +131,13 @@ namespace Gendarme.Rules.Design {
10830 return Runner.CurrentRuleResult;
10833 - static bool IsSpecificXmlType (string name)
10834 + static bool IsSpecificXmlType (TypeReference type)
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"));
10841 + return type.IsNamed ("System.Xml.XPath", "XPathDocument");
10844 static Severity GetSeverity (MethodDefinition method)
10845 diff --git a/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs b/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10846 index 1e1347e..e2197c5 100644
10847 --- a/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10848 +++ b/gendarme/rules/Gendarme.Rules.Design/ProvideAlternativeNamesForOperatorOverloadsRule.cs
10852 using System.Collections.Generic;
10853 +using System.Globalization;
10856 using Gendarme.Framework;
10857 @@ -171,7 +172,8 @@ namespace Gendarme.Rules.Design {
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);
10867 diff --git a/gendarme/rules/Gendarme.Rules.Design/README.md b/gendarme/rules/Gendarme.Rules.Design/README.md
10868 new file mode 100644
10869 index 0000000..22a4957
10871 +++ b/gendarme/rules/Gendarme.Rules.Design/README.md
10873 +# Gendarme.Rules.Design Rules
10875 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design(git)]] pages.
10880 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
10882 diff --git a/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs b/gendarme/rules/Gendarme.Rules.Design/StronglyTypeICollectionMembersRule.cs
10883 index 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
10892 + public class StronglyTypeICollectionMembersRule : StronglyTypedRule, ITypeRule {
10894 - private static MethodSignature CopyTo = new MethodSignature("CopyTo", "System.Void",
10895 - new string[] {"System.Array", "System.Int32"});
10896 + private static string [] Empty = new string [] { };
10898 + private static MethodSignature [] CopyTo = new MethodSignature [] {
10899 + new MethodSignature ("CopyTo", "System.Void", new string [] { "System.Array", "System.Int32" })
10902 protected override MethodSignature [] GetMethods ()
10904 - return new MethodSignature [] { CopyTo };
10908 protected override string [] GetProperties ()
10910 - return new string [] { };
10914 protected override string InterfaceName {
10915 - get { return "System.Collections.ICollection"; }
10916 + get { return "ICollection"; }
10919 + protected override string InterfaceNamespace {
10920 + get { return "System.Collections"; }
10924 diff --git a/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs b/gendarme/rules/Gendarme.Rules.Design/StronglyTypedRule.cs
10925 index 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; }
10933 - HashSet<string> weakTypes = new HashSet<string> {
10936 - "System.Object[]",
10938 + abstract protected string InterfaceNamespace { get; }
10940 MethodSignature [] signatures;
10941 string [] propertyNames;
10942 @@ -55,7 +50,7 @@ namespace Gendarme.Rules.Design {
10944 virtual public RuleResult CheckType (TypeDefinition type)
10946 - if (type.IsAbstract || type.IsGeneratedCode () || !type.Implements (InterfaceName))
10947 + if (type.IsAbstract || type.IsGeneratedCode () || !type.Implements (InterfaceNamespace, InterfaceName))
10948 return RuleResult.DoesNotApply;
10950 signatures = GetMethods ();
10951 @@ -106,13 +101,26 @@ namespace Gendarme.Rules.Design {
10952 ProcessProperties (baseType);
10955 + static bool IsWeak (TypeReference type)
10957 + if (type.Namespace != "System")
10959 + string name = type.Name;
10960 + return ((name == "Object") || (name == "Array") || (name == "Object[]"));
10963 + static bool IsWeak (string typeName)
10965 + return ((typeName == "System.Object") || (typeName == "System.Array") || (typeName == "System.Object[]"));
10968 private void ProcessProperties (TypeDefinition baseType)
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)
10974 - if (!weakTypes.Contains (property.PropertyType.FullName)) {
10975 + if (!IsWeak (property.PropertyType)) {
10977 propertyNames [i] = null;
10979 @@ -133,9 +141,9 @@ namespace Gendarme.Rules.Design {
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]))
10986 - if (weakTypes.Contains (methodParameters [j].ParameterType.FullName))
10987 + if (IsWeak (methodParameters [j].ParameterType))
10988 foundStrong = false;
10991 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/AttributeArgumentsShouldHaveAccessorsTest.cs
10992 index 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 {
10999 + internal abstract class FooAttribute : Attribute
11001 + protected FooAttribute (string foo)
11006 + public string Foo
11013 + internal class FooBarAttribute : FooAttribute
11015 + protected FooBarAttribute (string foo, string bar) : base (foo)
11020 + public string Bar
11029 public class AttributeArgumentsShouldHaveAccessorsTest : TypeRuleTestFixture<AttributeArgumentsShouldHaveAccessorsRule> {
11031 @@ -252,5 +281,11 @@ namespace Test.Rules.Design {
11033 AssertRuleFailure<TwoAccessorsMissingAttribute> (2);
11037 + public void TestInheritedPropertiesAttribute ()
11039 + AssertRuleSuccess<FooBarAttribute> ();
11043 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11044 index 9e9c707..8e55722 100644
11045 --- a/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11046 +++ b/gendarme/rules/Gendarme.Rules.Design/Test/ConsiderUsingStaticTypeTest.cs
11049 // Sebastien Pouliot <sebastien@ximian.com>
11051 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11052 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
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 {
11060 - public void SkipOnEmptyClassTest ()
11061 + public void EmptyClassHasDefaultPublicInstanceCtor ()
11063 - AssertRuleDoesNotApply<EmptyClass> ();
11064 + AssertRuleFailure<EmptyClass> ();
11067 //You cannot do this class static
11068 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs
11069 new file mode 100644
11070 index 0000000..4e22ddd
11072 +++ b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareSettersOnCollectionPropertiesTest.cs
11075 +// Unit tests for DoNotDeclareSettersOnCollectionPropertiesRule
11078 +// Sebastien Pouliot <sebastien@ximian.com>
11080 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
11089 +// The above copyright notice and this permission notice shall be included in
11090 +// all copies or substantial portions of the Software.
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
11101 +using System.Collections;
11102 +using System.Collections.Generic;
11103 +using System.Security;
11105 +using Gendarme.Rules.Design;
11107 +using NUnit.Framework;
11108 +using Test.Rules.Fixtures;
11109 +using Test.Rules.Definitions;
11111 +namespace Test.Rules.Design {
11114 + public class DoNotDeclareSettersOnCollectionPropertiesTest : TypeRuleTestFixture<DoNotDeclareSettersOnCollectionPropertiesRule> {
11117 + public void DoesNotApply ()
11119 + AssertRuleDoesNotApply (SimpleTypes.Class);
11120 + AssertRuleDoesNotApply (SimpleTypes.Delegate);
11121 + AssertRuleDoesNotApply (SimpleTypes.Enum);
11122 + AssertRuleDoesNotApply (SimpleTypes.GeneratedType);
11123 + AssertRuleDoesNotApply (SimpleTypes.Interface);
11124 + AssertRuleDoesNotApply (SimpleTypes.Structure);
11127 + public interface IGoodInterface {
11128 + ICollection Collection { get; }
11129 + ICollection<string> GenericCollection { get; }
11132 + public class TypeImplementingGoodInterface : IGoodInterface {
11133 + public ICollection Collection { get; private set; }
11134 + public ICollection<string> GenericCollection { get; private set; }
11137 + public struct GoodStruct {
11138 + private ArrayList list;
11140 + public IDictionary Dictionary { get; private set; }
11141 + public ArrayList List {
11142 + get { return list; }
11147 + public void Good ()
11149 + AssertRuleSuccess<IGoodInterface> ();
11150 + AssertRuleSuccess<TypeImplementingGoodInterface> ();
11151 + AssertRuleSuccess<GoodStruct> ();
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; }
11160 + public class TypeImplementingBadInterface : IBadInterface {
11161 + public ICollection Collection { get; set; }
11162 + public ICollection<string> GenericCollection { get; set; }
11165 + public struct BadStruct {
11166 + public IDictionary Dictionary { private get; set; }
11167 + public ArrayList List { get; set; }
11171 + public void Bad ()
11173 + AssertRuleFailure<IBadInterface> (2);
11174 + AssertRuleFailure<TypeImplementingBadInterface> (2);
11175 + AssertRuleFailure<BadStruct> (2);
11178 + public class SecurityPermissions {
11179 + public PermissionSet Permissions { get; set; }
11180 + public NamedPermissionSet NamedPermissions { get; set; }
11183 + public class Indexers {
11186 + public int this [int index] {
11187 + get { return array [index]; }
11188 + set { array [index] = value; }
11191 + public int this [int x, int y] {
11192 + get { return array [x]; }
11193 + set { array [y] = value; }
11197 + public class Arrays {
11199 + public Array Array { get; set; }
11203 + public void SpecialCases ()
11205 + AssertRuleSuccess<SecurityPermissions> ();
11206 + AssertRuleSuccess<Indexers> ();
11207 + AssertRuleFailure<Arrays> (1);
11211 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11212 index f495193..c5ae0ef 100644
11213 --- a/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11214 +++ b/gendarme/rules/Gendarme.Rules.Design/Test/DoNotDeclareVirtualMethodsInSealedTypeTest.cs
11217 // Sebastien Pouliot <sebastien@ximian.com>
11219 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11220 +// Copyright (C) 2008,2011 Novell, Inc (http://www.novell.com)
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
11228 +using System.Collections.Generic;
11231 using Gendarme.Rules.Design;
11232 @@ -103,7 +104,7 @@ namespace Test.Rules.Design {
11235 public abstract class AbstractClass {
11236 - public abstract string GetIt ();
11237 + public abstract string GetZit ();
11240 public sealed class SealedClass : AbstractClass {
11241 @@ -113,7 +114,7 @@ namespace Test.Rules.Design {
11245 - public override string GetIt ()
11246 + public override string GetZit ()
11248 return String.Empty;
11250 @@ -130,5 +131,34 @@ namespace Test.Rules.Design {
11251 AssertRuleDoesNotApply<AbstractClass> ();
11252 AssertRuleSuccess<SealedClass> ();
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> {
11259 + public override int GetHashCode (string obj)
11263 + return obj.GetHashCode ();
11266 + public override bool Equals (string x, string y)
11269 + return y == null;
11271 + if ((object) x == (object) y)
11274 + return x.Equals (y);
11279 + public void Generic ()
11281 + AssertRuleSuccess<InternalStringComparer> ();
11285 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/PreferUriOverStringTest.cs
11286 index 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 {
11293 + public string CUR
11299 public Uri GetUri ()
11301 @@ -117,6 +122,7 @@ namespace Test.Rules.Design {
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) });
11309 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj b/gendarme/rules/Gendarme.Rules.Design/Test/Tests.Rules.Design.csproj
11310 index 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
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
11318 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
11319 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
11348 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
11349 <DebugSymbols>true</DebugSymbols>
\r
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
11357 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
11358 <DebugType>pdbonly</DebugType>
\r
11360 <DefineConstants>TRACE</DefineConstants>
\r
11361 <ErrorReport>prompt</ErrorReport>
\r
11362 <WarningLevel>4</WarningLevel>
\r
11363 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
11366 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
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 @@
11378 <Folder Include="Properties\" />
\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
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.
11400 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
11401 deleted file mode 100644
11402 index 811ba7e..0000000
11403 --- a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithDisposableFieldsShouldBeDisposableTest.cs
11407 -// Unit tests for TypesWithDisposableFieldsShouldBeDisposableRule
11410 -// Andreas Noever <andreas.noever@gmail.com>
11411 -// Sebastien Pouliot <sebastien@ximian.com>
11413 -// (C) 2008 Andreas Noever
11414 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
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:
11424 -// The above copyright notice and this permission notice shall be
11425 -// included in all copies or substantial portions of the Software.
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.
11438 -using Gendarme.Rules.Design;
11440 -using NUnit.Framework;
11441 -using Test.Rules.Definitions;
11442 -using Test.Rules.Fixtures;
11444 -namespace Test.Rules.Design {
11446 - class Disposable : IDisposable {
11447 - public void Dispose ()
11449 - throw new NotImplementedException ();
11453 - class NoDisposeableFields {
11458 - class DisposeableFieldsImplementsIDisposeable : IDisposable {
11462 - public void Dispose ()
11464 - throw new NotImplementedException ();
11468 - class DisposeableFieldsExplicit : IDisposable {
11472 - void IDisposable.Dispose ()
11474 - throw new NotImplementedException ();
11478 - abstract class DisposeableFieldsImplementsIDisposeableAbstract : IDisposable {
11481 - public void Dispose (object asd) { B.Dispose (); }
11482 - public abstract void Dispose ();
11485 - class DisposeableFields : ICloneable {
11489 - public object Clone ()
11491 - throw new NotImplementedException ();
11495 - class DisposeableFieldsArray : ICloneable {
11499 - public object Clone ()
11501 - throw new NotImplementedException ();
11505 - struct StructWithDisposeableFields {
11510 - class DisposeableStaticFieldsArray {
11512 - static Disposable [] B;
11516 - public class TypesWithDisposableFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithDisposableFieldsShouldBeDisposableRule> {
11519 - public void DoesNotApply ()
11521 - AssertRuleDoesNotApply (SimpleTypes.Delegate);
11522 - AssertRuleDoesNotApply (SimpleTypes.Enum);
11523 - AssertRuleDoesNotApply (SimpleTypes.Interface);
11524 - AssertRuleDoesNotApply (SimpleTypes.Structure);
11528 - public void TestNoDisposeableFields ()
11530 - AssertRuleSuccess<NoDisposeableFields> ();
11534 - public void TestDisposeableFieldsImplementsIDisposeable ()
11536 - AssertRuleSuccess<DisposeableFieldsImplementsIDisposeable> ();
11540 - public void TestDisposeableFieldsExplicit ()
11542 - AssertRuleSuccess<DisposeableFieldsExplicit> ();
11546 - public void TestDisposeableFieldsImplementsIDisposeableAbstract ()
11548 - AssertRuleFailure<DisposeableFieldsImplementsIDisposeableAbstract> (2);
11552 - public void TestDisposeableFields ()
11554 - AssertRuleFailure<DisposeableFields> (1);
11558 - public void TestDisposeableFieldsArray ()
11560 - AssertRuleFailure<DisposeableFieldsArray> (1);
11564 - public void TestStructWithDisposeableFields ()
11566 - AssertRuleDoesNotApply<StructWithDisposeableFields> ();
11570 - public void TestDisposeableStaticFieldsArray ()
11572 - AssertRuleSuccess<DisposeableStaticFieldsArray> ();
11576 diff --git a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs b/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
11577 deleted file mode 100644
11578 index 75216df..0000000
11579 --- a/gendarme/rules/Gendarme.Rules.Design/Test/TypesWithNativeFieldsShouldBeDisposableTest.cs
11583 -// Unit tests for TypesWithNativeFieldsShouldBeDisposableRule
11586 -// Andreas Noever <andreas.noever@gmail.com>
11587 -// Sebastien Pouliot <sebastien@ximian.com>
11589 -// (C) 2008 Andreas Noever
11590 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
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:
11600 -// The above copyright notice and this permission notice shall be
11601 -// included in all copies or substantial portions of the Software.
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.
11613 -using System.Runtime.InteropServices;
11615 -using Gendarme.Rules.Design;
11617 -using NUnit.Framework;
11618 -using Test.Rules.Definitions;
11619 -using Test.Rules.Fixtures;
11621 -namespace Test.Rules.Design {
11623 - class NoNativeFields {
11628 - class NativeFieldsImplementsIDisposeable : IDisposable {
11632 - public void Dispose ()
11634 - throw new NotImplementedException ();
11638 - class NativeFieldsExplicit : IDisposable {
11642 - void IDisposable.Dispose ()
11644 - throw new NotImplementedException ();
11649 - class NativeFieldsIntPtr : ICloneable {
11653 - public object Clone ()
11655 - throw new NotImplementedException ();
11659 - class NativeFieldsUIntPtr : ICloneable {
11663 - public object Clone ()
11665 - throw new NotImplementedException ();
11669 - class NativeFieldsHandleRef : ICloneable {
11671 - System.Runtime.InteropServices.HandleRef B;
11673 - public object Clone ()
11675 - throw new NotImplementedException ();
11679 - abstract class AbstractNativeFields : IDisposable {
11681 - System.Runtime.InteropServices.HandleRef B;
11683 - public abstract void Dispose ();
11686 - abstract class AbstractNativeFields2 : IDisposable {
11688 - System.Runtime.InteropServices.HandleRef B;
11690 - public abstract void Dispose ();
11693 - void IDisposable.Dispose ()
11695 - throw new NotImplementedException ();
11699 - class NativeFieldsArray : ICloneable {
11703 - public object Clone ()
11705 - throw new NotImplementedException ();
11709 - struct StructWithNativeFields {
11715 - class NativeStaticFieldsArray {
11717 - static UIntPtr [] B;
11721 - public class TypesWithNativeFieldsShouldBeDisposableTest : TypeRuleTestFixture<TypesWithNativeFieldsShouldBeDisposableRule> {
11724 - public void DoesNotApply ()
11726 - AssertRuleDoesNotApply (SimpleTypes.Delegate);
11727 - AssertRuleDoesNotApply (SimpleTypes.Enum);
11728 - AssertRuleDoesNotApply (SimpleTypes.Interface);
11729 - AssertRuleDoesNotApply (SimpleTypes.Structure);
11733 - public void TestNoNativeFields ()
11735 - AssertRuleSuccess<NoNativeFields> ();
11739 - public void TestNativeFieldsImplementsIDisposeable ()
11741 - AssertRuleSuccess<NativeFieldsImplementsIDisposeable> ();
11745 - public void TestNativeFieldsExplicit ()
11747 - AssertRuleSuccess<NativeFieldsExplicit> ();
11751 - public void TestNativeFieldsIntPtr ()
11753 - AssertRuleFailure<NativeFieldsIntPtr> (1);
11757 - public void TestNativeFieldsUIntPtr ()
11759 - AssertRuleFailure<NativeFieldsUIntPtr> (1);
11763 - public void TestNativeFieldsHandleRef ()
11765 - AssertRuleFailure<NativeFieldsHandleRef> (1);
11769 - public void TestAbstractNativeFields ()
11771 - AssertRuleFailure<AbstractNativeFields> (2);
11775 - public void TestAbstractNativeFields2 ()
11777 - AssertRuleFailure<AbstractNativeFields2> (2);
11781 - public void TestNativeFieldsArray ()
11783 - AssertRuleFailure<NativeFieldsArray> (1);
11787 - public void TestStructWithNativeFields ()
11789 - AssertRuleDoesNotApply<StructWithNativeFields> ();
11793 - public void TestNativeStaticFieldsArray ()
11795 - AssertRuleSuccess<NativeStaticFieldsArray> ();
11799 diff --git a/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs
11800 deleted file mode 100644
11801 index b1d6f85..0000000
11802 --- a/gendarme/rules/Gendarme.Rules.Design/TypesWithDisposableFieldsShouldBeDisposableRule.cs
11806 -// Gendarme.Rules.Design.TypesWithDisposableFieldsShouldBeDisposableRule
11809 -// Andreas Noever <andreas.noever@gmail.com>
11811 -// (C) 2008 Andreas Noever
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:
11821 -// The above copyright notice and this permission notice shall be
11822 -// included in all copies or substantial portions of the Software.
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.
11834 -using System.Text;
11835 -using System.Collections.Generic;
11836 -using System.Diagnostics;
11840 -using Mono.Cecil.Cil;
11841 -using Gendarme.Framework;
11842 -using Gendarme.Framework.Helpers;
11843 -using Gendarme.Framework.Rocks;
11845 -namespace Gendarme.Rules.Design {
11848 - /// This rule will fire if a type contains disposable fields but does not implement
11849 - /// <c>System.IDisposable</c>.
11852 - /// Bad examples:
11854 - /// class DoesNotImplementIDisposable {
11855 - /// IDisposable field;
11858 - /// class AbstractDispose : IDisposable {
11859 - /// IDisposable field;
11861 - /// // the field should be disposed in the type that declares it
11862 - /// public abstract void Dispose ();
11867 - /// Good example:
11869 - /// class Dispose : IDisposable {
11870 - /// IDisposable field;
11872 - /// public void Dispose ()
11874 - /// field.Dispose ();
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 {
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.";
11889 - static bool IsAbstract (MethodDefinition method)
11891 - return ((method != null) && (method.IsAbstract));
11894 - public RuleResult CheckType (TypeDefinition type)
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;
11900 - MethodDefinition explicitDisposeMethod = null;
11901 - MethodDefinition implicitDisposeMethod = null;
11903 - bool abstractWarning = false;
11905 - if (type.Implements ("System.IDisposable")) {
11906 - implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
11907 - explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
11909 - if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
11910 - abstractWarning = true;
11912 - return RuleResult.Success;
11916 - foreach (FieldDefinition field in type.Fields) {
11917 - // we can't dispose static fields in IDisposable
11918 - if (field.IsStatic)
11920 - TypeDefinition fieldType = field.FieldType.GetElementType ().Resolve ();
11921 - if (fieldType == null)
11923 - // enums and primitives don't implement IDisposable
11924 - if (fieldType.IsEnum || fieldType.IsPrimitive)
11926 - if (fieldType.Implements ("System.IDisposable")) {
11927 - Runner.Report (field, Severity.High, Confidence.High,
11928 - abstractWarning ? AbstractTypeMessage : TypeMessage);
11932 - // Warn about possible confusion if the Dispose methods are abstract
11933 - if (IsAbstract (implicitDisposeMethod))
11934 - Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
11936 - return Runner.CurrentRuleResult;
11941 diff --git a/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs b/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs
11942 deleted file mode 100644
11943 index 113a5dd..0000000
11944 --- a/gendarme/rules/Gendarme.Rules.Design/TypesWithNativeFieldsShouldBeDisposableRule.cs
11948 -// Gendarme.Rules.Design.TypesWithNativeFieldsShouldBeDisposableRule
11951 -// Andreas Noever <andreas.noever@gmail.com>
11953 -// (C) 2008 Andreas Noever
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:
11963 -// The above copyright notice and this permission notice shall be
11964 -// included in all copies or substantial portions of the Software.
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.
11977 -using Gendarme.Framework;
11978 -using Gendarme.Framework.Helpers;
11979 -using Gendarme.Framework.Rocks;
11981 -namespace Gendarme.Rules.Design {
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>.
11988 - /// Bad examples:
11990 - /// public class DoesNotImplementIDisposable {
11991 - /// IntPtr field;
11994 - /// abstract public class AbstractDispose : IDisposable {
11995 - /// IntPtr field;
11997 - /// // the field should be disposed in the type that declares it
11998 - /// public abstract void Dispose ();
12003 - /// Good example:
12005 - /// public class Dispose : IDisposable {
12006 - /// IDisposable field;
12008 - /// public void Dispose ()
12010 - /// UnmanagedFree (field);
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 {
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.";
12025 - static bool IsAbstract (MethodDefinition method)
12027 - return ((method != null) && (method.IsAbstract));
12030 - public RuleResult CheckType (TypeDefinition type)
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;
12036 - MethodDefinition explicitDisposeMethod = null;
12037 - MethodDefinition implicitDisposeMethod = null;
12039 - bool abstractWarning = false;
12041 - if (type.Implements ("System.IDisposable")) {
12042 - implicitDisposeMethod = type.GetMethod (MethodSignatures.Dispose);
12043 - explicitDisposeMethod = type.GetMethod (MethodSignatures.DisposeExplicit);
12045 - if (IsAbstract (implicitDisposeMethod) || IsAbstract (explicitDisposeMethod)) {
12046 - abstractWarning = true;
12048 - return RuleResult.Success;
12052 - foreach (FieldDefinition field in type.Fields) {
12053 - // we can't dispose static fields in IDisposable
12054 - if (field.IsStatic)
12056 - if (field.FieldType.GetElementType ().IsNative ()) {
12057 - Runner.Report (field, Severity.High, Confidence.High,
12058 - abstractWarning ? AbstractTypeMessage : TypeMessage);
12062 - // Warn about possible confusion if the Dispose methods are abstract
12063 - if (IsAbstract (implicitDisposeMethod))
12064 - Runner.Report (implicitDisposeMethod, Severity.Medium, Confidence.High, AbstractDisposeMessage);
12066 - return Runner.CurrentRuleResult;
12070 diff --git a/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs b/gendarme/rules/Gendarme.Rules.Design/UseCorrectDisposeSignaturesRule.cs
12071 index 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;
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);
12085 MethodDefinition dispose0 = null;
12086 MethodDefinition dispose1 = null;
12087 @@ -236,7 +236,7 @@ namespace Gendarme.Rules.Design {
12089 if (type.HasInterfaces) {
12090 foreach (TypeReference candidate in type.Interfaces) {
12091 - if (candidate.FullName == "System.IDisposable")
12092 + if (candidate.IsNamed ("System", "IDisposable"))
12096 diff --git a/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs b/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12097 index 79671d8..c6adf87 100644
12098 --- a/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12099 +++ b/gendarme/rules/Gendarme.Rules.Design/UseFlagsAttributeRule.cs
12102 using System.Collections.Generic;
12103 using System.Diagnostics;
12104 +using System.Globalization;
12108 @@ -94,7 +95,7 @@ namespace Gendarme.Rules.Design {
12109 values.Add (value);
12112 - long v = Convert.ToInt64 (o);
12113 + long v = Convert.ToInt64 (o, CultureInfo.InvariantCulture);
12117 @@ -159,7 +160,7 @@ namespace Gendarme.Rules.Design {
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 ()));
12126 diff --git a/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs b/gendarme/rules/Gendarme.Rules.Design/UsingCloneWithoutImplementingICloneableRule.cs
12127 index 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)
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;
12138 foreach (MethodDefinition method in type.Methods) {
12139 @@ -110,7 +110,7 @@ namespace Gendarme.Rules.Design {
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);
12148 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidArgumentExceptionDefaultConstructorRule.cs
12149 index 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 {
12155 TypeReference type = ctor.DeclaringType;
12156 - string name = type.FullName;
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);
12166 - if (!name.EndsWith ("Exception", StringComparison.Ordinal))
12168 - if (type.Inherits ("System.ArgumentException"))
12169 - Runner.Report (method, ins, Severity.Medium, Confidence.Total, name);
12171 + string name = type.Name;
12172 + if (type.Namespace == "System") {
12173 + // most common cases
12175 + case "ArgumentException":
12176 + case "ArgumentNullException":
12177 + case "ArgumentOutOfRangeException":
12178 + case "DuplicateWaitObjectException":
12179 + Runner.Report (method, ins, Severity.Medium, Confidence.Total, type.GetFullName ());
12184 + if (name.EndsWith ("Exception", StringComparison.Ordinal)) {
12185 + if (type.Inherits ("System", "ArgumentException"))
12186 + Runner.Report (method, ins, Severity.Medium, Confidence.Total, type.GetFullName ());
12189 return Runner.CurrentRuleResult;
12190 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12191 index a43d01c..0ac510d 100644
12192 --- a/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12193 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/AvoidThrowingBasicExceptionsRule.cs
12195 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12199 using Gendarme.Framework;
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 {
12206 - static string [] BasicExceptions = {
12207 - "System.Exception",
12208 - "System.ApplicationException",
12209 - "System.SystemException"
12212 - protected override string [] GetExceptionTypes ()
12213 + protected override bool CheckException (TypeReference type)
12215 - return BasicExceptions;
12216 + if ((type == null) || (type.Namespace != "System"))
12218 + string name = type.Name;
12219 + return ((name == "Exception") || (name == "ApplicationException") || (name == "SystemException"));
12222 protected override Severity Severity {
12223 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12224 index b1587d7..661b53f 100644
12225 --- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12226 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotDestroyStackTraceRule.cs
12229 // DoNotDestroyStackTraceRule
12231 -// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
12232 +// Copyright (C) 2008, 2011 Novell, Inc (http://www.novell.com)
12234 // Permission is hereby granted, free of charge, to any person obtaining
12235 // a copy of this software and associated documentation files (the
12237 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12241 using System.Collections.Generic;
12244 @@ -31,6 +30,7 @@ using Mono.Cecil.Cil;
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;
12252 @@ -74,39 +74,116 @@ namespace Gendarme.Rules.Exceptions {
12253 [FxCopCompatibility ("Microsoft.Usage", "CA2200:RethrowToPreserveStackDetails")]
12254 public class DoNotDestroyStackTraceRule : Rule, IMethodRule {
12256 + // all branches instructions except leave[_s]
12257 + static OpCodeBitmask branches = new OpCodeBitmask (0xFFFFFC0000000000, 0xF, 0x0, 0x0);
12259 private List<int> warned_offsets_in_method = new List<int> ();
12261 public RuleResult CheckMethod (MethodDefinition method)
12263 // rule only applies to methods with IL and exceptions handlers
12264 - if (!method.HasBody)
12265 - return RuleResult.DoesNotApply;
12267 - MethodBody body = method.Body;
12268 - if (!body.HasExceptionHandlers)
12269 + if (!method.HasBody || !method.Body.HasExceptionHandlers)
12270 return RuleResult.DoesNotApply;
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;
12278 + // we can use a faster code path when no branches are present in the method
12279 + if (mask.Intersect (branches)) {
12280 + Branches (method);
12282 + Branchless (method);
12285 warned_offsets_in_method.Clear ();
12287 + return Runner.CurrentRuleResult;
12290 + private void Branchless (MethodDefinition method)
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;
12297 + foreach (ExceptionHandler eh in method.Body.ExceptionHandlers) {
12298 + if (eh.HandlerType != ExceptionHandlerType.Catch)
12301 + ProcessCatchBlock (eh.HandlerStart, eh.HandlerEnd, method, ref exStackPos, ref localVarPos);
12305 + private void ProcessCatchBlock (Instruction first, Instruction last, MethodDefinition method, ref int exStackPos, ref int localVarPos)
12307 + Instruction cur = null;
12309 + while (cur != last) {
12315 + // Rethrown exception - no problem!
12316 + if (cur.Is (Code.Rethrow))
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;
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
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);
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
12349 + int numPushes = cur.GetPushCount ();
12350 + exStackPos += numPushes - numPops;
12356 + private void Branches (MethodDefinition method)
12358 ExecutionPathFactory epf = new ExecutionPathFactory ();
12360 - foreach (ExceptionHandler eh in body.ExceptionHandlers) {
12361 + foreach (ExceptionHandler eh in method.Body.ExceptionHandlers) {
12362 if (eh.HandlerType != ExceptionHandlerType.Catch)
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");
12370 foreach (ExecutionPathCollection catchPath in list)
12371 ProcessCatchPath (catchPath, method);
12375 - return Runner.CurrentRuleResult;
12378 private void ProcessCatchPath (IEnumerable<ExecutionBlock> catchPath, MethodDefinition method)
12379 @@ -120,54 +197,41 @@ namespace Gendarme.Rules.Exceptions {
12380 int localVarPos = -1;
12382 foreach (ExecutionBlock block in catchPath) {
12383 - Instruction cur = null;
12385 - while (cur != block.Last) {
12387 - cur = block.First;
12391 - if (cur.OpCode == OpCodes.Rethrow)
12392 - // Rethrown exception - no problem!
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;
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
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);
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
12425 - int numPushes = cur.GetPushCount ();
12426 - exStackPos += numPushes - numPops;
12430 + ProcessCatchBlock (block.First, block.Last, method, ref exStackPos, ref localVarPos);
12434 + public void Bitmask ()
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);
12468 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs
12469 new file mode 100644
12470 index 0000000..f237349
12472 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInNonCatchClausesRule.cs
12475 +// Gendarme.Rules.Exceptions.DoNotThrowInNonCatchClausesRule
12478 +// Sebastien Pouliot <sebastien@ximian.com>
12480 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
12490 +// The above copyright notice and this permission notice shall be
12491 +// included in all copies or substantial portions of the Software.
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.
12503 +using Mono.Cecil.Cil;
12505 +using Gendarme.Framework;
12506 +using Gendarme.Framework.Engines;
12507 +using Gendarme.Framework.Rocks;
12509 +namespace Gendarme.Rules.Exceptions {
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.
12521 + /// err = Initialize ();
12525 + /// if (err != 0)
12526 + /// throw new NotSupportedException ();
12531 + /// Good example:
12534 + /// if (Initialize () != 0)
12535 + /// throw new NotSupportedException ();
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 {
12548 + void CheckBlock (MethodDefinition method, Instruction start, Instruction end)
12550 + Instruction ins = start;
12551 + while (ins != end) {
12552 + if (ins.Is (Code.Throw))
12553 + Runner.Report (method, ins, Severity.High, Confidence.High);
12558 + public RuleResult CheckMethod (MethodDefinition method)
12560 + // rule only applies to methods with IL...
12561 + if (!method.HasBody)
12562 + return RuleResult.DoesNotApply;
12564 + // ... and exceptions handlers
12565 + MethodBody body = method.Body;
12566 + if (!body.HasExceptionHandlers)
12567 + return RuleResult.DoesNotApply;
12569 + // and when the IL contains a Throw instruction (Rethrow is fine)
12570 + if (!OpCodeEngine.GetBitmask (method).Get (Code.Throw))
12571 + return RuleResult.DoesNotApply;
12573 + foreach (ExceptionHandler eh in body.ExceptionHandlers) {
12574 + // throwing in catch handler is fine
12575 + if (eh.HandlerType == ExceptionHandlerType.Catch)
12578 + CheckBlock (method, eh.HandlerStart, eh.HandlerEnd);
12579 + if (eh.FilterStart != null)
12580 + CheckBlock (method, eh.FilterStart, eh.HandlerStart);
12583 + return Runner.CurrentRuleResult;
12587 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12588 index 88e4379..cd7ad5b 100644
12589 --- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12590 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowInUnexpectedLocationRule.cs
12592 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12595 +using System.Globalization;
12596 +using System.Text;
12599 using Mono.Cecil.Cil;
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);
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"}
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" }
12621 + private static readonly string [][] EventExceptions = new string [][] {
12622 + new string [] { "System", "InvalidOperationException" },
12623 + new string [] { "System", "NotSupportedException" },
12624 + new string [] { "System", "ArgumentException" }
12627 + private static readonly string [][] HashCodeExceptions = new string [][] {
12628 + new string [] { "System", "ArgumentException" }
12631 private static bool CheckAttributes (MethodReference method, MethodAttributes attrs)
12633 @@ -180,7 +200,7 @@ namespace Gendarme.Rules.Exceptions {
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;
12642 @@ -189,7 +209,7 @@ namespace Gendarme.Rules.Exceptions {
12643 base.Initialize (runner);
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;
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)) {
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 {
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);
12677 case Code.Throw: // this one is obvious
12678 return string.Empty;
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);
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"))
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]))
12713 + foreach (string [] entry in allowedExceptions) {
12714 + if (type.Inherits (entry [0], entry [1])) {
12721 + Report (method, ins, methodLabel);
12725 @@ -388,10 +419,21 @@ namespace Gendarme.Rules.Exceptions {
12726 private void Report (MethodDefinition method, Instruction ins, string methodLabel)
12729 - if (allowedExceptions == null)
12730 - mesg = string.Format ("{0} should not throw{1}.", methodLabel, ExplainThrow (ins));
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));
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 (", ");
12745 + sb.Append (" or a subclass").Append (ExplainThrow (ins)).Append ('.');
12746 + mesg = sb.ToString ();
12749 Log.WriteLine (this, "{0:X4}: {1}", ins.Offset, mesg);
12750 Runner.Report (method, ins, severity, Confidence.High, mesg);
12751 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12752 index c69fc7c..a7d989b 100644
12753 --- a/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12754 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/DoNotThrowReservedExceptionRule.cs
12756 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12760 using Gendarme.Framework;
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 {
12767 - static string [] ReservedExceptions = {
12768 - "System.ExecutionEngineException",
12769 - "System.IndexOutOfRangeException",
12770 - "System.NullReferenceException",
12771 - "System.OutOfMemoryException"
12774 - protected override string [] GetExceptionTypes ()
12775 + protected override bool CheckException (TypeReference type)
12777 - return ReservedExceptions;
12778 + if (type == null)
12781 + switch (type.Name) {
12782 + case "ExecutionEngineException":
12783 + case "IndexOutOfRangeException":
12784 + case "NullReferenceException":
12785 + case "OutOfMemoryException":
12786 + return (type.Namespace == "System");
12792 protected override Severity Severity {
12793 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/DontSwallowErrorsCatchingNonspecificExceptionsRule.cs
12794 index 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 {
12801 - private static bool IsForbiddenTypeInCatches (string typeName)
12802 + private static bool IsForbiddenTypeInCatches (TypeReference type)
12804 - switch (typeName) {
12805 - case "System.Exception":
12806 - case "System.SystemException":
12807 - case "System.Object":
12810 + if (type.Namespace != "System")
12814 + string name = type.Name;
12815 + return ((name == "Exception") || (name == "SystemException") || (name == "Object"));
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) :
12829 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/ExceptionShouldBeVisibleRule.cs
12830 index 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 {
12835 public RuleResult CheckType (TypeDefinition type)
12837 - if (type.BaseType == null)
12838 + TypeReference btype = type.BaseType;
12839 + if (btype == null)
12840 return RuleResult.DoesNotApply;
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":
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;
12856 if (type.IsAbstract || type.IsVisible ())
12857 return RuleResult.Success;
12858 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj b/gendarme/rules/Gendarme.Rules.Exceptions/Gendarme.Rules.Exceptions.csproj
12859 index 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
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
12867 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
12868 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
12892 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
12893 <DebugSymbols>true</DebugSymbols>
\r
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
12900 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
12901 <DebugType>pdbonly</DebugType>
\r
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
12909 <Reference Include="System" />
\r
12910 @@ -96,14 +99,33 @@
12911 <None Include="ChangeLog" />
\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
12923 + <Install>false</Install>
\r
12924 </BootstrapperPackage>
\r
12925 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
12926 <Visible>False</Visible>
\r
12929 + <Install>false</Install>
\r
12930 </BootstrapperPackage>
\r
12931 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
12932 <Visible>False</Visible>
\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
12943 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
12944 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/InstantiateArgumentExceptionCorrectlyRule.cs
12945 index 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 {
12951 // OK public ArgumentException (string message, Exception innerException)
12952 - if (pdc [1].ParameterType.FullName != "System.String")
12953 + if (!pdc [1].ParameterType.IsNamed ("System", "String"))
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"))
12965 // CHECK public ArgumentNullException (string paramName)
12966 // CHECK public ArgumentNullException (string paramName, string message)
12967 Instruction call = ins.TraceBack (method, 0);
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)
12973 string name = call.Operand as string;
12974 if (MatchesAnyParameter (method, name))
12976 @@ -187,18 +192,19 @@ namespace Gendarme.Rules.Exceptions {
12979 MethodReference ctor = (current.Operand as MethodReference);
12980 + TypeReference type = ctor.DeclaringType;
12981 + if (type.Namespace != "System")
12984 - switch (ctor.DeclaringType.FullName) {
12985 - case "System.ArgumentException":
12986 + switch (type.Name) {
12987 + case "ArgumentException":
12988 CheckArgumentException (ctor, current, method);
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);
13003 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am b/gendarme/rules/Gendarme.Rules.Exceptions/Makefile.am
13004 index 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 = \
13017 AvoidArgumentExceptionDefaultConstructorTest.cs \
13018 AvoidThrowingBasicExceptionsTest.cs \
13019 + DoNotThrowInNonCatchClausesTest.cs \
13020 DoNotThrowInUnexpectedLocationTest.cs \
13021 DontDestroyStackTraceTest.cs \
13022 DontSwallowErrorsCatchingNonspecificExceptionsTest.cs \
13023 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13024 index 32663e5..d4d86af 100644
13025 --- a/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13026 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/MissingExceptionConstructorsRule.cs
13030 using System.Collections.Generic;
13031 +using System.Globalization;
13035 @@ -86,9 +87,6 @@ namespace Gendarme.Rules.Exceptions {
13036 [FxCopCompatibility ("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
13037 public class MissingExceptionConstructorsRule : Rule, ITypeRule {
13039 - // non-localizable
13040 - private const string Exception = "System.Exception";
13043 private const string MissingConstructor = "Exception is missing '{0} {1}{2}' constructor.";
13045 @@ -97,15 +95,15 @@ namespace Gendarme.Rules.Exceptions {
13046 if (!ctor.IsPublic)
13049 - return (ctor.Parameters [0].ParameterType.FullName == "System.String");
13050 + return (ctor.Parameters [0].ParameterType.IsNamed ("System", "String"));
13053 private static bool CheckForInnerExceptionConstructor (IMethodSignature ctor)
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"))
13061 + return pdc [pdc.Count - 1].ParameterType.IsNamed ("System", "Exception");
13064 private static bool CheckForSerializationConstructor (MethodDefinition ctor)
13065 @@ -119,7 +117,7 @@ namespace Gendarme.Rules.Exceptions {
13066 public RuleResult CheckType (TypeDefinition type)
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;
13073 // rule applies, only Success or Failure from the point on
13074 @@ -166,21 +164,24 @@ namespace Gendarme.Rules.Exceptions {
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);
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);
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);
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);
13105 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/NewExceptionRule.cs
13106 index 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);
13122 - abstract protected string [] GetExceptionTypes ();
13123 + abstract protected bool CheckException (TypeReference type);
13124 abstract protected Severity Severity { get; }
13126 public RuleResult CheckMethod (MethodDefinition method)
13127 @@ -69,18 +71,12 @@ namespace Gendarme.Rules.Exceptions {
13128 if (ins.OpCode.Code != Code.Newobj)
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;
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);
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);
13150 return Runner.CurrentRuleResult;
13151 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/README.md b/gendarme/rules/Gendarme.Rules.Exceptions/README.md
13152 new file mode 100644
13153 index 0000000..110e852
13155 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/README.md
13157 +# Gendarme.Rules.Exceptions Rules
13159 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Exceptions(git)]] pages.
13164 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
13166 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs b/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs
13167 new file mode 100644
13168 index 0000000..9bb6ddd
13170 +++ b/gendarme/rules/Gendarme.Rules.Exceptions/Test/DoNotThrowInNonCatchClausesTest.cs
13173 +// Unit Tests for DoNotThrowInNonCatchClausesRule
13176 +// Sebastien Pouliot <sebastien@ximian.com>
13178 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
13188 +// The above copyright notice and this permission notice shall be
13189 +// included in all copies or substantial portions of the Software.
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.
13201 +using Gendarme.Rules.Exceptions;
13203 +using NUnit.Framework;
13204 +using Test.Rules.Definitions;
13205 +using Test.Rules.Fixtures;
13207 +namespace Test.Rules.Exceptions {
13210 + public class DoNotThrowInNonCatchClausesTest : MethodRuleTestFixture<DoNotThrowInNonCatchClausesRule> {
13213 + public void DoesNotApply ()
13215 + AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
13216 + AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
13219 + void ThrowInTry ()
13222 + throw new NotImplementedException ("no luck");
13225 + Console.WriteLine ();
13229 + void ThrowInCatch ()
13232 + Console.WriteLine ();
13234 + catch (Exception e) {
13235 + throw new NotImplementedException ("no luck", e);
13239 + // copied from DontDestroyStackTraceTest since CSC compiles the HandlerEnd as past the method offset
13240 + void ThrowCatchThrowNew ()
13243 + throw new NotImplementedException ();
13245 + catch (Exception) {
13246 + throw new NotImplementedException ();
13251 + public void Success ()
13253 + AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowInTry");
13254 + AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowInCatch");
13255 + AssertRuleSuccess<DoNotThrowInNonCatchClausesTest> ("ThrowCatchThrowNew");
13258 + void RethrowInCatch ()
13261 + Console.WriteLine ();
13263 + catch (Exception) {
13264 + throw; // rethrow in IL which is seen only in catch clauses
13269 + public void Rethrow ()
13271 + AssertRuleDoesNotApply<DoNotThrowInNonCatchClausesTest> ("RethrowInCatch");
13274 + void ThrowInFinally ()
13277 + Console.WriteLine ();
13280 + throw new NotImplementedException ("no luck");
13284 + void ThrowInFinallyToo ()
13287 + throw new NotImplementedException ("no luck");
13289 + catch (Exception e) {
13290 + throw new NotImplementedException ("no more luck", e);
13293 + if (GetType ().IsSealed)
13294 + throw new NotImplementedException ("never any luck");
13296 + throw new NotSupportedException ("stop playing cards");
13301 + public void Failure ()
13303 + AssertRuleFailure<DoNotThrowInNonCatchClausesTest> ("ThrowInFinally", 1);
13304 + AssertRuleFailure<DoNotThrowInNonCatchClausesTest> ("ThrowInFinallyToo", 2);
13308 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs b/gendarme/rules/Gendarme.Rules.Exceptions/Test/InstantiateArgumentExceptionCorrectlyTest.cs
13309 index 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");
13317 + public void ArgumentNullExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13319 + throw new ArgumentNullException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13322 + public void ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13324 + throw new ArgumentOutOfRangeException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13327 + public void DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndIncorrectParameterName(int parameter)
13329 + throw new DuplicateWaitObjectException("asdf", parameter > 0 ? "little parameter " : "big parameter");
13332 + public void ArgumentNullExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13334 + throw new ArgumentNullException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13337 + public void ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13339 + throw new ArgumentOutOfRangeException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13342 + public void DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndCorrectParameterName(int parameter)
13344 + throw new DuplicateWaitObjectException("parameter", parameter > 0 ? "little parameter " : "big parameter");
13348 + public void ArgumentExceptionsWithBranchInMessageSelectionDoesNotThrow()
13350 + AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentNullExceptionWithBranchInMessageSelectionAndCorrectParameterName");
13351 + AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("ArgumentOutOfRangeExceptionWithBranchInMessageSelectionAndCorrectParameterName");
13352 + AssertRuleSuccess<InstantiateArgumentExceptionCorrectlyTest>("DuplicateWaitObjectExceptionWithBranchInMessageSelectionAndCorrectParameterName");
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");
13362 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj b/gendarme/rules/Gendarme.Rules.Exceptions/Test/Tests.Rules.Exceptions.csproj
13363 index 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
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
13371 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
13372 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
13396 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
13397 <DebugSymbols>true</DebugSymbols>
\r
13399 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
13400 <ErrorReport>prompt</ErrorReport>
\r
13401 <WarningLevel>4</WarningLevel>
\r
13402 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
13404 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
13405 <DebugType>pdbonly</DebugType>
\r
13407 <DefineConstants>TRACE</DefineConstants>
\r
13408 <ErrorReport>prompt</ErrorReport>
\r
13409 <WarningLevel>4</WarningLevel>
\r
13410 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\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
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
13427 + <Install>false</Install>
\r
13428 </BootstrapperPackage>
\r
13429 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
13430 <Visible>False</Visible>
\r
13433 + <Install>false</Install>
\r
13434 </BootstrapperPackage>
\r
13435 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
13436 <Visible>False</Visible>
\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
13447 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
13448 diff --git a/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Exceptions/UseObjectDisposedExceptionRule.cs
13449 index 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 {
13454 private void CheckBody (MethodDefinition method)
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) {
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 {
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 {
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;
13490 @@ -220,7 +222,7 @@ namespace Gendarme.Rules.Exceptions {
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)) {
13499 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/DefectsMustBeReportedRule.cs
13500 index 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)
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;
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)))
13516 foreach (Instruction instruction in method.Body.Instructions) {
13517 @@ -87,9 +87,9 @@ namespace Gendarme.Rules.Gendarme {
13520 MethodReference m = (instruction.Operand as MethodReference);
13521 - if (m == null || m.DeclaringType.FullName != "Gendarme.Framework.IRunner")
13522 + if (m == null || (m.Name != "Report"))
13524 - if (m.Name == "Report")
13525 + if (m.DeclaringType.IsNamed ("Gendarme.Framework", "IRunner"))
13526 return RuleResult.Success;
13529 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/DoNotThrowExceptionRule.cs
13530 index 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 {
13535 Runner.AnalyzeType += (object sender, RunnerEventArgs e) =>
13537 - Active = e.CurrentType.Implements ("Gendarme.Framework.IRule");
13538 + Active = e.CurrentType.Implements ("Gendarme.Framework", "IRule");
13542 @@ -89,7 +89,7 @@ namespace Gendarme.Rules.Gendarme {
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;
13551 @@ -105,7 +105,7 @@ namespace Gendarme.Rules.Gendarme {
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);
13560 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj b/gendarme/rules/Gendarme.Rules.Gendarme/Gendarme.Rules.Gendarme.csproj
13561 index 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
13565 -<?xml version="1.0" encoding="utf-8"?>
13566 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
13600 - <Reference Include="System" />
13601 - <Reference Include="System.Core">
13602 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
13606 - <Compile Include="..\..\AssemblyStaticInfo.cs">
13607 - <Link>AssemblyStaticInfo.cs</Link>
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" />
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>
13627 - <Folder Include="Properties\" />
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
13687 + <Reference Include="System" />
\r
13688 + <Reference Include="System.Core">
\r
13689 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
13693 + <Compile Include="..\..\AssemblyStaticInfo.cs">
\r
13694 + <Link>AssemblyStaticInfo.cs</Link>
\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
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
13714 + <Folder Include="Properties\" />
\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
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">
13738 <Target Name="AfterBuild">
13743 \ No newline at end of file
13744 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/MissingEngineDependencyRule.cs
13745 index 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"
13752 + private HashSet<string> declaredEngines = new HashSet<string> ();
13754 public RuleResult CheckType (TypeDefinition type)
13756 if (!type.HasMethods)
13757 return RuleResult.DoesNotApply;
13759 - HashSet<string> declaredEngines = GetEngineDependencyValue (type);
13760 + GetEngineDependencyValue (type);
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);
13768 - string declaringType = m.DeclaringType.FullName;
13769 - if (!engines.Contains (declaringType) || declaredEngines.Contains(declaringType))
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")
13776 + string declaringType = dtype.GetFullName ();
13777 + if (!engines.Contains (declaringType) || declaredEngines.Contains (declaringType))
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;
13785 - private HashSet<string> GetEngineDependencyValue (TypeDefinition type)
13786 + private void GetEngineDependencyValue (TypeDefinition type)
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"))
13799 - // ToString for both constuctors (Type and String) will return the type name we need
13800 - retval.Add (attribute.ConstructorArguments [0].Value.ToString ());
13802 + object value = attribute.ConstructorArguments [0].Value;
13803 + MemberReference mr = (value as MemberReference);
13804 + declaredEngines.Add (mr == null ? value.ToString () : mr.GetFullName ());
13806 if (td.BaseType == null)
13808 - TypeDefinition baseType = td.BaseType.Resolve();
13809 + TypeDefinition baseType = td.BaseType.Resolve ();
13810 if (baseType == null)
13818 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/README.md b/gendarme/rules/Gendarme.Rules.Gendarme/README.md
13819 new file mode 100644
13820 index 0000000..fe4ec4e
13822 +++ b/gendarme/rules/Gendarme.Rules.Gendarme/README.md
13824 +# Gendarme.Rules.Gendarme Rules
13826 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Gendarme(git)]] pages.
13831 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
13833 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/ReviewAttributesOnRulesRule.cs
13834 index 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")
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;
13855 @@ -149,19 +153,19 @@ namespace Gendarme.Rules.Gendarme {
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);
13868 private bool IsRule (TypeReference type)
13870 - var typeName = type.FullName;
13871 + var typeName = type.GetFullName ();
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;
13879 @@ -182,7 +186,7 @@ namespace Gendarme.Rules.Gendarme {
13880 // check if second argument has correct format
13881 if (!attribute.HasConstructorArguments)
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)
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");
13896 CheckIfStringArgumentsAreNotNullOrEmpty (attribute, provider);
13897 @@ -209,9 +213,9 @@ namespace Gendarme.Rules.Gendarme {
13898 var argument = attribute.ConstructorArguments [0];
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");
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");
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");
13926 // returns true when all arguments are fine, false otherwise
13927 @@ -247,11 +251,11 @@ namespace Gendarme.Rules.Gendarme {
13928 if (!attribute.HasConstructorArguments)
13930 foreach (CustomAttributeArgument argument in attribute.ConstructorArguments) {
13931 - if (argument.Type.FullName != "System.String")
13932 + if (!argument.Type.IsNamed ("System", "String"))
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");
13941 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj b/gendarme/rules/Gendarme.Rules.Gendarme/Test/Tests.Rules.Gendarme.csproj
13942 index 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
13946 -<?xml version="1.0" encoding="utf-8"?>
13947 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
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>
13983 - <Reference Include="System" />
13984 - <Reference Include="System.Core">
13985 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
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" />
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>
14014 - <Folder Include="Properties\" />
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
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
14076 + <Reference Include="System" />
\r
14077 + <Reference Include="System.Core">
\r
14078 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\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
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
14107 + <Folder Include="Properties\" />
\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
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">
14131 <Target Name="AfterBuild">
14136 \ No newline at end of file
14137 diff --git a/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs b/gendarme/rules/Gendarme.Rules.Gendarme/UseCorrectSuffixRule.cs
14138 index 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)
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");
14148 if (implementsIRule && !endsWithRule)
14149 Runner.Report (type, Severity.Medium, Confidence.High, "Type implements IRule but does not end with the 'Rule'");
14150 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/AvoidUnusedInternalResourceRule.cs
14151 index 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 {
14158 - private static readonly string [] resXAttributes = {
14159 - "System.CodeDom.Compiler.GeneratedCodeAttribute",
14160 - "System.Diagnostics.DebuggerNonUserCodeAttribute",
14161 - "System.Runtime.CompilerServices.CompilerGeneratedAttribute"
14164 static private bool Applicable (MethodDefinition method)
14166 // only internal resources
14167 @@ -71,11 +65,14 @@ namespace Gendarme.Rules.Globalization {
14168 if (!typeDefinition.HasCustomAttributes)
14171 - var attributes = typeDefinition.CustomAttributes;
14172 - if (!resXAttributes.All (a => attributes.ContainsType (a)))
14174 + if (typeDefinition.HasAttribute ("System.CodeDom.Compiler", "GeneratedCodeAttribute"))
14176 + if (typeDefinition.HasAttribute ("System.Diagnostics", "DebuggerNonUserCodeAttribute"))
14178 + if (typeDefinition.HasAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"))
14185 public RuleResult CheckMethod (MethodDefinition method)
14186 @@ -167,7 +164,7 @@ namespace Gendarme.Rules.Globalization {
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 ();
14195 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj b/gendarme/rules/Gendarme.Rules.Globalization/Gendarme.Rules.Globalization.csproj
14196 index 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
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
14204 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
14205 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
14234 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
14235 <DebugSymbols>true</DebugSymbols>
\r
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
14242 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
14243 <DebugType>pdbonly</DebugType>
\r
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
14251 <Reference Include="System" />
\r
14254 <Folder Include="Properties\" />
\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
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
14276 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am b/gendarme/rules/Gendarme.Rules.Globalization/Makefile.am
14277 index 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
14283 AvoidUnusedInternalResourceRule.cs \
14284 + PreferIFormatProviderOverrideRule.cs \
14285 + PreferOverrideBaseRule.cs \
14286 + PreferStringComparisonOverrideRule.cs \
14287 SatelliteResourceMismatchRule.cs
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/
14293 AvoidUnusedInternalResourceTest.cs \
14294 + PreferIFormatProviderOverrideTest.cs \
14295 + PreferStringComparisonOverrideTest.cs \
14296 SatelliteResourceMismatchTest.cs \
14297 Resource.Designer.cs \
14298 InternalResource.Designer.cs \
14299 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs
14300 new file mode 100644
14301 index 0000000..6a63c4f
14303 +++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferIFormatProviderOverrideRule.cs
14306 +// Gendarme.Rules.Globalization.PreferIFormatProviderOverrideRule
14309 +// Sebastien Pouliot <sebastien@ximian.com>
14311 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
14321 +// The above copyright notice and this permission notice shall be
14322 +// included in all copies or substantial portions of the Software.
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.
14334 +using System.Globalization;
14337 +using Mono.Cecil.Cil;
14338 +using Gendarme.Framework;
14339 +using Gendarme.Framework.Rocks;
14341 +namespace Gendarme.Rules.Globalization {
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:
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>
14360 + /// public bool Confirm (double amount)
14362 + /// string msg = String.Format ("Accept payment of {0} ?", amount);
14363 + /// Transaction.Log ("{0} {1}", DateTime.Now, amount);
14364 + /// return Prompt (msg);
14369 + /// Good example:
14371 + /// public bool Confirm (double amount)
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);
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 {
14385 + protected override bool CheckFirstParameter
14387 + get { return true; }
14390 + protected override bool IsPrefered (TypeReference type)
14392 + return (type.IsNamed ("System", "IFormatProvider") || type.IsNamed ("System.Globalization", "CultureInfo"));
14395 + protected override bool IsSpecialCase (MethodReference method)
14397 + if ((method == null) || method.IsNamed ("System", "Activator", "CreateInstance"))
14400 + TypeReference type = method.DeclaringType;
14401 + if (!type.IsNamed ("System.Resources", "ResourceManager"))
14404 + string name = method.Name;
14405 + return (name == "GetObject" || name == "GetString");
14408 + protected override void Report (MethodDefinition method, Instruction instruction, MethodReference prefered)
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);
14416 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs
14417 new file mode 100644
14418 index 0000000..020e0e4
14420 +++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferOverrideBaseRule.cs
14423 +// Gendarme.Rules.Globalization.PreferOverrideBaseRule
14426 +// Sebastien Pouliot <sebastien@ximian.com>
14428 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
14438 +// The above copyright notice and this permission notice shall be
14439 +// included in all copies or substantial portions of the Software.
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.
14451 +using System.Collections.Generic;
14454 +using Mono.Cecil.Cil;
14455 +using Mono.Collections.Generic;
14457 +using Gendarme.Framework;
14458 +using Gendarme.Framework.Engines;
14459 +using Gendarme.Framework.Helpers;
14460 +using Gendarme.Framework.Rocks;
14462 +namespace Gendarme.Rules.Globalization {
14464 + [EngineDependency (typeof (OpCodeEngine))]
14465 + public abstract class PreferOverrideBaseRule : Rule, IMethodRule {
14467 + protected virtual bool CheckFirstParameter {
14468 + get { return false; }
14471 + protected abstract bool IsPrefered (TypeReference type);
14473 + protected virtual bool IsSpecialCase (MethodReference method)
14475 + return (method == null);
14478 + protected abstract void Report (MethodDefinition method, Instruction instruction, MethodReference prefered);
14480 + static bool MatchParameters (Collection<ParameterDefinition> pmethod, Collection<ParameterDefinition> candidate, int offset)
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 ())
14488 + TypeReference ptype = pd.ParameterType;
14489 + if (!pmethod [i].ParameterType.IsNamed (ptype.Namespace, ptype.Name))
14492 + return (ccount - count <= 1);
14495 + // look for a signature identical to ours but that accept an extra parameter
14496 + MethodReference LookForPreferredOverride (MethodReference method)
14498 + TypeDefinition type = method.DeclaringType.Resolve ();
14499 + if (type == null)
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)
14508 + string name = method.Name;
14510 + Collection<ParameterDefinition> mparams = null;
14511 + if (method.HasParameters) {
14512 + mparams = method.Parameters;
14513 + pcount = mparams.Count;
14516 + foreach (MethodDefinition md in methods) {
14517 + // has one more parameter, so non-zero
14518 + if (!md.HasParameters)
14521 + Collection<ParameterDefinition> pdc = md.Parameters;
14522 + if (name != md.Name)
14525 + // compare parameters and return value
14526 + TypeReference rtype = md.ReturnType;
14527 + if (!method.ReturnType.IsNamed (rtype.Namespace, rtype.Name))
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))
14535 + if (MatchParameters (mparams, pdc, 0))
14537 + } else if (CheckFirstParameter && IsPrefered (pdc [0].ParameterType)) {
14538 + if (MatchParameters (mparams, pdc, 1))
14545 + Dictionary<MethodReference, MethodReference> prefered_overloads = new Dictionary<MethodReference, MethodReference> ();
14547 + MethodReference GetPreferedOverride (MethodReference method)
14549 + MethodReference prefered = null;
14550 + if (!prefered_overloads.TryGetValue (method, out prefered)) {
14551 + prefered = LookForPreferredOverride (method);
14552 + prefered_overloads.Add (method, prefered);
14557 + public RuleResult CheckMethod (MethodDefinition method)
14559 + if (!method.HasBody)
14560 + return RuleResult.DoesNotApply;
14562 + // exclude methods that don't have calls
14563 + if (!OpCodeBitmask.Calls.Intersect (OpCodeEngine.GetBitmask (method)))
14564 + return RuleResult.DoesNotApply;
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))
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))
14577 + if (IsPrefered (pdc [pdc.Count - 1].ParameterType))
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);
14587 + return Runner.CurrentRuleResult;
14592 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs
14593 new file mode 100644
14594 index 0000000..3ed3dfa
14596 +++ b/gendarme/rules/Gendarme.Rules.Globalization/PreferStringComparisonOverrideRule.cs
14599 +// Gendarme.Rules.Globalization.PreferStringComparisonOverrideRule
14602 +// Sebastien Pouliot <sebastien@ximian.com>
14604 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
14614 +// The above copyright notice and this permission notice shall be
14615 +// included in all copies or substantial portions of the Software.
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.
14627 +using System.Globalization;
14630 +using Mono.Cecil.Cil;
14631 +using Gendarme.Framework;
14632 +using Gendarme.Framework.Rocks;
14634 +namespace Gendarme.Rules.Globalization {
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.
14646 + /// public bool Check (string name)
14648 + /// // it's not clear if the string comparison should be culture sensitive or not
14649 + /// return (String.Compare (name, "Software") == 0);
14654 + /// Good example:
14656 + /// public bool Check (string name)
14658 + /// return (String.Compare (name, "Software", StringComparison.CurrentCulture) == 0);
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 {
14667 + protected override bool IsPrefered (TypeReference type)
14669 + return type.IsNamed ("System", "StringComparison");
14672 + protected override void Report (MethodDefinition method, Instruction instruction, MethodReference prefered)
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);
14680 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/README.md b/gendarme/rules/Gendarme.Rules.Globalization/README.md
14681 new file mode 100644
14682 index 0000000..9c08b48
14684 +++ b/gendarme/rules/Gendarme.Rules.Globalization/README.md
14686 +# Gendarme.Rules.Globalization Rules
14688 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Globalization(git)]] pages.
14693 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
14695 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs b/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14696 index 86af3a4..5829b97 100644
14697 --- a/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14698 +++ b/gendarme/rules/Gendarme.Rules.Globalization/SatelliteResourceMismatchRule.cs
14703 +using System.Globalization;
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",
14716 + Runner.Report (satellite, Severity.Low, Confidence.High, msg);
14720 @@ -102,16 +105,20 @@ namespace Gendarme.Rules.Globalization {
14721 object satelliteValue = entry.Value;
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);
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);
14745 @@ -119,9 +126,12 @@ namespace Gendarme.Rules.Globalization {
14746 Bitmask<int> mainParameters = GetStringFormatExpectedParameters ((string) mainValue);
14747 Bitmask<int> satelliteParameters = GetStringFormatExpectedParameters ((string) satelliteValue);
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);
14761 @@ -203,7 +213,7 @@ namespace Gendarme.Rules.Globalization {
14763 string cultureExtension = "." + culture;
14765 - if (!nameWithoutExtension.EndsWith (cultureExtension))
14766 + if (!nameWithoutExtension.EndsWith (cultureExtension, StringComparison.Ordinal))
14769 string nameWithoutCulture = Path.GetFileNameWithoutExtension (nameWithoutExtension);
14770 @@ -212,7 +222,7 @@ namespace Gendarme.Rules.Globalization {
14772 private static bool IsResXResources (Resource resource)
14774 - return resource.Name.EndsWith (resXResourcesExtension);
14775 + return resource.Name.EndsWith (resXResourcesExtension, StringComparison.Ordinal);
14778 private sealed class AssemblyResourceCache {
14779 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/InternalResource.Designer.cs
14780 index 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
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
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 {
14802 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs
14803 new file mode 100644
14804 index 0000000..83fa855
14806 +++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferIFormatProviderOverrideTest.cs
14809 +// Unit tests for PreferIFormatProviderOverrideRule
14812 +// Sebastien Pouliot <sebastien@ximian.com>
14814 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
14824 +// The above copyright notice and this permission notice shall be
14825 +// included in all copies or substantial portions of the Software.
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.
14837 +using System.Globalization;
14838 +using System.Reflection;
14839 +using System.Resources;
14841 +using Gendarme.Rules.Globalization;
14842 +using NUnit.Framework;
14844 +using Test.Rules.Definitions;
14845 +using Test.Rules.Fixtures;
14847 +namespace Tests.Rules.Globalization {
14849 + class IFormatProviderTestCases {
14851 + public void Empty ()
14855 + public void Empty (IFormatProvider format)
14859 + public void BadEmpty ()
14864 + public void CorrectEmpty ()
14869 + public void First (object obj)
14873 + public void First (IFormatProvider format, object obj)
14877 + public void BadFirst ()
14882 + public void CorrectFirst ()
14884 + First (null, null);
14887 + public void Last (object obj)
14891 + public void Last (object obj, IFormatProvider format)
14895 + public void BadLast ()
14900 + public void CorrectLast ()
14902 + Last (null, null);
14906 + class CultureInfoTestCases {
14908 + public void Empty ()
14912 + public void Empty (CultureInfo info)
14916 + public void BadEmpty ()
14921 + public void CorrectEmpty ()
14926 + public void First (object obj)
14930 + public void First (CultureInfo info, object obj)
14934 + public void BadFirst ()
14939 + public void CorrectFirst ()
14941 + First (null, null);
14944 + public void Last (object obj)
14948 + public void Last (object obj, CultureInfo info)
14952 + public void BadLast ()
14957 + public void CorrectLast ()
14959 + Last (null, null);
14964 + public class PreferIFormatProviderOverrideTest : MethodRuleTestFixture<PreferIFormatProviderOverrideRule> {
14967 + public void DoesNotApply ()
14969 + AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
14970 + AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
14974 + public void Success ()
14976 + AssertRuleSuccess<IFormatProviderTestCases> ("CorrectEmpty");
14977 + AssertRuleSuccess<IFormatProviderTestCases> ("CorrectFirst");
14978 + AssertRuleSuccess<IFormatProviderTestCases> ("CorrectLast");
14980 + AssertRuleSuccess<CultureInfoTestCases> ("CorrectEmpty");
14981 + AssertRuleSuccess<CultureInfoTestCases> ("CorrectFirst");
14982 + AssertRuleSuccess<CultureInfoTestCases> ("CorrectLast");
14986 + public void Failure ()
14988 + AssertRuleFailure<IFormatProviderTestCases> ("BadEmpty", 1);
14989 + AssertRuleFailure<IFormatProviderTestCases> ("BadFirst", 1);
14990 + AssertRuleFailure<IFormatProviderTestCases> ("BadLast", 1);
14992 + AssertRuleFailure<CultureInfoTestCases> ("BadEmpty", 1);
14993 + AssertRuleFailure<CultureInfoTestCases> ("BadFirst", 1);
14994 + AssertRuleFailure<CultureInfoTestCases> ("BadLast", 1);
14997 + void Ignored (ResourceManager rm)
14999 + rm.GetObject ("a");
15000 + rm.GetObject ("a", CultureInfo.CurrentCulture);
15001 + rm.GetString ("b");
15002 + rm.GetString ("b", CultureInfo.InvariantCulture);
15007 + // the overload to use is: Format(IFormatProvider, string, params object []);
15008 + return String.Format ("{0} {1} {2}", 1, 2, 3);
15011 + void NoSimpleOverload (FieldInfo fi)
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);
15019 + public void SpecialCases ()
15021 + AssertRuleSuccess<PreferIFormatProviderOverrideTest> ("Ignored");
15022 + AssertRuleFailure<PreferIFormatProviderOverrideTest> ("Params", 1);
15023 + AssertRuleSuccess<PreferIFormatProviderOverrideTest> ("NoSimpleOverload");
15027 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs
15028 new file mode 100644
15029 index 0000000..722ff32
15031 +++ b/gendarme/rules/Gendarme.Rules.Globalization/Test/PreferStringComparisonOverrideTest.cs
15034 +// Unit tests for PreferStringComparisonOverrideRule
15037 +// Sebastien Pouliot <sebastien@ximian.com>
15039 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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:
15049 +// The above copyright notice and this permission notice shall be
15050 +// included in all copies or substantial portions of the Software.
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.
15063 +using Gendarme.Rules.Globalization;
15064 +using NUnit.Framework;
15066 +using Test.Rules.Definitions;
15067 +using Test.Rules.Fixtures;
15069 +namespace Tests.Rules.Globalization {
15072 + public class PreferStringComparisonOverrideTest : MethodRuleTestFixture<PreferStringComparisonOverrideRule> {
15075 + public void DoesNotApply ()
15077 + AssertRuleDoesNotApply (SimpleMethods.EmptyMethod);
15078 + AssertRuleDoesNotApply (SimpleMethods.ExternalMethod);
15081 + public class InstanceWithoutOverride {
15083 + public bool Compare (string s1, string s2)
15088 + public void Test ()
15090 + if (Compare ("a", "b"))
15091 + Console.WriteLine ();
15095 + public class Base {
15097 + public bool Compare (string s1, string s2)
15102 + public void TestBase ()
15104 + if (Compare ("a", "b"))
15105 + Console.WriteLine ();
15109 + public class Inherited : Base {
15110 + public bool Compare (string s1, string s2, StringComparison comparison)
15115 + public void TestInherited ()
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 ();
15124 + public class StaticHelperWithoutOverride {
15126 + // no alternative
15127 + public static bool StaticCompare (string s1, string s2)
15132 + public void Test ()
15134 + if (StaticCompare ("a", "b"))
15135 + Console.WriteLine ();
15139 + public class StaticHelperWithExtraParameterInOverride {
15141 + public static bool StaticCompare (string s1, string s2)
15146 + // the extra parameter disqualify the override
15147 + public static bool StaticCompare (string s1, string s2, bool value, StringComparison comparison)
15152 + // the extra parameter disqualify the override
15153 + public static bool StaticCompare (string s1, string s2, StringComparison comparison, bool value)
15158 + public void Test ()
15160 + if (StaticCompare ("a", "b"))
15161 + Console.WriteLine ();
15165 + public class Weird {
15166 + public bool Compare (StringComparison a, StringComparison b)
15171 + public void Test ()
15173 + if (Compare (StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase))
15174 + Console.WriteLine ();
15179 + public void Success ()
15181 + AssertRuleSuccess<InstanceWithoutOverride> ("Test");
15183 + AssertRuleSuccess<Base> ("TestBase");
15184 + AssertRuleSuccess<Inherited> ("TestInherited");
15186 + AssertRuleSuccess<StaticHelperWithoutOverride> ("Test");
15187 + AssertRuleSuccess<StaticHelperWithExtraParameterInOverride> ("Test");
15189 + AssertRuleSuccess<Weird> ("Test");
15192 + public class InstanceWithOverride {
15194 + public bool Compare (string s1, string s2)
15199 + public bool Compare (string s1, string s2, StringComparison comparison)
15205 + public void Test ()
15207 + if (Compare ("a", "b"))
15208 + Console.WriteLine ();
15212 + public class StaticHelper {
15214 + public static bool StaticCompare (string s1, string s2)
15219 + // we have an alternative
15220 + public static bool StaticCompare (string s1, string s2, StringComparison comparison)
15226 + public void Test ()
15228 + if (StaticHelper.StaticCompare ("a", "b"))
15229 + Console.WriteLine ();
15233 + public class NonString {
15235 + public bool Kompare (char [] s1, char [] s2)
15240 + public bool Kompare (char [] s1, char [] s2, StringComparison comparison)
15246 + public void TestCharArray ()
15248 + if (Kompare (new char [] { }, new char [] { }))
15249 + Console.WriteLine ();
15252 + public bool KomparInt (int a, int b)
15257 + public bool KomparInt (int a, int b, StringComparison comparison)
15263 + public void TestInt ()
15265 + if (KomparInt (0, 0))
15266 + Console.WriteLine ();
15270 + public class ExtraParameters {
15272 + public bool Kompare (int level, string s1, string s2)
15277 + public bool Kompare (int level, string s1, string s2, StringComparison comparison)
15283 + public void TestExtraFirst ()
15285 + if (Kompare (0, "a", "B"))
15286 + Console.WriteLine ();
15289 + public bool Kompar (string s1, int start, string s2)
15294 + public bool Kompar (string s1, int start, string s2, StringComparison comparison)
15300 + public void TestExtraMid ()
15302 + if (Kompar ("a", 0, "B"))
15303 + Console.WriteLine ();
15306 + public bool Komparz (string s1, string s2, int end)
15311 + // note: parameter name mismatch
15312 + public bool Komparz (string s1, string s2, int start, StringComparison comparison)
15318 + public void TestExtraEnd ()
15320 + if (Komparz ("a", "B", 0))
15321 + Console.WriteLine ();
15325 + public class FewParameters {
15327 + public bool Compare ()
15332 + public bool Compare (StringComparison comparison)
15338 + public void TestNone ()
15341 + Console.WriteLine ();
15344 + public bool Compare (object o)
15346 + return (o == null);
15349 + public bool Compare (object o, StringComparison comparison)
15355 + public void TestSingle ()
15357 + if (Compare (null))
15358 + Console.WriteLine ();
15361 + public bool Compare (short a, long b)
15366 + public bool Compare (short a, long b, StringComparison comparison)
15372 + public void TestDifferent ()
15374 + if (Compare (1, 1))
15375 + Console.WriteLine ();
15380 + public void Failure ()
15382 + AssertRuleFailure<InstanceWithOverride> ("Test");
15384 + AssertRuleFailure<StaticHelper> ("Test");
15386 + AssertRuleFailure<NonString> ("TestCharArray");
15387 + AssertRuleFailure<NonString> ("TestInt");
15389 + AssertRuleFailure<ExtraParameters> ("TestExtraFirst");
15390 + AssertRuleFailure<ExtraParameters> ("TestExtraMid");
15391 + AssertRuleFailure<ExtraParameters> ("TestExtraEnd");
15393 + AssertRuleFailure<FewParameters> ("TestNone");
15394 + AssertRuleFailure<FewParameters> ("TestSingle");
15395 + AssertRuleFailure<FewParameters> ("TestDifferent");
15399 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/PublicResource.Designer.cs
15400 index 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
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
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 {
15422 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs b/gendarme/rules/Gendarme.Rules.Globalization/Test/Resource.Designer.cs
15423 index 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
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
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 {
15445 diff --git a/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj b/gendarme/rules/Gendarme.Rules.Globalization/Test/Tests.Rules.Globalization.csproj
15446 index 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
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
15454 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
15455 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
15484 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
15485 <DebugSymbols>true</DebugSymbols>
\r
15487 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
15488 <ErrorReport>prompt</ErrorReport>
\r
15489 <WarningLevel>4</WarningLevel>
\r
15490 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
15492 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
15493 <DebugType>pdbonly</DebugType>
\r
15495 <DefineConstants>TRACE</DefineConstants>
\r
15496 <ErrorReport>prompt</ErrorReport>
\r
15497 <WarningLevel>4</WarningLevel>
\r
15498 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
15501 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
15502 @@ -128,6 +150,23 @@
15504 <Folder Include="Properties\" />
\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
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
15526 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AutoLayoutTypesShouldNotBeComVisibleRule.cs
15527 index 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 {
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.
15545 @@ -80,7 +82,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15547 public RuleResult CheckType (TypeDefinition type)
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;
15554 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidInt64ArgumentsInComVisibleMethodsRule.cs
15555 index 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;
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);
15567 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/AvoidStaticMembersInComVisibleTypesRule.cs
15568 index 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 {
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);
15580 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15581 index e25404c..5c1de40 100644
15582 --- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15583 +++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComRocks.cs
15588 +using Gendarme.Framework.Rocks;
15590 namespace Gendarme.Rules.Interoperability.Com {
15593 @@ -56,7 +58,7 @@ namespace Gendarme.Rules.Interoperability.Com {
15594 // any attribute without arguments can be skipped
15595 if (!attribute.HasConstructorArguments)
15597 - if (attribute.Constructor.DeclaringType.FullName != "System.Runtime.InteropServices.ComVisibleAttribute")
15598 + if (!attribute.Constructor.DeclaringType.IsNamed ("System.Runtime.InteropServices", "ComVisibleAttribute"))
15600 return (bool) attribute.ConstructorArguments[0].Value;
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)
15606 + // [ComVisible] attribute will be ignored on non-visible types
15607 + if (!self.IsVisible ())
15610 return (self.IsComVisible () ?? self.Module.Assembly.IsComVisible () ?? true);
15613 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15614 index 8e46c99..46291d5 100644
15615 --- a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15616 +++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ComVisibleShouldInheritFromComVisibleRule.cs
15621 +using System.Globalization;
15622 using System.Runtime.InteropServices;
15625 @@ -101,9 +102,9 @@ namespace Gendarme.Rules.Interoperability.Com {
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);
15636 return Runner.CurrentRuleResult;
15638 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/DoNotUseAutoDualClassInterfaceTypeRule.cs
15639 index 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)
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)
15651 - if (attribute.AttributeType.FullName != "System.Runtime.InteropServices.ClassInterfaceAttribute")
15652 + if (!attribute.AttributeType.IsNamed ("System.Runtime.InteropServices", "ClassInterfaceAttribute"))
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;
15660 diff --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
15661 index 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
15665 -<?xml version="1.0" encoding="utf-8"?>
15666 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
15700 - <Reference Include="System" />
15701 - <Reference Include="System.Core">
15702 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
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>
15716 - <Compile Include="..\..\AssemblyStaticInfo.cs">
15717 - <Link>AssemblyStaticInfo.cs</Link>
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" />
15732 - <Folder Include="Properties\" />
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
15792 + <Reference Include="System" />
\r
15793 + <Reference Include="System.Core">
\r
15794 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\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
15808 + <Compile Include="..\..\AssemblyStaticInfo.cs">
\r
15809 + <Link>AssemblyStaticInfo.cs</Link>
\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
15824 + <Folder Include="Properties\" />
\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
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">
15848 <Target Name="AfterBuild">
15853 \ No newline at end of file
15854 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/MarkComSourceInterfacesAsIDispatchRule.cs
15855 index 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> ();
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)
15871 - interfaces.Add (type);
15872 + interfaces.Add (type.GetFullName (), type);
15878 - // Find a TypeDefinition for an interface with the given name.
15879 - private TypeDefinition FindInterfaceDefinition (string fullName)
15881 - foreach (var def in interfaces)
15882 - if (fullName == def.FullName)
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)
15891 foreach (var attribute in type.CustomAttributes) {
15892 - if (!attribute.HasConstructorArguments)
15895 - TypeReference atype = attribute.AttributeType;
15896 - if (atype.Namespace != "System.Runtime.InteropServices")
15899 - if (atype.Name == name)
15900 + if (attribute.AttributeType.IsNamed (nameSpace, name))
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");
15908 - var attribute = FindComAttribute (def, "InterfaceTypeAttribute");
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");
15914 @@ -129,7 +114,9 @@ namespace Gendarme.Rules.Interoperability.Com {
15916 private void CheckInterface (string interface_name)
15918 - CheckInterface (FindInterfaceDefinition (interface_name));
15919 + TypeDefinition td;
15920 + if (interfaces.TryGetValue (interface_name, out td))
15921 + CheckInterface (td);
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;
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.
15934 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md b/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md
15935 new file mode 100644
15936 index 0000000..af988cb
15938 +++ b/gendarme/rules/Gendarme.Rules.Interoperability.Com/README.md
15940 +# Gendarme.Rules.Interoperability.Com Rules
15942 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability.Com(git)]] pages.
15947 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
15949 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/ReviewComRegistrationMethodsRule.cs
15950 index 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 {
15957 - const string comRegister = "System.Runtime.InteropServices.ComRegisterFunctionAttribute";
15958 - const string comUnregister = "System.Runtime.InteropServices.ComUnregisterFunctionAttribute";
15960 public RuleResult CheckType (TypeDefinition type)
15962 if (type.HasGenericParameters || !type.IsVisible () || !type.IsTypeComVisible ())
15963 @@ -111,12 +108,12 @@ namespace Gendarme.Rules.Interoperability.Com {
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;
15974 - if (!foundUnregister && name == comUnregister) {
15975 + if (!foundUnregister && atype.IsNamed ("System.Runtime.InteropServices", "ComUnregisterFunctionAttribute")) {
15976 foundUnregister = true;
15977 foundRegisterUnregisterMethod = true;
15979 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AutoLayoutTypesShouldNotBeComVisibleTest.cs
15980 index 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);
15988 + [ComVisible (true)]
15989 + public enum Enum {
15994 + [ComVisible (true)]
15995 + public enum Flags {
16000 + public void SpecialCases ()
16002 + AssertRuleDoesNotApply<Enum> ();
16003 + AssertRuleDoesNotApply<Flags> ();
16007 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/AvoidStaticMembersInComVisibleTypesTest.cs
16008 index 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> {
16014 [ComVisible (true)]
16015 - class ComVisibleClass {
16016 + public class ComVisibleClass {
16017 public static void Bad ()
16020 @@ -103,20 +103,20 @@ namespace Test.Rules.Interoperability.Com {
16023 [ComVisible (false)]
16024 - class ComInvisibleClass {
16025 + public class ComInvisibleClass {
16026 public static void DoesNotApply ()
16031 - class NoAttributesClass {
16032 + public class NoAttributesClass {
16033 public static void DoesNotApply ()
16038 [ComVisible (true)]
16039 - interface Interface {
16040 + public interface Interface {
16041 void DoesNotApply ();
16044 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/ComVisibleShouldInheritFromComVisibleTest.cs
16045 index 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
16052 +using System.Collections;
16053 using System.Runtime.InteropServices;
16056 @@ -57,6 +58,10 @@ namespace Test.Rules.Interoperability.Com {
16057 public class ComVisibleInheritsFromInvisibleClass : ComInvisibleClass {
16060 + [ComVisible (true)]
16061 + class NotReallyComVisibleInheritsFromInvisibleClass : ComInvisibleClass {
16064 [ComVisible (false)]
16065 public class ComInvisibleInheritsFromVisibleClass : ComVisibleClass {
16067 @@ -64,9 +69,6 @@ namespace Test.Rules.Interoperability.Com {
16069 public void Good ()
16071 - // no ComVisible attributes in inheritance chain
16072 - AssertRuleSuccess (SimpleTypes.Class);
16074 AssertRuleSuccess<ComVisibleClass> ();
16077 @@ -79,8 +81,15 @@ namespace Test.Rules.Interoperability.Com {
16079 public void DoesNotApply ()
16081 + // BaseType is null
16082 + AssertRuleDoesNotApply<ICollection> ();
16084 + // not visible / no ComVisible attributes in inheritance chain
16085 + AssertRuleDoesNotApply (SimpleTypes.Class);
16087 AssertRuleDoesNotApply<ComInvisibleClass> ();
16088 AssertRuleDoesNotApply<ComInvisibleInheritsFromVisibleClass> ();
16089 + AssertRuleDoesNotApply<NotReallyComVisibleInheritsFromInvisibleClass> ();
16093 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs b/gendarme/rules/Gendarme.Rules.Interoperability.Com/Test/DoNotUseAutoDualClassInterfaceTypeTest.cs
16094 index 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 {
16099 [ComVisible (true)]
16100 [ClassInterface (ClassInterfaceType.AutoDual)]
16102 + public class BadClass {
16106 [ComVisible (true)]
16107 [ClassInterface (2)]
16108 - class BadClassShortConstuctor {
16109 + public class BadClassShortConstuctor {
16113 [ComVisible (false)]
16114 [ClassInterface (ClassInterfaceType.AutoDual)]
16115 - class DoesNotApplyInvisible {
16116 + public class DoesNotApplyInvisible {
16120 [ComVisible (true)]
16121 - class GoodNoInterfaceAttribute {
16122 + public class GoodNoInterfaceAttribute {
16126 [ComVisible (true)]
16127 [ClassInterface (ClassInterfaceType.None)]
16128 - class GoodClassNone : ICloneable {
16129 + public class GoodClassNone : ICloneable {
16130 public object Clone ()
16132 return new object ();
16133 @@ -75,7 +75,7 @@ namespace Test.Rules.Interoperability.Com {
16135 [ComVisible (true)]
16136 [ClassInterface ((short)0)]
16137 - class GoodClassNoneShortConstructor : ICloneable {
16138 + public class GoodClassNoneShortConstructor : ICloneable {
16139 public object Clone ()
16141 return new object ();
16142 diff --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
16143 index 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
16147 -<?xml version="1.0" encoding="utf-8"?>
16148 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
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>
16184 - <Reference Include="System" />
16185 - <Reference Include="System.Core">
16186 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
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>
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" />
16221 - <Folder Include="Properties\" />
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
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
16283 + <Reference Include="System" />
\r
16284 + <Reference Include="System.Core">
\r
16285 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\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
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
16320 + <Folder Include="Properties\" />
\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
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">
16344 <Target Name="AfterBuild">
16349 \ No newline at end of file
16350 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16351 index fbadfc9..26d1dca 100644
16352 --- a/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16353 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/CentralizePInvokesIntoNativeMethodsTypeRule.cs
16358 +using System.Globalization;
16362 @@ -91,20 +92,22 @@ namespace Gendarme.Rules.Interoperability {
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);
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);
16380 - private void CheckSuppressUnmanagedCodeSecurity (TypeDefinition type, bool required)
16381 + private void CheckSuppressUnmanagedCodeSecurity (ICustomAttributeProvider type, bool required)
16384 - if (type.HasCustomAttributes && type.CustomAttributes.ContainsType ("System.Security.SuppressUnmanagedCodeSecurityAttribute")) {
16385 + if (type.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute")) {
16387 msg = "Remove [SuppressUnmanagedCodeSecurity] attribute on the type declaration.";
16389 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16390 index a407980..72b8ffc 100644
16391 --- a/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16392 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/DelegatesPassedToNativeCodeMustIncludeExceptionHandlingRule.cs
16395 using System.Collections.Generic;
16396 using System.Diagnostics;
16397 +using System.Globalization;
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 {
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);
16418 MethodBody body = method.Body;
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);
16428 @@ -493,12 +494,12 @@ namespace Gendarme.Rules.Interoperability {
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)
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")))
16443 // Mark the code this exception handler handles as safe.
16444 @@ -521,8 +522,8 @@ namespace Gendarme.Rules.Interoperability {
16445 // Console.ResetColor ();
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);
16455 @@ -665,7 +666,8 @@ namespace Gendarme.Rules.Interoperability {
16456 case Code.Ldloca_S:
16457 case Code.Ldloc_S: return ((VariableDefinition) ins.Operand).Index;
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);
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;
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);
16475 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16476 index 908fb83..6e2f0d6 100644
16477 --- a/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16478 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/DoNotCastIntPtrToInt32Rule.cs
16483 +using System.Globalization;
16486 using Mono.Cecil.Cil;
16487 @@ -87,7 +88,7 @@ namespace Gendarme.Rules.Interoperability {
16489 private void Report (MethodDefinition method, Instruction ins, string typeName)
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);
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")
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);
16517 @@ -190,12 +192,14 @@ namespace Gendarme.Rules.Interoperability {
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);
16538 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj b/gendarme/rules/Gendarme.Rules.Interoperability/Gendarme.Rules.Interoperability.csproj
16539 index 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
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
16547 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
16548 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
16577 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
16578 <DebugSymbols>true</DebugSymbols>
\r
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
16585 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
16586 <DebugType>pdbonly</DebugType>
\r
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
16594 <Reference Include="System" />
\r
16596 <Name>Gendarme.Framework</Name>
\r
16597 </ProjectReference>
\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
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
16619 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/GetLastErrorMustBeCalledRightAfterPInvokeRule.cs
16620 index 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 {
16627 - public bool Equals (Branch branch)
16628 + public bool Equals (Branch other)
16630 - return (Instruction == branch.Instruction) && (DirtyMethodCalled == branch.DirtyMethodCalled);
16631 + return (Instruction == other.Instruction) && (DirtyMethodCalled == other.DirtyMethodCalled);
16634 public override int GetHashCode ()
16635 @@ -135,13 +135,18 @@ namespace Gendarme.Rules.Interoperability {
16637 //check if a method is called
16638 if (ins.OpCode.FlowControl == FlowControl.Call) {
16639 + MethodReference mRef = ins.Operand as MethodReference;
16641 - MethodDefinition mDef = (ins.Operand as MethodReference).Resolve ();
16642 + if (mRef == null) {
16646 + MethodDefinition mDef = mRef.Resolve();
16647 if (mDef != null && mDef.IsPInvokeImpl) { //check if another pinvoke method is called, this counts as "GetLastError not called"
16651 - string s = (mDef == null) ? String.Empty : mDef.DeclaringType.FullName;
16653 + string s = (mDef == null) ? String.Empty : mDef.DeclaringType.GetFullName ();
16655 case "System.Runtime.InteropServices.Marshal":
16656 getLastErrorFound = (mDef.Name == "GetLastWin32Error");
16657 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalBooleansInPInvokeDeclarationsRule.cs
16658 index 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 {
16665 - static bool CheckBooleanMarshalling (IMarshalInfoProvider spec, MemberReference type)
16666 + static bool CheckBooleanMarshalling (IMarshalInfoProvider spec, TypeReference type)
16668 // is marshalling information provided
16669 if (spec.MarshalInfo != null)
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));
16676 public RuleResult CheckMethod (MethodDefinition method)
16677 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16678 index 442dd74..7edf597 100644
16679 --- a/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16680 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/MarshalStringsInPInvokeDeclarationsRule.cs
16685 +using System.Globalization;
16688 using Gendarme.Framework;
16689 +using Gendarme.Framework.Rocks;
16691 namespace Gendarme.Rules.Interoperability {
16693 @@ -69,13 +71,8 @@ namespace Gendarme.Rules.Interoperability {
16695 private static bool IsStringOrSBuilder (TypeReference reference)
16697 - switch (reference.GetElementType ().FullName) {
16698 - case "System.String":
16699 - case "System.Text.StringBuilder":
16704 + TypeReference type = reference.GetElementType ();
16705 + return (type.IsNamed ("System", "String") || type.IsNamed ("System.Text", "StringBuilder"));
16708 public RuleResult CheckMethod (MethodDefinition method)
16709 @@ -93,7 +90,8 @@ namespace Gendarme.Rules.Interoperability {
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);
16719 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/README.md b/gendarme/rules/Gendarme.Rules.Interoperability/README.md
16720 new file mode 100644
16721 index 0000000..7932c1e
16723 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/README.md
16725 +# Gendarme.Rules.Interoperability Rules
16727 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Interoperability(git)]] pages.
16732 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
16734 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj b/gendarme/rules/Gendarme.Rules.Interoperability/Test/Tests.Rules.Interoperability.csproj
16735 index 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
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
16743 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
16744 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
16773 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
16774 <DebugSymbols>true</DebugSymbols>
\r
16776 <ErrorReport>prompt</ErrorReport>
\r
16777 <WarningLevel>4</WarningLevel>
\r
16778 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
\r
16779 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
16781 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
16782 <DebugType>pdbonly</DebugType>
\r
16784 <ErrorReport>prompt</ErrorReport>
\r
16785 <WarningLevel>4</WarningLevel>
\r
16786 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
\r
16787 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
16790 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
16793 <Folder Include="Properties\" />
\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
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
16815 diff --git a/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs b/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16816 index 4f502cb..27c7d8f 100644
16817 --- a/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16818 +++ b/gendarme/rules/Gendarme.Rules.Interoperability/UseManagedAlternativesToPInvokeRule.cs
16823 -using System.Linq;
16824 using System.Collections.Generic;
16825 +using System.Globalization;
16826 +using System.Linq;
16828 using Gendarme.Framework;
16830 @@ -129,7 +130,8 @@ namespace Gendarme.Rules.Interoperability {
16831 if (alternatives == null)
16832 return RuleResult.Success;
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;
16840 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidAlwaysNullFieldRule.cs
16841 index 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 {
16849 + void CheckMethods (TypeDefinition type)
16851 + if (!type.HasMethods)
16854 + IList<MethodDefinition> mc = type.Methods;
16855 + for (int i = 0; i < mc.Count && nullFields.Count > 0; ++i)
16856 + CheckMethod (mc [i]);
16859 public RuleResult CheckType (TypeDefinition type)
16861 @@ -175,7 +185,7 @@ namespace Gendarme.Rules.Maintainability {
16862 Log.WriteLine (this);
16863 Log.WriteLine (this, "----------------------------------");
16865 - bool isWinFormControl = usesWinForms && type.Inherits("System.Windows.Forms.Control");
16866 + bool isWinFormControl = usesWinForms && type.Inherits ("System.Windows.Forms", "Control");
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);
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);
16884 // Report a defect if:
16885 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16886 index 46200ab..59d780d 100644
16887 --- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16888 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
16891 using System.Collections.Generic;
16892 using System.ComponentModel;
16893 +using System.Globalization;
16896 using Mono.Cecil.Cil;
16897 @@ -127,7 +128,8 @@ namespace Gendarme.Rules.Maintainability {
16899 Severity sev = GetCyclomaticComplexitySeverity(cc);
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;
16907 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16908 index a0e2af8..010ac00 100644
16909 --- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16910 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidDeepInheritanceTreeRule.cs
16914 using System.ComponentModel;
16915 +using System.Globalization;
16919 @@ -84,11 +85,12 @@ namespace Gendarme.Rules.Maintainability {
16920 return RuleResult.DoesNotApply;
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)
16931 - if (countExternalDepth || Runner.Assemblies.Contains (type.Module.Assembly))
16932 + if (countExternalDepth || Runner.Assemblies.Contains(temp.Module.Assembly))
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;
16946 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16947 index 4a428f0..44df73b 100644
16948 --- a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16949 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidLackOfCohesionOfMethodsRule.cs
16952 using System.Collections.Generic;
16953 using System.ComponentModel;
16954 +using System.Globalization;
16957 using Mono.Cecil.Cil;
16958 @@ -88,7 +89,8 @@ namespace Gendarme.Rules.Maintainability {
16960 Severity sev = GetCohesivenessSeverity(coh);
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;
16968 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/AvoidUnnecessarySpecializationRule.cs
16969 index 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?
16976 - parameters [i] = pType.FullName;
16977 + parameters [i] = pType.GetFullName ();
16979 return new MethodSignature (name, rtype, parameters);
16981 @@ -225,7 +225,7 @@ namespace Gendarme.Rules.Maintainability {
16982 //special exception
16983 if (!method.HasParameters && (method.Name == "GetEnumerator"))
16985 - return method.ReturnType.FullName;
16986 + return method.ReturnType.GetFullName ();
16989 private static bool IsSystemObjectMethod (MethodReference method)
16990 @@ -250,7 +250,7 @@ namespace Gendarme.Rules.Maintainability {
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")));
16999 @@ -262,7 +262,7 @@ namespace Gendarme.Rules.Maintainability {
17001 private static bool IsIgnoredSuggestionType (TypeReference type)
17003 - return ((type.FullName == "System.Object") || IsFromNonGenericCollectionNamespace (type.Namespace));
17004 + return (type.IsNamed ("System", "Object") || IsFromNonGenericCollectionNamespace (type.Namespace));
17007 private static List<MethodSignature> GetSignatures (IEnumerable<StackEntryUsageResult> usageResults)
17008 @@ -285,7 +285,7 @@ namespace Gendarme.Rules.Maintainability {
17010 private void UpdateParameterLeastType (ParameterReference parameter, IEnumerable<StackEntryUsageResult> usageResults)
17012 - int pIndex = parameter.GetSequence () - 1;
17013 + int pIndex = parameter.Index;
17014 int parameterDepth = GetActualTypeDepth (parameter.ParameterType);
17016 int currentLeastDepth = 0;
17017 @@ -366,7 +366,7 @@ namespace Gendarme.Rules.Maintainability {
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))
17025 // is parameter already known ?
17026 @@ -474,7 +474,7 @@ namespace Gendarme.Rules.Maintainability {
17028 foreach (ParameterDefinition parameter in method.Parameters){
17030 - int i = parameter.GetSequence () - 1;
17031 + int i = parameter.Index;
17032 if (null == types_least [i])
17033 continue; //argument is not used
17035 @@ -540,7 +540,7 @@ namespace Gendarme.Rules.Maintainability {
17039 - string fullname = type.FullName;
17040 + string fullname = type.GetFullName ();
17041 sb.Append (fullname.Substring (0, fullname.Length - nRemoveTrail));
17044 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/ConsiderUsingStopwatchRule.cs
17045 index 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 {
17052 - private const string DateTime = "System.DateTime";
17053 - private const string GetNow = "get_Now";
17055 public override void Initialize (IRunner runner)
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");
17072 @@ -106,7 +106,7 @@ namespace Gendarme.Rules.Maintainability {
17075 MethodReference calledMethod = (MethodReference) ins.Operand;
17076 - return calledMethod.DeclaringType.FullName == DateTime && calledMethod.Name == GetNow;
17077 + return calledMethod.IsNamed ("System", "DateTime", "get_Now");
17080 private static bool CheckParameters (MethodDefinition method, Instruction ins)
17081 @@ -125,14 +125,14 @@ namespace Gendarme.Rules.Maintainability {
17082 ParameterDefinition p = prev.GetParameter (method);
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);
17096 prev = prev.Previous;
17098 @@ -161,11 +161,10 @@ namespace Gendarme.Rules.Maintainability {
17099 return RuleResult.DoesNotApply;
17101 foreach (Instruction ins in method.Body.Instructions) {
17102 - if (!calls.Get (ins.OpCode.Code))
17103 + MethodReference calledMethod = ins.GetMethod ();
17104 + if (calledMethod == null)
17107 - MethodReference calledMethod = (MethodReference) ins.Operand;
17108 - if (calledMethod.DeclaringType.FullName != DateTime)
17109 + if (!calledMethod.DeclaringType.IsNamed ("System", "DateTime"))
17111 if (!MethodSignatures.op_Subtraction.Matches (calledMethod))
17113 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj b/gendarme/rules/Gendarme.Rules.Maintainability/Gendarme.Rules.Maintainability.csproj
17114 index 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
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
17122 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
17123 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
17152 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
17153 <DebugSymbols>true</DebugSymbols>
\r
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
17160 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
17161 <DebugType>pdbonly</DebugType>
\r
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
17169 <Reference Include="System" />
\r
17171 <Name>Gendarme.Framework</Name>
\r
17172 </ProjectReference>
\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
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.
17194 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/PreferStringIsNullOrEmptyRule.cs
17195 index 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 {
17200 return (ins.Operand as VariableDefinition).Name;
17202 - return (ins.Operand == null) ? String.Empty : ins.Operand.ToString ();
17203 + object o = ins.Operand;
17204 + MemberReference mr = (o as MemberReference);
17206 + return mr.GetFullName ();
17207 + else if (o != null)
17208 + return o.ToString ();
17210 + return String.Empty;
17214 @@ -196,7 +203,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17223 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/README.md b/gendarme/rules/Gendarme.Rules.Maintainability/README.md
17224 new file mode 100644
17225 index 0000000..d843fdd
17227 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/README.md
17229 +# Gendarme.Rules.Maintainability Rules
17231 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Maintainability(git)]] pages.
17236 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
17238 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17239 index 7686b8e..31868ea 100644
17240 --- a/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17241 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/RemoveDependenceOnObsoleteCodeRule.cs
17245 using System.Collections.Generic;
17246 +using System.Globalization;
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 {
17254 - const string Obsolete = "System.ObsoleteAttribute";
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);
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);
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);
17286 @@ -154,7 +153,7 @@ namespace Gendarme.Rules.Maintainability {
17287 if (!IsObsolete (type.BaseType))
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);
17295 @@ -162,7 +161,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17304 @@ -172,7 +171,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17313 @@ -183,7 +182,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17322 @@ -194,7 +193,7 @@ namespace Gendarme.Rules.Maintainability {
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)
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;
17339 // check if we inherit from an [Obsolete] class / struct / enum
17340 @@ -249,7 +248,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17349 @@ -261,7 +260,7 @@ namespace Gendarme.Rules.Maintainability {
17350 if (!IsObsolete (rt))
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);
17358 @@ -269,7 +268,7 @@ namespace Gendarme.Rules.Maintainability {
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);
17367 @@ -280,7 +279,7 @@ namespace Gendarme.Rules.Maintainability {
17368 if (!IsObsolete (type))
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);
17376 @@ -292,11 +291,11 @@ namespace Gendarme.Rules.Maintainability {
17379 if (IsObsolete (call)) {
17380 - msg = String.Format ("Method '{0}' is obsolete.", call);
17381 + msg = String.Format (CultureInfo.InvariantCulture, "Method '{0}' is obsolete.", call);
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);
17390 @@ -312,9 +311,9 @@ namespace Gendarme.Rules.Maintainability {
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);
17402 @@ -339,7 +338,7 @@ namespace Gendarme.Rules.Maintainability {
17403 return RuleResult.DoesNotApply;
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;
17410 // check method signature (parameters, return value)
17411 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs b/gendarme/rules/Gendarme.Rules.Maintainability/ReviewMisleadingFieldNamesRule.cs
17412 index 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.
17423 using Gendarme.Framework;
17425 namespace Gendarme.Rules.Maintainability {
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.
17434 - /// public class Bad {
17435 - /// public int s_Value;
17436 - /// public static int m_OtherValue;
17438 + /// public class Bad {
17440 + /// static int m_other_value;
17447 - /// public class Good {
17448 - /// public int m_Value;
17449 - /// public static int s_OtherValue;
17451 + /// public class Good {
17453 + /// static int other_value;
17458 @@ -68,7 +68,8 @@ namespace Gendarme.Rules.Maintainability {
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);
17468 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17469 index 95ac856..4307c2f 100644
17470 --- a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17471 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidAlwaysNullFieldTest.cs
17475 // Jesse Jones <jesjones@mindspring.com>
17476 +// Sebastien Pouliot <sebastien@ximian.com>
17478 // Copyright (C) 2008 Jesse Jones
17479 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
17481 // Permission is hereby granted, free of charge, to any person obtaining
17482 // a copy of this software and associated documentation files (the
17485 using System.Collections.Generic;
17487 -using System.Runtime.InteropServices;
17488 -using System.Text;
17489 +using System.Threading;
17491 using Gendarme.Rules.Maintainability;
17493 @@ -231,5 +232,51 @@ namespace Test.Rules.Maintainability {
17494 AssertRuleSuccess<Bug667692a> ();
17495 AssertRuleSuccess<Bug667692b> ();
17498 + // this will create an anonymous method
17499 + class AnonymousDelegatesAllFields {
17505 + ThreadPool.QueueUserWorkItem (delegate {
17512 + Console.WriteLine (file);
17516 + // this will create a nested type with the anonymous method
17517 + class AnonymousDelegatesFieldsAndLocals {
17525 + ThreadPool.QueueUserWorkItem (delegate {
17533 + Console.WriteLine (file);
17538 + public void AnonymousDelegates ()
17540 + AssertRuleSuccess<AnonymousDelegatesAllFields> ();
17541 + AssertRuleSuccess<AnonymousDelegatesFieldsAndLocals> ();
17545 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17546 index c974504..1ae36c4 100644
17547 --- a/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17548 +++ b/gendarme/rules/Gendarme.Rules.Maintainability/Test/AvoidUnnecessarySpecializationTest.cs
17553 -using System.Reflection;
17554 using System.Collections;
17555 using System.Collections.Generic;
17556 +using System.Linq;
17557 +using System.Reflection;
17561 @@ -631,5 +632,34 @@ namespace Test.Rules.Maintainability {
17562 AssertRuleSuccess<GeneralizedClass> ("OverloadNotSupportedByInterface");
17563 AssertRuleFailure<SpecializedClass> ("OverloadNotSupportedByInterface", 1);
17566 + class TestCase690057 {
17567 + public class nauczyciel {
17569 + public List<object> NoweGrupies = new List<object> ();
17571 + public List<nauczyciel> nauczyciele = new List<nauczyciel> ();
17572 + public void WyslijMaile (List<Guid> ListIdJ, Guid idRok)
17575 + var cmd = from c in nauczyciele
17576 + where ListIdJ.Contains (c.Oid)
17578 + foreach (var s in cmd) {
17580 + foreach (var grp in s.NoweGrupies)
17583 + catch (Exception ex) {
17590 + public void Bug690057 ()
17592 + AssertRuleSuccess<TestCase690057> ("WyslijMaile");
17596 diff --git a/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj b/gendarme/rules/Gendarme.Rules.Maintainability/Test/Tests.Rules.Maintainability.csproj
17597 index 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
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
17605 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
17606 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
17635 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
17636 <DebugSymbols>true</DebugSymbols>
\r
17638 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
17639 <ErrorReport>prompt</ErrorReport>
\r
17640 <WarningLevel>4</WarningLevel>
\r
17641 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
17643 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
17644 <DebugType>pdbonly</DebugType>
\r
17646 <DefineConstants>TRACE</DefineConstants>
\r
17647 <ErrorReport>prompt</ErrorReport>
\r
17648 <WarningLevel>4</WarningLevel>
\r
17649 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
17652 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
17655 <Folder Include="Properties\" />
\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
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.
17677 diff --git a/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj b/gendarme/rules/Gendarme.Rules.NUnit/Gendarme.Rules.NUnit.csproj
17678 index 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
17682 -<?xml version="1.0" encoding="utf-8"?>
17683 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
17717 - <Reference Include="System" />
17718 - <Reference Include="System.Core">
17719 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
17723 - <Compile Include="..\..\AssemblyStaticInfo.cs">
17724 - <Link>AssemblyStaticInfo.cs</Link>
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" />
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>
17743 - <Folder Include="Properties\" />
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
17803 + <Reference Include="System" />
\r
17804 + <Reference Include="System.Core">
\r
17805 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
17809 + <Compile Include="..\..\AssemblyStaticInfo.cs">
\r
17810 + <Link>AssemblyStaticInfo.cs</Link>
\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
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
17829 + <Folder Include="Properties\" />
\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
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">
17853 <Target Name="AfterBuild">
17858 \ No newline at end of file
17859 diff --git a/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs b/gendarme/rules/Gendarme.Rules.NUnit/ProvideMessageOnAssertCallsRule.cs
17860 index 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 {
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))
17872 @@ -105,7 +105,7 @@ namespace Gendarme.Rules.NUnit {
17873 if (resolvedMethod == null)
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;
17881 diff --git a/gendarme/rules/Gendarme.Rules.NUnit/README.md b/gendarme/rules/Gendarme.Rules.NUnit/README.md
17882 new file mode 100644
17883 index 0000000..00a3cb5
17885 +++ b/gendarme/rules/Gendarme.Rules.NUnit/README.md
17887 +# Gendarme.Rules.NUnit Rules
17889 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.NUnit(git)]] pages.
17894 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
17896 diff --git a/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj b/gendarme/rules/Gendarme.Rules.NUnit/Test/Tests.Rules.NUnit.csproj
17897 index 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
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
17905 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
17906 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
17935 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
17936 <DebugSymbols>true</DebugSymbols>
\r
17938 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
17939 <ErrorReport>prompt</ErrorReport>
\r
17940 <WarningLevel>4</WarningLevel>
\r
17941 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
17943 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
17944 <DebugType>pdbonly</DebugType>
\r
17946 <DefineConstants>TRACE</DefineConstants>
\r
17947 <ErrorReport>prompt</ErrorReport>
\r
17948 <WarningLevel>4</WarningLevel>
\r
17949 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
17952 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
17955 <Folder Include="Properties\" />
\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
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.
17977 diff --git a/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs b/gendarme/rules/Gendarme.Rules.NUnit/UnitTestsMissingTestFixtureRule.cs
17978 index 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 ();
17990 diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidDeepNamespaceHierarchyRule.cs
17991 index 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; }
18000 + return max_depth;
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)) {
18009 - } else if (ns.EndsWith (".Internal") || ns.EndsWith (".Impl")) {
18010 + } else if (ns.EndsWith (".Internal", StringComparison.Ordinal) || ns.EndsWith (".Impl", StringComparison.Ordinal)) {
18014 @@ -149,5 +151,11 @@ namespace Gendarme.Rules.Naming {
18016 return Runner.CurrentRuleResult;
18019 + public override string Solution {
18021 + return string.Format("Try to keep the depth below {0}, with an additional one for specialization (e.g. Design, Interop, Permissions).", MaxDepth);
18026 diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18027 index 305f23b..2bff9a0 100644
18028 --- a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18029 +++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInMethodNameRule.cs
18031 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18034 +using System.Globalization;
18038 @@ -138,7 +139,7 @@ namespace Gendarme.Rules.Naming {
18039 if (method_name.StartsWith (name, StringComparison.Ordinal))
18040 return RuleResult.Success;
18042 - int pos = method_name.LastIndexOf (name);
18043 + int pos = method_name.LastIndexOf (name, StringComparison.Ordinal);
18045 return RuleResult.Success;
18047 @@ -159,10 +160,11 @@ namespace Gendarme.Rules.Naming {
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);
18056 - msg = String.Format ("Consider renaming method to '{0}'.", suggestion);
18057 + msg = String.Format (CultureInfo.InvariantCulture, "Consider renaming method to '{0}'.", suggestion);
18060 Runner.Report (method, severity, confidence, msg);
18061 @@ -184,7 +186,7 @@ namespace Gendarme.Rules.Naming {
18063 private static string GetSuggestionMemberKind (IMethodSignature method)
18065 - if (method.Parameters.Count == 1 && method.ReturnType.FullName != "System.Void")
18066 + if (method.Parameters.Count == 1 && !method.ReturnType.IsNamed ("System", "Void"))
18070 diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18071 index b050cb5..7a36180 100644
18072 --- a/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18073 +++ b/gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs
18077 using System.Collections.Generic;
18078 +using System.Globalization;
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 {
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;
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;
18099 diff --git a/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs b/gendarme/rules/Gendarme.Rules.Naming/AvoidTypeInterfaceInconsistencyRule.cs
18100 index 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;
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);
18118 diff --git a/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs b/gendarme/rules/Gendarme.Rules.Naming/DetectNonAlphaNumericsInTypeNamesRule.cs
18119 index 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 {
18126 - private const string GuidAttribute = "System.Runtime.InteropServices.GuidAttribute";
18127 - private const string InterfaceTypeAttribute = "System.Runtime.InteropServices.InterfaceTypeAttribute";
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 {
18134 private static bool UsedForComInterop (TypeDefinition type)
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"));
18142 public RuleResult CheckAssembly (AssemblyDefinition assembly)
18143 diff --git a/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj b/gendarme/rules/Gendarme.Rules.Naming/Gendarme.Rules.Naming.csproj
18144 index 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
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
18152 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
18153 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
18182 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
18183 <DebugSymbols>true</DebugSymbols>
\r
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
18190 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
18191 <DebugType>pdbonly</DebugType>
\r
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
18199 <Compile Include="..\..\AssemblyStaticInfo.cs">
\r
18201 <RequiredTargetFramework>3.5</RequiredTargetFramework>
\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
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.
18224 diff --git a/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs b/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18225 index 95a3e46..7e4a8db 100644
18226 --- a/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18227 +++ b/gendarme/rules/Gendarme.Rules.Naming/ParameterNamesShouldMatchOverridenMethodRule.cs
18231 // Andreas Noever <andreas.noever@gmail.com>
18232 +// Sebastien Pouliot <sebastien@ximian.com>
18234 // (C) 2008 Andreas Noever
18235 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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);
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");
18252 @@ -97,29 +101,26 @@ namespace Gendarme.Rules.Naming {
18253 if (name != base_name) {
18254 if (!explicitInterfaceCheck)
18256 - string full_name = baseMethod.DeclaringType.FullName;
18257 - if (!name.StartsWith (full_name, StringComparison.Ordinal))
18259 + TypeReference btype = baseMethod.DeclaringType;
18260 + string bnspace = btype.Namespace;
18261 + if (!name.StartsWith (bnspace, StringComparison.Ordinal))
18263 - if (name [full_name.Length] != '.')
18264 + if (name [bnspace.Length] != '.')
18266 - if (name.LastIndexOf (base_name, StringComparison.Ordinal) != full_name.Length + 1)
18268 + string bname = btype.Name;
18269 + if (String.CompareOrdinal (bname, 0, name, bnspace.Length + 1, bname.Length) != 0)
18272 - if (method.ReturnType.FullName != baseMethod.ReturnType.FullName)
18274 - if (method.HasParameters != baseMethod.HasParameters)
18277 - IList<ParameterDefinition> pdc = method.Parameters;
18278 - IList<ParameterDefinition> base_pdc = baseMethod.Parameters;
18279 - if (pdc.Count != base_pdc.Count)
18281 + int dot = bnspace.Length + bname.Length + 1;
18282 + if (name [dot] != '.')
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)
18291 + return method.CompareSignature (baseMethod);
18294 private static MethodDefinition GetBaseMethod (MethodDefinition method)
18295 @@ -130,7 +131,7 @@ namespace Gendarme.Rules.Naming {
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
18303 foreach (MethodDefinition baseMethodCandidate in baseType.Methods) {
18304 @@ -143,11 +144,15 @@ namespace Gendarme.Rules.Naming {
18306 private static MethodDefinition GetInterfaceMethod (MethodDefinition method)
18308 - TypeDefinition type = (TypeDefinition) method.DeclaringType;
18309 + TypeDefinition type = (method.DeclaringType as TypeDefinition);
18310 + if (!type.HasInterfaces)
18313 foreach (TypeReference interfaceReference in type.Interfaces) {
18314 TypeDefinition interfaceCandidate = interfaceReference.Resolve ();
18315 - if (interfaceCandidate == null)
18316 + if ((interfaceCandidate == null) || !interfaceCandidate.HasMethods)
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);
18332 @@ -185,21 +191,11 @@ namespace Gendarme.Rules.Naming {
18333 return Runner.CurrentRuleResult;
18336 - private const string BooMacroStatement = "Boo.Lang.Compiler.Ast.MacroStatement";
18338 - private bool IsBooAssemblyUsingMacro {
18340 - return isBooAssemblyUsingMacro;
18343 - isBooAssemblyUsingMacro = value;
18346 - private bool isBooAssemblyUsingMacro;
18347 + private bool IsBooAssemblyUsingMacro { get; set; }
18349 private static bool IsBooMacroParameter (ParameterReference p)
18351 - return p.Name == "macro" && p.ParameterType.FullName == BooMacroStatement;
18352 + return p.Name == "macro" && p.ParameterType.IsNamed ("Boo.Lang.Compiler.Ast", "MacroStatement");
18356 diff --git a/gendarme/rules/Gendarme.Rules.Naming/README.md b/gendarme/rules/Gendarme.Rules.Naming/README.md
18357 new file mode 100644
18358 index 0000000..a5e5992
18360 +++ b/gendarme/rules/Gendarme.Rules.Naming/README.md
18362 +# Gendarme.Rules.Naming Rules
18364 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Naming(git)]] pages.
18369 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
18371 diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18372 index ff5fc3a..7baa37f 100644
18373 --- a/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18374 +++ b/gendarme/rules/Gendarme.Rules.Naming/Test/ParameterNamesShouldMatchOverridenMethodTest.cs
18378 // Andreas Noever <andreas.noever@gmail.com>
18379 +// Sebastien Pouliot <sebastien@ximian.com>
18381 // (C) 2008 Andreas Noever
18382 +// Copyright (C) 2011 Novell, Inc (http://www.novell.com)
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 @@
18390 -using System.Reflection;
18392 -using Gendarme.Framework;
18393 +using Gendarme.Framework.Helpers;
18394 using Gendarme.Rules.Naming;
18395 -using Gendarme.Framework.Rocks;
18398 using NUnit.Framework;
18399 -using Test.Rules.Helpers;
18400 +using Test.Rules.Fixtures;
18402 namespace Test.Rules.Naming {
18404 @@ -75,141 +74,94 @@ namespace Test.Rules.Naming {
18408 - public class ParameterNamesShouldMatchOverridenMethodTest : BaseClass, ISomeInterface, ISomeInterface2 {
18409 + public class ParameterNamesShouldMatchOverridenMethodTest : MethodRuleTestFixture<ParameterNamesShouldMatchOverriddenMethodRule> {
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)
18420 - [TestFixtureSetUp]
18421 - public void FixtureSetUp ()
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);
18429 + protected override void VirtualIncorrect (int vi1, int vi2a)
18433 - private MethodDefinition GetTest (string name)
18435 - foreach (MethodDefinition method in type.Methods) {
18436 - if (method.Name == name)
18438 + protected override void VirtualSuperIncorrect (int vsi1, bool vsi2_)
18444 - protected override void VirtualCorrect (int vc1, int vc2)
18447 + protected override void AbstractCorrect (int ac1, int ac2)
18449 + throw new NotImplementedException ();
18453 - public void TestVirtualCorrect ()
18455 - MethodDefinition method = GetTest ("VirtualCorrect");
18456 - Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18457 - Assert.AreEqual (0, runner.Defects.Count, "Count");
18459 + protected override void AbstractIncorrect (int ai1, int ai2_)
18461 + throw new NotImplementedException ();
18464 - protected override void VirtualIncorrect (int vi1, int vi2a)
18467 + protected virtual void NoOverwrite (int a, int bb)
18472 - public void TestVirtualIncorrect ()
18474 - MethodDefinition method = GetTest ("VirtualIncorrect");
18475 - Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18476 - Assert.AreEqual (1, runner.Defects.Count, "Count");
18478 + public bool InterfaceMethod (int im_)
18483 - protected override void VirtualSuperIncorrect (int vsi1, bool vsi2_)
18486 + bool ISomeInterface2.InterfaceMethod2 (int im_)
18492 - public void TestVirtualSuperIncorrect ()
18494 - MethodDefinition method = GetTest ("VirtualSuperIncorrect");
18495 - Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18496 - Assert.AreEqual (1, runner.Defects.Count, "Count");
18498 + void NoParameter ()
18502 - protected override void AbstractCorrect (int ac1, int ac2)
18504 - throw new NotImplementedException ();
18505 + public bool Equals (string s)
18507 + throw new NotImplementedException ();
18512 - public void TestAbstractCorrect ()
18513 + public void TestVirtual ()
18515 - MethodDefinition method = GetTest ("AbstractCorrect");
18516 - Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18517 - Assert.AreEqual (0, runner.Defects.Count, "Count");
18520 - protected override void AbstractIncorrect (int ai1, int ai2_)
18522 - throw new NotImplementedException ();
18523 + AssertRuleSuccess<TestCase> ("VirtualCorrect");
18524 + AssertRuleFailure<TestCase> ("VirtualIncorrect", 1);
18525 + AssertRuleFailure<TestCase> ("VirtualSuperIncorrect", 1);
18529 - public void TestAbstractIncorrect ()
18531 - MethodDefinition method = GetTest ("AbstractIncorrect");
18532 - Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18533 - Assert.AreEqual (1, runner.Defects.Count, "Count");
18536 - protected virtual void NoOverwrite (int a, int bb)
18537 + public void TestAbstract ()
18539 + AssertRuleSuccess<TestCase> ("AbstractCorrect");
18540 + AssertRuleFailure<TestCase> ("AbstractIncorrect", 1);
18544 public void TestNoOverwrite ()
18546 - MethodDefinition method = GetTest ("NoOverwrite");
18547 - Assert.AreEqual (RuleResult.Success, runner.CheckMethod (method), "RuleResult");
18548 - Assert.AreEqual (0, runner.Defects.Count, "Count");
18551 - public bool InterfaceMethod (int im_)
18554 + AssertRuleSuccess<TestCase> ("NoOverwrite");
18558 public void TestInterfaceMethod ()
18560 - MethodDefinition method = GetTest ("InterfaceMethod");
18561 - Assert.AreEqual (RuleResult.Failure, runner.CheckMethod (method), "RuleResult");
18562 - Assert.AreEqual (1, runner.Defects.Count, "Count");
18565 - bool ISomeInterface2.InterfaceMethod2 (int im_)
18568 + AssertRuleFailure<TestCase> ("InterfaceMethod", 1);
18569 + AssertRuleFailure<TestCase> ("Test.Rules.Naming.ISomeInterface2.InterfaceMethod2", 1);
18573 - public void TestInterfaceMethod2 ()
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");
18580 - void NoParameter ()
18581 + public void TestDoesNotApply ()
18583 + AssertRuleDoesNotApply<TestCase> ("NoParameter");
18587 - public void TestDoesNotApply ()
18588 + public void GenericInterface ()
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);
18597 diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj b/gendarme/rules/Gendarme.Rules.Naming/Test/Tests.Rules.Naming.csproj
18598 index 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
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
18606 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
18607 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
18636 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
18637 <DebugSymbols>true</DebugSymbols>
\r
18639 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
18640 <ErrorReport>prompt</ErrorReport>
\r
18641 <WarningLevel>4</WarningLevel>
\r
18642 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
18644 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
18645 <DebugType>pdbonly</DebugType>
\r
18647 <DefineConstants>TRACE</DefineConstants>
\r
18648 <ErrorReport>prompt</ErrorReport>
\r
18649 <WarningLevel>4</WarningLevel>
\r
18650 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
18653 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
18656 <Folder Include="Properties\" />
\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
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.
18678 diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectPrefixTest.cs
18679 index 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 {
18686 + public class InMemoryDoohicky
18690 public interface I {
18693 @@ -102,6 +106,7 @@ namespace Test.Rules.Naming {
18694 AssertRuleFailure<CIncorrectClass> (1);
18695 AssertRuleFailure<INcorrectClass> (1);
18696 AssertRuleSuccess<ILRange> ();
18697 + AssertRuleSuccess<InMemoryDoohicky> ();
18701 diff --git a/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs b/gendarme/rules/Gendarme.Rules.Naming/Test/UseCorrectSuffixTest.cs
18702 index 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 {
18709 - public class DerivingClassImplementingInterfaces : EventArgs, IEnumerable, IPermission {
18710 + public class DerivingClassImplementingInterfaces : EventArgs, IPermission {
18712 - public IEnumerator GetEnumerator ()
18714 - throw new NotImplementedException();
18717 public void FromXml (SecurityElement e)
18719 throw new NotImplementedException();
18720 @@ -246,16 +241,27 @@ namespace Test.Rules.Naming {
18721 public class DictionaryIncorrectDerived<T, V> : DictionaryIncorrect<T, V> {
18724 + // test case from https://github.com/Iristyle/mono-tools/commit/40bfb2260511cfe4171e9153c3c434fedd8a4d4a.diff
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(); }
18736 public class UseCorrectSuffixTest : TypeRuleTestFixture<UseCorrectSuffixRule> {
18738 - void AssertRuleFailureWithHighConfidence<T>()
18739 + void AssertRuleFailureWithHighConfidence<T> (int num)
18741 - AssertRuleFailure<T> (1);
18742 + AssertRuleFailure<T> (num);
18743 Assert.AreEqual (Confidence.High, Runner.Defects [0].Confidence, typeof (T).Name);
18746 - void AssertRuleFailureWithLowConfidence<T>()
18747 + void AssertRuleFailureWithLowConfidence<T> ()
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 {
18753 public void TestOneLevelInheritanceIncorrectName ()
18755 - AssertRuleFailureWithHighConfidence<IncorrectAttr> ();
18756 + AssertRuleFailureWithHighConfidence<IncorrectAttr> (1);
18760 @@ -288,7 +294,7 @@ namespace Test.Rules.Naming {
18762 public void TestVariousLevelInheritanceIncorrectName ()
18764 - AssertRuleFailureWithHighConfidence<OtherAttr> ();
18765 + AssertRuleFailureWithHighConfidence<OtherAttr> (1);
18769 @@ -326,7 +332,7 @@ namespace Test.Rules.Naming {
18771 public void TestMultipleInterfaceImplementerIncorrectName ()
18773 - AssertRuleFailureWithHighConfidence<MultipleInterfaceImplementer> ();
18774 + AssertRuleFailureWithHighConfidence<MultipleInterfaceImplementer> (1);
18778 @@ -342,7 +348,7 @@ namespace Test.Rules.Naming {
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);
18787 @@ -360,23 +366,24 @@ namespace Test.Rules.Naming {
18789 public void TestDerivingClassImplementingInterfacesAnotherIncorrectName ()
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);
18799 public void GenericCollection ()
18801 AssertRuleSuccess<CorrectCollection<int>> ();
18802 - AssertRuleFailureWithHighConfidence<CollectionIncorrect<int>> ();
18803 + AssertRuleFailureWithHighConfidence<CollectionIncorrect<int>> (1);
18807 public void GenericDictionary ()
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);
18817 @@ -410,11 +417,11 @@ namespace Test.Rules.Naming {
18818 public void CheckShouldNeverBeUsedSuffixes ()
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);
18833 class MyCollection : EventArgs {
18834 @@ -467,16 +474,16 @@ namespace Test.Rules.Naming {
18835 public void EnumName ()
18837 AssertRuleSuccess<ReturnValue> ();
18838 - AssertRuleFailureWithHighConfidence<ReturnValueEnum> ();
18839 - AssertRuleFailureWithHighConfidence<returnvalueenum> ();
18840 + AssertRuleFailureWithHighConfidence<ReturnValueEnum> (1);
18841 + AssertRuleFailureWithHighConfidence<returnvalueenum> (1);
18845 public void FlagsName ()
18847 AssertRuleSuccess<ReturnValues> ();
18848 - AssertRuleFailureWithHighConfidence<ReturnValuesFlags> ();
18849 - AssertRuleFailureWithHighConfidence<returnvaluesflags> ();
18850 + AssertRuleFailureWithHighConfidence<ReturnValuesFlags> (1);
18851 + AssertRuleFailureWithHighConfidence<returnvaluesflags> (1);
18855 diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18856 index 32cec08..6a6252b 100644
18857 --- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18858 +++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectCasingRule.cs
18862 using System.Collections.Generic;
18863 +using System.Globalization;
18867 @@ -96,7 +97,7 @@ namespace Gendarme.Rules.Naming {
18868 return name.ToUpperInvariant ();
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);
18875 // check if name is camelCased
18876 @@ -118,7 +119,7 @@ namespace Gendarme.Rules.Naming {
18877 return name.ToLowerInvariant ();
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);
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) {
18889 - ReportCasingError (nd, string.Format (
18890 + ReportCasingError (nd, String.Format (CultureInfo.InvariantCulture,
18891 "Use of single character namespace is discouraged. Rename namespace {0}", ns));
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);
18903 @@ -159,11 +161,13 @@ namespace Gendarme.Rules.Naming {
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);
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)));
18929 @@ -222,7 +226,8 @@ namespace Gendarme.Rules.Naming {
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);
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);
18949 diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18950 index 68de78a..03ff58c 100644
18951 --- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18952 +++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectPrefixRule.cs
18957 +using System.Globalization;
18960 using Gendarme.Framework;
18961 @@ -89,9 +90,9 @@ namespace Gendarme.Rules.Naming {
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]);
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.",
18982 Runner.Report (type, Severity.Critical, Confidence.High, s);
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.",
18991 Runner.Report (type, Severity.Medium, Confidence.High, s);
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.",
19001 Runner.Report (type, Severity.High, Confidence.High, s);
19004 diff --git a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19005 index cad641b..671d842 100644
19006 --- a/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19007 +++ b/gendarme/rules/Gendarme.Rules.Naming/UseCorrectSuffixRule.cs
19011 using System.Collections.Generic;
19012 +using System.Globalization;
19016 @@ -83,29 +84,30 @@ namespace Gendarme.Rules.Naming {
19017 public class UseCorrectSuffixRule : Rule, ITypeRule {
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>> ();
19023 static UseCorrectSuffixRule ()
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);
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'.");
19070 - static void Add (string suffix, string type, bool reserved)
19071 + static void Add (string suffix, string nameSpace, string name, bool reserved)
19074 - reservedSuffixes.Add (suffix, message => InheritsOrImplements (message, type));
19075 + reservedSuffixes.Add (suffix, message => InheritsOrImplements (message, nameSpace, name));
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);
19089 - static string InheritsOrImplements (TypeReference type, string subtype)
19090 + static string InheritsOrImplements (TypeReference type, string nameSpace, string name)
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);
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);
19102 static string CheckCollection (TypeReference type)
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;
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;
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 {
19121 static string CheckDictionary (TypeReference type)
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>.";
19128 @@ -168,16 +174,24 @@ namespace Gendarme.Rules.Naming {
19129 return "'EventHandler' should only be used for event handler delegates.";
19132 - // handle types using generics
19133 - private static string GetFullName (TypeReference type)
19134 + static bool TryGetCandidates (TypeReference type, out HashSet<string> candidates)
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);
19143 + name = name.Substring (0, pos);
19146 + if (definedSuffixes.TryGetValue (name, out candidates)) {
19148 + if (namespaces.TryGetValue (name, out nspace)) {
19149 + if (nspace == type.Namespace)
19154 + candidates = null;
19158 // checks if type name ends with an approriate suffix
19159 @@ -189,18 +203,15 @@ namespace Gendarme.Rules.Naming {
19160 currentTypeSuffix = false;
19162 while (current != null && current.BaseType != null) {
19163 - string base_name = GetFullName (current.BaseType);
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;
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);
19190 // inspect base type
19191 @@ -224,8 +236,11 @@ namespace Gendarme.Rules.Naming {
19193 private static string ComposeMessage (List<string> candidates)
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.",
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 {
19207 private List<string> proposedSuffixes = new List<string> ();
19209 + static bool HasSuffix (string typeName, string suffix)
19211 + if (suffix.Length > typeName.Length)
19215 + int gpos = typeName.LastIndexOf ('`');
19217 + gpos = typeName.Length;
19218 + else if (suffix.Length > gpos)
19221 + return (String.Compare (suffix, 0, typeName, gpos - suffix.Length, suffix.Length, StringComparison.OrdinalIgnoreCase) == 0);
19224 public RuleResult CheckType (TypeDefinition type)
19226 // rule does not apply to generated code (outside developer's control)
19227 @@ -247,15 +277,19 @@ namespace Gendarme.Rules.Naming {
19229 // ok, rule applies
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;
19246 + Runner.Report (type, Severity.Medium, Confidence.High, msg);
19250 diff --git a/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs b/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19251 index 59ede41..d2367c5 100644
19252 --- a/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19253 +++ b/gendarme/rules/Gendarme.Rules.Naming/UsePreferredTermsRule.cs
19257 using System.Collections.Generic;
19258 +using System.Globalization;
19262 @@ -140,7 +141,7 @@ namespace Gendarme.Rules.Naming {
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);
19271 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19272 index e753a0d..44ba1e6 100644
19273 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19274 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidConcatenatingCharsRule.cs
19279 +using System.Globalization;
19282 using Mono.Cecil.Cil;
19283 @@ -74,26 +75,20 @@ namespace Gendarme.Rules.Performance {
19284 [EngineDependency (typeof (OpCodeEngine))]
19285 public class AvoidConcatenatingCharsRule : Rule, IMethodRule {
19287 - static bool IsStringConcat (MemberReference member)
19289 - if (member == null || (member.Name != "Concat"))
19292 - return (member.DeclaringType.FullName == "System.String");
19295 static bool HasReferenceToStringConcatObject (ModuleDefinition module)
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)
19304 - switch (method.Parameters [0].ParameterType.FullName) {
19305 - case "System.Object":
19306 - case "System.Object[]":
19309 + TypeReference ptype = method.Parameters [0].ParameterType;
19310 + switch (ptype.Name) {
19313 + return (ptype.Namespace == "System");
19317 @@ -113,7 +108,8 @@ namespace Gendarme.Rules.Performance {
19319 private void ReportBoxing (MethodDefinition method, Instruction ins, Confidence confidence)
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);
19327 @@ -159,14 +155,18 @@ namespace Gendarme.Rules.Performance {
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"))
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
19341 + switch (ptype.Name) {
19343 CheckParameters (mr, method, ins);
19345 - case "System.Object[]":
19347 if ((ins.Previous.OpCode.Code == Code.Stelem_Ref) || ins.Previous.IsLoadLocal ())
19348 ScanArray (method, ins.Previous);
19350 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19351 index a1bd50f..698867c 100644
19352 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19353 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeNumberOfLocalVariablesRule.cs
19357 using System.ComponentModel;
19358 +using System.Globalization;
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;
19371 @@ -78,7 +79,8 @@ namespace Gendarme.Rules.Performance {
19372 if (num <= MaximumVariables)
19373 return RuleResult.Success;
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;
19381 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19382 index 99ecb4f..2ce5e3f 100644
19383 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19384 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidLargeStructureRule.cs
19387 using System.Collections.Generic;
19388 using System.ComponentModel;
19389 +using System.Globalization;
19393 @@ -75,20 +76,20 @@ namespace Gendarme.Rules.Performance {
19394 private const int ReferenceSize = 4;
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
19413 + { "Boolean", 1 },
19423 + { "IntPtr", ReferenceSize }, // so rule return the same results
19424 + { "UIntPtr", ReferenceSize }, // on 32 and 64 bits architectures
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") {
19432 - if (Primitives.TryGetValue (type.FullName, out size))
19433 + if (Primitives.TryGetValue (type.Name, out size))
19434 return (long) size;
19437 @@ -216,7 +217,7 @@ namespace Gendarme.Rules.Performance {
19438 else if (size > medium_severity_limit)
19439 severity = Severity.Medium;
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;
19446 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidLocalDataStoreSlotRule.cs
19447 index 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 {
19454 - private const string LocalDataStoreSlot = "System.LocalDataStoreSlot";
19456 public override void Initialize (IRunner runner)
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");
19470 @@ -119,9 +119,18 @@ namespace Gendarme.Rules.Performance {
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":
19486 + switch (type.Name) {
19492 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19493 index 5fbc09d..576e211 100644
19494 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19495 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidMethodWithLargeMaximumStackSizeRule.cs
19500 +using System.Globalization;
19503 using Mono.Cecil.Cil;
19504 @@ -64,7 +65,8 @@ namespace Gendarme.Rules.Performance {
19505 if (num <= MaximumStackSize)
19506 return RuleResult.Success;
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;
19514 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19515 index a470e55..7e1bc64 100644
19516 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19517 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCallsToPropertiesRule.cs
19520 using System.Collections.Generic;
19521 using System.ComponentModel;
19522 +using System.Globalization;
19526 @@ -107,14 +108,19 @@ namespace Gendarme.Rules.Performance {
19527 static string GetKey (MethodDefinition caller, MethodDefinition callee, Instruction ins)
19529 if (callee.IsStatic)
19530 - return callee.ToString ();
19531 + return callee.GetFullName ();
19533 IMetadataTokenProvider chain = callee;
19534 Instruction instance = ins.TraceBack (caller);
19536 StringBuilder sb = new StringBuilder ();
19537 while (instance != null) {
19538 - sb.Append (chain.ToString () ?? "null").Append ('.');
19539 + MemberReference mr = (chain as MemberReference);
19541 + sb.Append (chain.ToString ()); // ?? "null")
19543 + sb.Append (mr.GetFullName ());
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 {
19550 static bool Filter (MethodDefinition method)
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"))
19559 - case "System.DateTime":
19560 + else if (type.IsNamed ("System", "DateTime"))
19561 return method.IsStatic;
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);
19588 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19589 index 5680c14..5a4a10e 100644
19590 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19591 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidRepetitiveCastsRule.cs
19595 using System.Collections.Generic;
19596 +using System.Globalization;
19599 using Mono.Cecil.Cil;
19600 @@ -237,7 +238,7 @@ namespace Gendarme.Rules.Performance {
19604 - private int FindDuplicates (MethodDefinition method, string type, Instruction origin)
19605 + private int FindDuplicates (MethodDefinition method, TypeReference type, Instruction origin)
19607 // we already had our first cast if we got here
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))
19616 if (!OriginsMatch(method, origin, GetOrigin (ins)))
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);
19626 int count = FindDuplicates (method, type, origin);
19627 @@ -296,7 +297,8 @@ namespace Gendarme.Rules.Performance {
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);
19636 casts.RemoveAt (0);
19637 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19638 index 23da450..e2d9ed1 100644
19639 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19640 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidTypeGetTypeForConstantStringsRule.cs
19645 +using System.Globalization;
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;
19655 namespace Gendarme.Rules.Performance {
19657 @@ -84,9 +86,9 @@ namespace Gendarme.Rules.Performance {
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)
19664 - if (mr.DeclaringType.FullName != "System.Type")
19665 + if (!mr.IsNamed ("System", "Type", "GetType"))
19668 if (ins.Previous.OpCode.Code != Code.Ldstr)
19669 @@ -100,7 +102,8 @@ namespace Gendarme.Rules.Performance {
19670 if (type_name == "Mono.Runtime")
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);
19678 return Runner.CurrentRuleResult;
19679 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUncalledPrivateCodeRule.cs
19680 index 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 {
19687 - static string [] SpecialAttributes = new string[] {
19688 - "System.Runtime.InteropServices.ComRegisterFunctionAttribute",
19689 - "System.Runtime.InteropServices.ComUnregisterFunctionAttribute",
19690 - "System.Diagnostics.ConditionalAttribute"
19692 + static bool HasAnySpecialAttribute (ICustomAttributeProvider method)
19694 + if (!method.HasCustomAttributes)
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"))) {
19708 static private bool Applicable (MethodDefinition method)
19710 @@ -119,10 +129,8 @@ namespace Gendarme.Rules.Performance {
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))
19718 + if (HasAnySpecialAttribute (method))
19723 @@ -301,7 +309,7 @@ namespace Gendarme.Rules.Performance {
19727 - private static void BuildMethodUsage (HashSet<ulong> methods, MethodDefinition method)
19728 + private static void BuildMethodUsage (ISet<ulong> methods, MethodDefinition method)
19730 foreach (Instruction ins in method.Body.Instructions) {
19731 MethodReference mr = (ins.Operand as MethodReference);
19732 @@ -310,7 +318,7 @@ namespace Gendarme.Rules.Performance {
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 ();
19741 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUninstantiatedInternalClassesRule.cs
19742 index 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);
19749 - static void AddType (HashSet<TypeReference> typeset, TypeReference type)
19750 + static void AddType (ISet<TypeReference> typeset, TypeReference type)
19752 // we're interested in the array element type, not the array itself
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;
19763 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnnecessaryOverridesRule.cs
19764 index 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))
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))
19778 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19779 index 212892a..08a051b 100644
19780 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19781 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededCallsOnStringRule.cs
19786 +using System.Globalization;
19789 using Mono.Cecil.Cil;
19790 @@ -126,15 +127,15 @@ namespace Gendarme.Rules.Performance {
19791 if (call.HasParameters)
19792 return String.Empty;
19794 - if (!IsSystemString (ins.Previous.GetOperandType (method)))
19795 + if (!ins.Previous.GetOperandType (method).IsNamed ("System", "String"))
19796 return String.Empty;
19798 - return String.Format (MessageString, call.Name, String.Empty);
19799 + return String.Format (CultureInfo.InvariantCulture, MessageString, call.Name, String.Empty);
19802 private static string CheckSubstring (MethodReference call, Instruction ins)
19804 - if (!IsSystemString (call.DeclaringType))
19805 + if (!call.DeclaringType.IsNamed ("System", "String"))
19806 return String.Empty;
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;
19813 - return String.Format (MessageString, call.Name, "0");
19814 + return String.Format (CultureInfo.InvariantCulture, MessageString, call.Name, "0");
19817 private static string CheckToString (MethodReference call, Instruction ins, MethodDefinition method)
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);
19826 // signature for Clone is identical (well close enough) to share code
19827 return CheckClone (call, ins, method);
19831 - private static bool IsSystemString (MemberReference type)
19833 - return (type == null) ? false : (type.FullName == "System.String");
19837 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19838 index 06bbc3b..1b5e6d7 100644
19839 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19840 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnneededUnboxingRule.cs
19844 using System.Collections.Generic;
19845 +using System.Globalization;
19848 using Mono.Cecil.Cil;
19849 @@ -95,7 +96,6 @@ namespace Gendarme.Rules.Performance {
19850 private static string Previous (MethodDefinition method, Instruction ins)
19853 - string type = (ins.Operand as TypeReference).FullName;
19855 ins = ins.Previous;
19856 Code previous_op_code = ins.OpCode.Code;
19857 @@ -139,7 +139,8 @@ namespace Gendarme.Rules.Performance {
19859 return String.Empty;
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 ());
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
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);
19876 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnsealedUninheritedInternalClassesRule.cs
19877 index 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;
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 ()) {
19889 - if (type_definition.FullName == type_name)
19890 + if (type_definition.IsNamed (nspace, name))
19892 - if (type_definition.Inherits (type_name))
19893 + if (type_definition.Inherits (nspace, name))
19894 return RuleResult.Success;
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;
19902 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19903 index 75a6448..8df328f 100644
19904 --- a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19905 +++ b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedParametersRule.cs
19909 using System.Collections.Generic;
19910 +using System.Globalization;
19913 using Mono.Cecil.Cil;
19914 @@ -132,10 +133,8 @@ namespace Gendarme.Rules.Performance {
19915 return RuleResult.DoesNotApply;
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;
19922 + if (method.HasAttribute ("System.Diagnostics", "ConditionalAttribute"))
19923 + return RuleResult.DoesNotApply;
19927 @@ -151,7 +150,7 @@ namespace Gendarme.Rules.Performance {
19928 ParameterDefinition parameter = ins.GetParameter (method);
19929 if (parameter == null)
19931 - mask |= ((ulong)1 << (parameter.GetSequence () - 1));
19932 + mask |= ((ulong)1 << parameter.Index);
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);
19946 diff --git a/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/AvoidUnusedPrivateFieldsRule.cs
19947 index 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
19953 foreach (FieldDefinition field in type.Fields) {
19954 - if (!field.IsPrivate || field.IsLiteral)
19955 + if (!field.IsPrivate || field.IsLiteral || field.IsGeneratedCode ())
19958 fields.Add (field);
19961 // scan all methods, including constructors, to find if the field is used
19962 + if (fields.Count > 0) {
19963 + CheckFieldsUsageInType (type);
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);
19971 + // check remaining (private) fields in the set
19972 + foreach (FieldDefinition field in fields) {
19973 + Runner.Report (field, Severity.Medium, Confidence.Normal);
19976 + return Runner.CurrentRuleResult;
19979 + private void CheckFieldsUsageInType (TypeDefinition type)
19981 foreach (MethodDefinition method in type.Methods) {
19982 if (!method.HasBody)
19984 @@ -127,14 +146,12 @@ namespace Gendarme.Rules.Performance {
19986 fields.Remove (fd);
19989 + if (fields.Count == 0)
19993 - // check remaining (private) fields in the set
19994 - foreach (FieldDefinition field in fields) {
19995 - Runner.Report (field, Severity.Medium, Confidence.Normal);
19997 - return Runner.CurrentRuleResult;
20001 public void Bitmask ()
20003 diff --git a/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs b/gendarme/rules/Gendarme.Rules.Performance/CompareWithStringEmptyEfficientlyRule.cs
20004 index 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 {
20009 if (mref.Parameters.Count > 1)
20011 - string tname = mref.DeclaringType.FullName;
20012 - if ((tname != "System.String") && (tname != "System.Object"))
20013 + TypeReference type = mref.DeclaringType;
20014 + if (type.Namespace != "System")
20016 + string name = type.Name;
20017 + if ((name != "String") && (name != "Object"))
20020 case "op_Equality":
20021 case "op_Inequality":
20022 - if (mref.DeclaringType.FullName != "System.String")
20023 + if (!mref.DeclaringType.IsNamed ("System", "String"))
20027 @@ -115,7 +118,7 @@ namespace Gendarme.Rules.Performance {
20030 FieldReference field = (prev.Operand as FieldReference);
20031 - if (field.DeclaringType.FullName != "System.String")
20032 + if (!field.DeclaringType.IsNamed ("System", "String"))
20034 // unlikely to be anything else (at least with released fx)
20035 if (field.Name != "Empty")
20036 diff --git a/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs b/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20037 index aadb867..fbd1931 100644
20038 --- a/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20039 +++ b/gendarme/rules/Gendarme.Rules.Performance/DontIgnoreMethodResultRule.cs
20044 +using System.Globalization;
20047 using Mono.Cecil.Cil;
20048 @@ -99,17 +100,17 @@ namespace Gendarme.Rules.Performance {
20050 private static bool IsCallException (MethodReference method)
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");
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 {
20071 private static bool IsNewException (MemberReference method)
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)":
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);
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);
20098 diff --git a/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs b/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20099 index a6b3bb3..4971448 100644
20100 --- a/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20101 +++ b/gendarme/rules/Gendarme.Rules.Performance/EmptyDestructorRule.cs
20106 +using System.Globalization;
20109 using Mono.Cecil.Cil;
20110 @@ -131,7 +132,8 @@ namespace Gendarme.Rules.Performance {
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;
20120 diff --git a/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj b/gendarme/rules/Gendarme.Rules.Performance/Gendarme.Rules.Performance.csproj
20121 index 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
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
20129 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
20130 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
20154 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
20155 <DebugSymbols>true</DebugSymbols>
\r
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
20162 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
20163 <DebugType>pdbonly</DebugType>
\r
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
20171 <Reference Include="System" />
\r
20172 @@ -117,14 +120,33 @@
20173 <None Include="ChangeLog" />
\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
20185 + <Install>false</Install>
\r
20186 </BootstrapperPackage>
\r
20187 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
20188 <Visible>False</Visible>
\r
20191 + <Install>false</Install>
\r
20192 </BootstrapperPackage>
\r
20193 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
20194 <Visible>False</Visible>
\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
20205 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
20206 diff --git a/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/IDisposableWithDestructorWithoutSuppressFinalizeRule.cs
20207 index 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")) {
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;
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;
20227 // and provide a finalizer
20228 diff --git a/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs b/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20229 index 528a7cf..76240b4 100644
20230 --- a/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20231 +++ b/gendarme/rules/Gendarme.Rules.Performance/ImplementEqualsTypeRule.cs
20236 +using System.Globalization;
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>");
20248 return Runner.CurrentRuleResult;
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;
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;
20264 diff --git a/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs b/gendarme/rules/Gendarme.Rules.Performance/MathMinMaxCandidateRule.cs
20265 index 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)
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")
20286 + // GetElementType will remove the '&' for references
20287 + TypeReference tr = type.GetElementType ();
20288 + switch (tr.Name) {
20302 diff --git a/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20303 index 5ab9c1c..169ced5 100644
20304 --- a/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20305 +++ b/gendarme/rules/Gendarme.Rules.Performance/OverrideValueTypeDefaultsRule.cs
20310 +using System.Globalization;
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);
20323 diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20324 index a81b773..84c84aa 100644
20325 --- a/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20326 +++ b/gendarme/rules/Gendarme.Rules.Performance/PreferCharOverloadRule.cs
20330 using System.Collections.Generic;
20331 +using System.Globalization;
20334 using Mono.Cecil.Cil;
20335 @@ -93,7 +94,8 @@ namespace Gendarme.Rules.Performance {
20337 void Report (MethodDefinition method, Instruction ins, Confidence confidence, MemberReference call, string parameter)
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);
20345 @@ -106,7 +108,7 @@ namespace Gendarme.Rules.Performance {
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)
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);
20365 static bool CheckFirstParameterIsString (IMethodSignature method)
20367 - return (method.HasParameters && (method.Parameters [0].ParameterType.FullName == "System.String"));
20368 + return (method.HasParameters && method.Parameters [0].ParameterType.IsNamed ("System", "String"));
20371 public RuleResult CheckMethod (MethodDefinition method)
20372 @@ -165,7 +168,7 @@ namespace Gendarme.Rules.Performance {
20375 MethodReference call = (ins.Operand as MethodReference);
20376 - if (call.DeclaringType.FullName != "System.String")
20377 + if (!call.DeclaringType.IsNamed ("System", "String"))
20380 switch (call.Name) {
20381 diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20382 index 2567025..6dac441 100644
20383 --- a/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20384 +++ b/gendarme/rules/Gendarme.Rules.Performance/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule.cs
20388 using System.Collections.Generic;
20389 +using System.Globalization;
20391 using Gendarme.Framework;
20392 +using Gendarme.Framework.Rocks;
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 {
20400 - private readonly HashSet<string> primitiveTypeInterfaces = new HashSet<string> ();
20401 + static bool CheckGenericArgument (GenericInstanceType git)
20403 + if ((git == null) || !git.HasGenericArguments)
20404 + return false; // should not happen with the '`1' but...
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:
20430 - public PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceRule ()
20431 + static bool IsPrimitiveInterface (MemberReference type)
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);
20478 public RuleResult CheckMethod (MethodDefinition method)
20479 @@ -108,10 +119,10 @@ namespace Gendarme.Rules.Performance {
20480 if (type.Namespace != "System")
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",
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);
20494 diff --git a/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Performance/PreferLiteralOverInitOnlyFieldsRule.cs
20495 index 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);
20507 diff --git a/gendarme/rules/Gendarme.Rules.Performance/README.md b/gendarme/rules/Gendarme.Rules.Performance/README.md
20508 new file mode 100644
20509 index 0000000..5ef5f3b
20511 +++ b/gendarme/rules/Gendarme.Rules.Performance/README.md
20513 +# Gendarme.Rules.Performance Rules
20515 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Performance(git)]] pages.
20520 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
20522 diff --git a/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20523 index bf1cda5..ac4ece9 100644
20524 --- a/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20525 +++ b/gendarme/rules/Gendarme.Rules.Performance/RemoveUnusedLocalVariablesRule.cs
20529 using System.Collections;
20530 +using System.Globalization;
20533 using Mono.Cecil.Cil;
20534 @@ -132,8 +133,8 @@ namespace Gendarme.Rules.Performance {
20535 if (variable.IsGeneratedName ())
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);
20545 diff --git a/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs b/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20546 index 0bef7c2..095c240 100644
20547 --- a/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20548 +++ b/gendarme/rules/Gendarme.Rules.Performance/ReviewLinqMethodRule.cs
20552 using System.Collections.Generic;
20553 +using System.Globalization;
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 {
20561 - private const string EnumerableName = "System.Linq.Enumerable";
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);
20568 @@ -181,14 +178,16 @@ namespace Gendarme.Rules.Performance {
20569 private void CheckForSubscript (TypeReference type, MethodDefinition method, Instruction ins, string name)
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);
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);
20587 @@ -198,14 +197,16 @@ namespace Gendarme.Rules.Performance {
20588 private void CheckForSort (TypeReference type, MethodDefinition method, Instruction ins, string name)
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);
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);
20606 @@ -251,7 +252,7 @@ namespace Gendarme.Rules.Performance {
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"))
20614 string tname = target.Name;
20615 diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidRepetitiveCallsToPropertiesTest.cs
20616 index 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))
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))
20630 diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/AvoidUnusedPrivateFieldsTest.cs
20631 index 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>> ();
20639 + class FieldsUsedInNested {
20640 + private bool field;
20642 + private static string staticField;
20645 + public void Foo (FieldsUsedInNested parent)
20647 + FieldsUsedInNested.staticField = "bar";
20648 + parent.field = true;
20654 + public void FieldsUsedInNestedType ()
20656 + AssertRuleSuccess<FieldsUsedInNested> ();
20659 + class CompilerGenerated {
20660 + public string Name { get; set; }
20664 + public void ClassWithCompilerGeneratedFields ()
20666 + AssertRuleSuccess<CompilerGenerated> ();
20669 + class CompilerGeneratedAndUnused {
20670 + private int number;
20671 + public string Name { get; set; }
20675 + public void ClassWithCompilerGeneratedFieldsAndUnusedPrivate ()
20677 + AssertRuleFailure<CompilerGeneratedAndUnused> (1);
20681 diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs b/gendarme/rules/Gendarme.Rules.Performance/Test/PreferInterfaceConstraintOnGenericParameterForPrimitiveInterfaceTest.cs
20682 index 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 {
20689 - private void MethodWithGenericInterfaceOfBaseTypeParameter2 (IComparable<int> comparable)
20690 + private void MethodWithGenericInterfaceOfBaseTypeParameter2a (IComparable<int> comparable)
20695 + private void MethodWithGenericInterfaceOfBaseTypeParameter2b (IComparable<decimal> comparable)
20700 + private void MethodWithGenericInterfaceOfBaseTypeParameter2c (IComparable<object> comparable)
20704 @@ -101,25 +111,27 @@ namespace Tests.Rules.Performance {
20706 public void MethodWithInterfaceOfBaseTypeParameter ()
20708 - AssertRuleFailure<TestCase> ("MethodWithInterfaceOfBaseTypeParameter");
20709 + AssertRuleFailure<TestCase> ("MethodWithInterfaceOfBaseTypeParameter", 1);
20713 public void MethodWithGenericInterfaceOfBaseTypeParameter ()
20715 - AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter");
20716 + AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter", 1);
20720 public void MethodWithGenericInterfaceOfBaseTypeParameter2 ()
20722 - AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2");
20723 + AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2a", 1);
20724 + AssertRuleFailure<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2b", 1);
20725 + AssertRuleSuccess<TestCase> ("MethodWithGenericInterfaceOfBaseTypeParameter2c");
20729 public void MethodWithMultipleParameters ()
20731 - AssertRuleFailure<TestCase> ("MethodWithMultipleParameters");
20732 + AssertRuleFailure<TestCase> ("MethodWithMultipleParameters", 1);
20736 diff --git a/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj b/gendarme/rules/Gendarme.Rules.Performance/Test/Tests.Rules.Performance.csproj
20737 index 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
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
20745 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
20746 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
20770 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
20771 <DebugSymbols>true</DebugSymbols>
\r
20773 <ErrorReport>prompt</ErrorReport>
\r
20774 <WarningLevel>4</WarningLevel>
\r
20775 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
\r
20776 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
20778 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
20779 <DebugType>pdbonly</DebugType>
\r
20781 <ErrorReport>prompt</ErrorReport>
\r
20782 <WarningLevel>4</WarningLevel>
\r
20783 <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
\r
20784 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\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
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
20801 + <Install>false</Install>
\r
20802 </BootstrapperPackage>
\r
20803 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
20804 <Visible>False</Visible>
\r
20807 + <Install>false</Install>
\r
20808 </BootstrapperPackage>
\r
20809 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
20810 <Visible>False</Visible>
\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
20821 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
20822 diff --git a/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs b/gendarme/rules/Gendarme.Rules.Performance/UseTypeEmptyTypesRule.cs
20823 index 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)
20830 - var type = (TypeReference) ins.Operand;
20832 - if (type.FullName != "System.Type")
20833 + if (!(ins.Operand as TypeReference).IsNamed ("System", "Type"))
20836 if (ins.Previous.IsOperandZero ())
20837 diff --git a/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs b/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20838 index 009ebba..92b597a 100644
20839 --- a/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20840 +++ b/gendarme/rules/Gendarme.Rules.Portability/DoNotHardcodePathsRule.cs
20844 using System.Collections.Generic;
20845 +using System.Globalization;
20848 using Mono.Cecil.Cil;
20849 @@ -363,11 +364,13 @@ namespace Gendarme.Rules.Portability {
20851 // we can avoid some false positives by doing additional checks here
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;
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))) {
20865 return true; // handled
20866 @@ -389,10 +392,8 @@ namespace Gendarme.Rules.Portability {
20868 // this is a constructor call
20869 MethodReference ctor = (MethodReference) ins.Operand;
20870 - string createdTypeName = ctor.DeclaringType.FullName;
20872 // avoid catching regular expressions
20873 - if (createdTypeName == "System.Text.RegularExpressions.Regex")
20874 + if (ctor.DeclaringType.IsNamed ("System.Text.RegularExpressions", "Regex"))
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);
20888 diff --git a/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs b/gendarme/rules/Gendarme.Rules.Portability/ExitCodeIsLimitedOnUnixRule.cs
20889 index 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");
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;
20911 Instruction previous = null;
20912 @@ -188,7 +190,7 @@ namespace Gendarme.Rules.Portability {
20913 return (a >= 0 && a <= 255) ? InspectionResult.Good : InspectionResult.Bad;
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;
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"))
20925 - if (calledMethod.DeclaringType.FullName != "System.Environment")
20926 + if (!calledMethod.DeclaringType.IsNamed ("System", "Environment"))
20929 InspectionResult result = CheckInstruction (previous);
20930 diff --git a/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs b/gendarme/rules/Gendarme.Rules.Portability/FeatureRequiresRootPrivilegeOnUnixRule.cs
20931 index 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.";
20938 - // non-localizable
20939 - private const string Ping = "System.Net.NetworkInformation.Ping";
20940 - private const string Process = "System.Diagnostics.Process";
20942 private bool ping_present = true;
20943 private bool process_present = true;
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);
20957 + // activate the rule if any (or both) is/are present(s)
20958 Active = (ping_present || process_present);
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"))
20965 - if (method.DeclaringType.FullName != "System.Diagnostics.Process")
20966 + if (!method.DeclaringType.IsNamed ("System.Diagnostics", "Process"))
20969 Instruction prev = ins.Previous; //check stack
20970 @@ -132,7 +133,7 @@ namespace Gendarme.Rules.Portability {
20971 private static bool CheckPing (Instruction ins)
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")));
20978 public RuleResult CheckMethod (MethodDefinition method)
20979 diff --git a/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj b/gendarme/rules/Gendarme.Rules.Portability/Gendarme.Rules.Portability.csproj
20980 index 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
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
20988 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
20989 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
21013 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21014 <DebugSymbols>true</DebugSymbols>
\r
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
21021 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21022 <DebugType>pdbonly</DebugType>
\r
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
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
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
21044 + <Install>false</Install>
\r
21045 </BootstrapperPackage>
\r
21046 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
21047 <Visible>False</Visible>
\r
21050 + <Install>false</Install>
\r
21051 </BootstrapperPackage>
\r
21052 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
21053 <Visible>False</Visible>
\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
21064 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
21065 diff --git a/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs b/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21066 index 141323f..e3a5d3b 100644
21067 --- a/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21068 +++ b/gendarme/rules/Gendarme.Rules.Portability/MonoCompatibilityReviewRule.cs
21070 // Sebastien Pouliot <sebastien@ximian.com>
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)
21076 // Permission is hereby granted, free of charge, to any person obtaining
21077 // a copy of this software and associated documentation files (the
21080 using System.Collections.Generic;
21081 using System.ComponentModel;
21082 +using System.Globalization;
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;
21092 using ICSharpCode.SharpZipLib.Zip;
21094 @@ -126,7 +128,7 @@ namespace Gendarme.Rules.Portability {
21096 private string GetFileName (Version v)
21098 - return Path.Combine (DefinitionsFolder, String.Format ("definitions-{0}.zip", v));
21099 + return Path.Combine (DefinitionsFolder, String.Format (CultureInfo.InvariantCulture, "definitions-{0}.zip", v));
21102 private Version FindLastestLocalVersion ()
21103 @@ -139,7 +141,7 @@ namespace Gendarme.Rules.Portability {
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
21111 catch (FormatException) {
21112 @@ -175,7 +177,7 @@ namespace Gendarme.Rules.Portability {
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)) {
21119 while ((ze = zs.GetNextEntry ()) != null) {
21121 @@ -291,29 +293,28 @@ namespace Gendarme.Rules.Portability {
21125 - private static Dictionary<string, string> ReadWithComments (TextReader reader)
21126 + static char [] buffer = new char [4096];
21128 + private static Dictionary<string, string> ReadWithComments (StreamLineReader reader)
21130 Dictionary<string, string> dict = new Dictionary<string, string> ();
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);
21139 - dict.Add (target, line.Substring (split + 1));
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);
21152 - private static HashSet<string> Read (TextReader reader)
21153 + private static HashSet<string> Read (StreamLineReader reader)
21155 HashSet<string> set = new HashSet<string> ();
21157 - while ((line = reader.ReadLine ()) != null) {
21159 + while (!reader.EndOfStream) {
21160 + int length = reader.ReadLine (buffer, 0, buffer.Length);
21161 + set.Add (new string (buffer, 0, length));
21165 @@ -344,18 +345,18 @@ namespace Gendarme.Rules.Portability {
21168 // MethodReference.ToString is costly so we do it once for the three checks
21169 - string callee = mr.ToString ();
21170 + string callee = mr.GetFullName ();
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);
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);
21187 @@ -363,7 +364,7 @@ namespace Gendarme.Rules.Portability {
21188 if (ToDo != null) {
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);
21196 diff --git a/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs b/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21197 index 40345c9..1e3afa3 100644
21198 --- a/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21199 +++ b/gendarme/rules/Gendarme.Rules.Portability/NewLineLiteralRule.cs
21204 +using System.Globalization;
21208 @@ -115,7 +116,7 @@ namespace Gendarme.Rules.Portability {
21209 else if (c == '\t')
21210 result.Append ("\\t");
21212 - result.AppendFormat ("\\x").Append (((short) c).ToString ("x"));
21213 + result.Append ("\\x").Append (((short) c).ToString ("x", CultureInfo.InvariantCulture));
21215 return result.Append ("\".").ToString ();
21217 diff --git a/gendarme/rules/Gendarme.Rules.Portability/README.md b/gendarme/rules/Gendarme.Rules.Portability/README.md
21218 new file mode 100644
21219 index 0000000..ffe7609
21221 +++ b/gendarme/rules/Gendarme.Rules.Portability/README.md
21223 +# Gendarme.Rules.Portability Rules
21225 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Portability(git)]] pages.
21230 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21232 diff --git a/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj b/gendarme/rules/Gendarme.Rules.Portability/Test/Tests.Rules.Portability.csproj
21233 index 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
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
21241 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21242 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
21266 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21267 <DebugSymbols>true</DebugSymbols>
\r
21269 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
21270 <ErrorReport>prompt</ErrorReport>
\r
21271 <WarningLevel>4</WarningLevel>
\r
21272 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
21274 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21275 <DebugType>pdbonly</DebugType>
\r
21277 <DefineConstants>TRACE</DefineConstants>
\r
21278 <ErrorReport>prompt</ErrorReport>
\r
21279 <WarningLevel>4</WarningLevel>
\r
21280 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\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
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
21297 + <Install>false</Install>
\r
21298 </BootstrapperPackage>
\r
21299 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
21300 <Visible>False</Visible>
\r
21303 + <Install>false</Install>
\r
21304 </BootstrapperPackage>
\r
21305 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
21306 <Visible>False</Visible>
\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
21317 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
21318 diff --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
21319 index 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
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
21327 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21328 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
21357 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21358 <DebugSymbols>true</DebugSymbols>
\r
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
21365 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21366 <DebugType>pdbonly</DebugType>
\r
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
21374 <Reference Include="System" />
\r
21376 <Name>Gendarme.Framework</Name>
\r
21377 </ProjectReference>
\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
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.
21399 diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/README.md b/gendarme/rules/Gendarme.Rules.Security.Cas/README.md
21400 new file mode 100644
21401 index 0000000..7fb8880
21403 +++ b/gendarme/rules/Gendarme.Rules.Security.Cas/README.md
21405 +# Gendarme.Rules.Security.Cas Rules
21407 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security.Cas(git)]] pages.
21412 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21414 diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/ReviewSuppressUnmanagedCodeSecurityUsageRule.cs
21415 index 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 {
21422 - private const string SUCS = "System.Security.SuppressUnmanagedCodeSecurityAttribute";
21424 public override void Initialize (IRunner runner)
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");
21440 @@ -78,7 +78,7 @@ namespace Gendarme.Rules.Security.Cas {
21442 return RuleResult.DoesNotApply;
21444 - if (!type.HasAttribute (SUCS))
21445 + if (!type.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute"))
21446 return RuleResult.Success;
21448 Runner.Report (type, Severity.Audit, Confidence.Total);
21449 @@ -87,7 +87,7 @@ namespace Gendarme.Rules.Security.Cas {
21451 public RuleResult CheckMethod (MethodDefinition method)
21453 - if (!method.HasAttribute (SUCS))
21454 + if (!method.HasAttribute ("System.Security", "SuppressUnmanagedCodeSecurityAttribute"))
21455 return RuleResult.Success;
21457 Runner.Report (method, Severity.Audit, Confidence.Total);
21458 diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21459 index 481e95e..79831bd 100644
21460 --- a/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21461 +++ b/gendarme/rules/Gendarme.Rules.Security.Cas/SecureGetObjectDataOverridesRule.cs
21466 +using System.Globalization;
21467 using System.Security;
21468 using System.Security.Permissions;
21470 @@ -87,7 +88,7 @@ namespace Gendarme.Rules.Security.Cas {
21471 public RuleResult CheckType (TypeDefinition type)
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;
21478 MethodDefinition method = type.GetMethod (MethodSignatures.GetObjectData);
21479 @@ -112,7 +113,8 @@ namespace Gendarme.Rules.Security.Cas {
21480 case Mono.Cecil.SecurityAction.NonCasLinkDemand:
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);
21489 diff --git a/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs b/gendarme/rules/Gendarme.Rules.Security.Cas/SecurityDeclarationRocks.cs
21490 index 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;
21497 +using Gendarme.Framework.Rocks;
21499 namespace Gendarme.Rules.Security.Cas {
21501 diff --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
21502 index 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
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
21510 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21511 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
21540 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21541 <DebugSymbols>true</DebugSymbols>
\r
21543 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
21544 <ErrorReport>prompt</ErrorReport>
\r
21545 <WarningLevel>4</WarningLevel>
\r
21546 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
21548 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21549 <DebugType>pdbonly</DebugType>
\r
21551 <DefineConstants>TRACE</DefineConstants>
\r
21552 <ErrorReport>prompt</ErrorReport>
\r
21553 <WarningLevel>4</WarningLevel>
\r
21554 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
21557 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
21560 <Folder Include="Properties\" />
\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
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.
21582 diff --git a/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs b/gendarme/rules/Gendarme.Rules.Security/DoNotShortCircuitCertificateCheckRule.cs
21583 index 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");
21600 @@ -138,11 +141,11 @@ namespace Gendarme.Rules.Security {
21604 - switch (pd.GetSequence ()) {
21607 - return RuleResult.Success;
21608 + switch (pd.Index) {
21611 + return RuleResult.Success;
21614 return RuleResult.Success;
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 {
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;
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]))
21643 - if (callback && (name != RemoteCertificateValidationParameters [i]))
21644 + if (callback && !ptype.IsNamed (RemoteCertificateValidationParameters [i]))
21648 diff --git a/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj b/gendarme/rules/Gendarme.Rules.Security/Gendarme.Rules.Security.csproj
21649 index 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
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
21657 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21658 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
21682 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21683 <DebugSymbols>true</DebugSymbols>
\r
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
21690 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21691 <DebugType>pdbonly</DebugType>
\r
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
21699 <Reference Include="System" />
\r
21700 @@ -84,14 +87,33 @@
21701 <None Include="ChangeLog" />
\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
21713 + <Install>false</Install>
\r
21714 </BootstrapperPackage>
\r
21715 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
21716 <Visible>False</Visible>
\r
21719 + <Install>false</Install>
\r
21720 </BootstrapperPackage>
\r
21721 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
21722 <Visible>False</Visible>
\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
21733 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
21734 diff --git a/gendarme/rules/Gendarme.Rules.Security/README.md b/gendarme/rules/Gendarme.Rules.Security/README.md
21735 new file mode 100644
21736 index 0000000..d0b7430
21738 +++ b/gendarme/rules/Gendarme.Rules.Security/README.md
21740 +# Gendarme.Rules.Security Rules
21742 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Security(git)]] pages.
21747 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
21749 diff --git a/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj b/gendarme/rules/Gendarme.Rules.Security/Test/Tests.Rules.Security.csproj
21750 index 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
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
21758 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21759 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
21783 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21784 <DebugSymbols>true</DebugSymbols>
\r
21786 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
21787 <ErrorReport>prompt</ErrorReport>
\r
21788 <WarningLevel>4</WarningLevel>
\r
21789 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
21791 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21792 <DebugType>pdbonly</DebugType>
\r
21794 <DefineConstants>TRACE</DefineConstants>
\r
21795 <ErrorReport>prompt</ErrorReport>
\r
21796 <WarningLevel>4</WarningLevel>
\r
21797 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\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
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
21814 + <Install>false</Install>
\r
21815 </BootstrapperPackage>
\r
21816 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
21817 <Visible>False</Visible>
\r
21820 + <Install>false</Install>
\r
21821 </BootstrapperPackage>
\r
21822 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
21823 <Visible>False</Visible>
\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
21834 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
21835 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/CallBaseMethodsOnISerializableTypesRule.cs
21836 index 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)
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"))
21846 - if (current.IsSerializable && current.Implements ("System.Runtime.Serialization.ISerializable"))
21847 + if (current.IsSerializable && current.Implements ("System.Runtime.Serialization", "ISerializable"))
21850 return InheritsFromISerializableImplementation (current);
21851 @@ -124,7 +124,8 @@ namespace Gendarme.Rules.Serialization {
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))
21861 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21862 index 217384b..5fdbd75 100644
21863 --- a/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21864 +++ b/gendarme/rules/Gendarme.Rules.Serialization/DeserializeOptionalFieldRule.cs
21868 using System.Collections.Generic;
21869 +using System.Globalization;
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.";
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";
21881 public override void Initialize (IRunner runner)
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");
21896 @@ -121,9 +121,9 @@ namespace Gendarme.Rules.Serialization {
21897 if (method.IsConstructor || !method.HasCustomAttributes)
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;
21907 if (deserialized_candidate && deserializing_candidate)
21908 @@ -133,19 +133,17 @@ namespace Gendarme.Rules.Serialization {
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)
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);
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);
21931 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj b/gendarme/rules/Gendarme.Rules.Serialization/Gendarme.Rules.Serialization.csproj
21932 index 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
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
21940 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
21941 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
21970 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
21971 <DebugSymbols>true</DebugSymbols>
\r
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
21978 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
21979 <DebugType>pdbonly</DebugType>
\r
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
21987 <Reference Include="System" />
\r
21989 <Name>Gendarme.Framework</Name>
\r
21990 </ProjectReference>
\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
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
22012 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/ImplementISerializableCorrectlyRule.cs
22013 index 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 {
22018 static private FieldDefinition CheckProperty (MethodDefinition getter)
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)
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))
22031 @@ -143,7 +143,7 @@ namespace Gendarme.Rules.Serialization {
22032 if (!mr.HasParameters || (mr.Name != "AddValue") || (mr.Parameters.Count < 2))
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"))
22039 // look at the second parameter, which should be (or return) the field
22040 @@ -189,7 +189,7 @@ namespace Gendarme.Rules.Serialization {
22042 public RuleResult CheckType (TypeDefinition type)
22044 - if (!type.IsSerializable || !type.Implements ("System.Runtime.Serialization.ISerializable"))
22045 + if (!type.IsSerializable || !type.Implements ("System.Runtime.Serialization", "ISerializable"))
22046 return RuleResult.DoesNotApply;
22048 MethodDefinition getObjectData = type.GetMethod (MethodSignatures.GetObjectData);
22049 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22050 index 75d3a89..bfa7bf1 100644
22051 --- a/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22052 +++ b/gendarme/rules/Gendarme.Rules.Serialization/MarkAllNonSerializableFieldsRule.cs
22057 +using System.Globalization;
22058 using Gendarme.Framework;
22059 using Gendarme.Framework.Rocks;
22061 @@ -75,7 +76,7 @@ namespace Gendarme.Rules.Serialization {
22062 public RuleResult CheckType (TypeDefinition type)
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;
22069 foreach (FieldDefinition field in type.Fields) {
22070 @@ -85,11 +86,17 @@ namespace Gendarme.Rules.Serialization {
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);
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);
22091 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializableAttributeOnISerializableTypeRule.cs
22092 index 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 {
22099 - private const string ISerializable = "System.Runtime.Serialization.ISerializable";
22101 public RuleResult CheckType (TypeDefinition type)
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;
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;
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)
22118 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/MissingSerializationConstructorRule.cs
22119 index 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 {
22126 - // non-localizable
22127 - private const string ISerializable = "System.Runtime.Serialization.ISerializable";
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)
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;
22140 // rule applies, only Success or Failure from the point on
22141 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/README.md b/gendarme/rules/Gendarme.Rules.Serialization/README.md
22142 new file mode 100644
22143 index 0000000..e236c99
22145 +++ b/gendarme/rules/Gendarme.Rules.Serialization/README.md
22147 +# Gendarme.Rules.Serialization Rules
22149 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Serialization(git)]] pages.
22154 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
22156 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj b/gendarme/rules/Gendarme.Rules.Serialization/Test/Tests.Rules.Serialization.csproj
22157 index 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
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
22165 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
22166 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
22195 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
22196 <DebugSymbols>true</DebugSymbols>
\r
22198 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
22199 <ErrorReport>prompt</ErrorReport>
\r
22200 <WarningLevel>4</WarningLevel>
\r
22201 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
22203 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
22204 <DebugType>pdbonly</DebugType>
\r
22206 <DefineConstants>TRACE</DefineConstants>
\r
22207 <ErrorReport>prompt</ErrorReport>
\r
22208 <WarningLevel>4</WarningLevel>
\r
22209 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
22212 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
22215 <Folder Include="Properties\" />
\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
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
22237 diff --git a/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Serialization/UseCorrectSignatureForSerializationMethodsRule.cs
22238 index 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.";
22245 - static string [] Attributes = {
22246 - "System.Runtime.Serialization.OnSerializingAttribute",
22247 - "System.Runtime.Serialization.OnSerializedAttribute",
22248 - "System.Runtime.Serialization.OnDeserializingAttribute",
22249 - "System.Runtime.Serialization.OnDeserializedAttribute"
22252 public override void Initialize (IRunner runner)
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);
22266 + static bool IsSerializationAttribute (TypeReference type)
22268 + if (type.Namespace != "System.Runtime.Serialization")
22271 + switch (type.Name) {
22272 + case "OnSerializingAttribute":
22273 + case "OnSerializedAttribute":
22274 + case "OnDeserializingAttribute":
22275 + case "OnDeserializedAttribute":
22282 + static bool HasAnySerializationAttribute (ICustomAttributeProvider method)
22284 + if (!method.HasCustomAttributes)
22287 + foreach (CustomAttribute ca in method.CustomAttributes) {
22288 + if (IsSerializationAttribute (ca.AttributeType))
22294 public RuleResult CheckMethod (MethodDefinition method)
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;
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;
22306 diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22307 index 25519b4..947bd6a 100644
22308 --- a/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22309 +++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidLargeClassesRule.cs
22313 using System.Collections.Generic;
22314 +using System.Globalization;
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);
22327 @@ -167,7 +168,8 @@ namespace Gendarme.Rules.Smells {
22329 int count = CountPrefixedFields (prefix, i);
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}'.",
22335 Runner.Report (type, Severity.Medium, Confidence.High, msg);
22337 @@ -182,7 +184,8 @@ namespace Gendarme.Rules.Smells {
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);
22347 diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22348 index 67cb274..1ef115b 100644
22349 --- a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22350 +++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongMethodsRule.cs
22354 using System.Collections.Generic;
22355 +using System.Globalization;
22358 using Mono.Cecil.Cil;
22359 @@ -181,19 +182,6 @@ namespace Gendarme.Rules.Smells {
22361 const int AssignationRatio = 7;
22362 const int DefaultAmountOfElements = 13;
22363 - static Dictionary<string, string> typeMethodDictionary;
22365 - static AvoidLongMethodsRule ()
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");
22377 public AvoidLongMethodsRule ()
22379 @@ -215,12 +203,31 @@ namespace Gendarme.Rules.Smells {
22380 if (method.HasParameters)
22383 + string name = method.Name;
22384 + if ((name != "Build") && (name != "InitializeComponent"))
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))
22395 + string nspace = type.BaseType.Namespace;
22396 + string tname = type.BaseType.Name;
22399 + if (nspace != "Gtk")
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";
22415 @@ -326,7 +333,8 @@ namespace Gendarme.Rules.Smells {
22417 return RuleResult.Success;
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);
22424 // success if the instruction count is below the defined threshold
22425 @@ -336,7 +344,8 @@ namespace Gendarme.Rules.Smells {
22427 return RuleResult.Success;
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);
22435 diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidLongParameterListsRule.cs
22436 index 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)
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.");
22447 private void CheckMethod (IMethodSignature method)
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.");
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;
22464 diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22465 index 8d79e77..f786cb7 100644
22466 --- a/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22467 +++ b/gendarme/rules/Gendarme.Rules.Smells/AvoidMessageChainsRule.cs
22470 using System.Collections.Generic;
22471 using System.Diagnostics;
22472 +using System.Globalization;
22475 using Mono.Cecil.Cil;
22476 @@ -116,7 +117,7 @@ namespace Gendarme.Rules.Smells {
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))
22485 @@ -131,7 +132,8 @@ namespace Gendarme.Rules.Smells {
22486 Log.WriteLine (this, "chain of length {0} at {1:X4}", counter, ins.Offset);
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);
22495 diff --git a/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs b/gendarme/rules/Gendarme.Rules.Smells/AvoidSpeculativeGeneralityRule.cs
22496 index 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 {
22503 - private bool HasExpectedInheritedTypeCount (MemberReference baseType, int expected)
22504 + private bool HasExpectedInheritedTypeCount (TypeReference baseType, int expected)
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)
22517 @@ -168,7 +167,7 @@ namespace Gendarme.Rules.Smells {
22519 private static bool InheritsOnlyFromObject (TypeDefinition type)
22521 - return !type.HasInterfaces && type.BaseType.FullName == "System.Object";
22522 + return !type.HasInterfaces && type.BaseType.IsNamed ("System", "Object");
22525 private static bool MostlyMethodsDelegatesCall (TypeDefinition type)
22526 diff --git a/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs b/gendarme/rules/Gendarme.Rules.Smells/CodeDuplicatedLocator.cs
22527 index 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;
22537 using Mono.Cecil.Cil;
22538 @@ -81,8 +82,10 @@ namespace Gendarme.Rules.Smells {
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 ()));
22551 diff --git a/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj b/gendarme/rules/Gendarme.Rules.Smells/Gendarme.Rules.Smells.csproj
22552 index 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
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
22560 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
22561 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
22590 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
22591 <DebugSymbols>true</DebugSymbols>
\r
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
22598 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
22599 <DebugType>pdbonly</DebugType>
\r
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
22607 <Reference Include="System" />
\r
22609 <Name>Gendarme.Rules.Performance</Name>
\r
22610 </ProjectReference>
\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
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.
22632 diff --git a/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs b/gendarme/rules/Gendarme.Rules.Smells/InstructionMatcher.cs
22633 index 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))
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))
22647 diff --git a/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs b/gendarme/rules/Gendarme.Rules.Smells/Pattern.cs
22648 index 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 {
22653 if (ins.OpCode.Code != Code.Isinst)
22655 - return ((ins.Operand as TypeReference).FullName == "System.IDisposable");
22658 - // look for a virtual call to a specific method
22659 - static bool IsCallVirt (Instruction ins, string typeName, string methodName)
22661 - if (ins.OpCode.Code != Code.Callvirt)
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");
22669 @@ -69,7 +60,9 @@ namespace Gendarme.Rules.Smells {
22671 static bool IsIDisposableDisposePattern (Instruction ins)
22673 - if (!IsCallVirt (ins, "System.IDisposable", "Dispose"))
22674 + if (ins.OpCode.Code != Code.Callvirt)
22676 + if (!(ins.Operand as MethodReference).IsNamed ("System", "IDisposable", "Dispose"))
22678 return ins.Next.Is (Code.Endfinally);
22680 @@ -89,10 +82,13 @@ namespace Gendarme.Rules.Smells {
22681 for (int i = 0; i < Count; i++) {
22682 Instruction ins = instructions [i];
22684 - if (IsCallVirt (ins, "System.Collections.IEnumerator", "get_Current"))
22686 - if (IsCallVirt (ins, "System.Collections.IEnumerator", "MoveNext"))
22688 + if (ins.OpCode.Code == Code.Callvirt) {
22689 + MethodReference mr = (ins.Operand as MethodReference);
22690 + if (mr.IsNamed ("System.Collections", "IEnumerator", "get_Current"))
22692 + if (mr.IsNamed ("System.Collections", "IEnumerator", "MoveNext"))
22695 // if there's a unknown call then it's likely not (totally) compiler generated
22696 call |= (ins.OpCode.FlowControl == FlowControl.Call);
22698 diff --git a/gendarme/rules/Gendarme.Rules.Smells/README.md b/gendarme/rules/Gendarme.Rules.Smells/README.md
22699 new file mode 100644
22700 index 0000000..b02c441
22702 +++ b/gendarme/rules/Gendarme.Rules.Smells/README.md
22704 +# Gendarme.Rules.Smells Rules
22706 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Smells(git)]] pages.
22711 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
22713 diff --git a/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs b/gendarme/rules/Gendarme.Rules.Smells/Test/AvoidCodeDuplicatedInSameClassTest.cs
22714 index 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)
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"))
22724 return "'Dictionary' should only be used for types implementing IDictionary and IDictionary<TKey,TValue>.";
22727 string CheckThreeOptions (TypeReference type)
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"))
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"))
22743 return "'Collection' should only be used for implementing ICollection or IEnumerable or inheriting from Queue, Stack, DataSet and DataTable.";
22744 diff --git a/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj b/gendarme/rules/Gendarme.Rules.Smells/Test/Tests.Rules.Smells.csproj
22745 index 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
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
22753 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
22754 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
22783 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
22784 <DebugSymbols>true</DebugSymbols>
\r
22786 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
22787 <ErrorReport>prompt</ErrorReport>
\r
22788 <WarningLevel>4</WarningLevel>
\r
22789 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
22791 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
22792 <DebugType>pdbonly</DebugType>
\r
22794 <DefineConstants>TRACE</DefineConstants>
\r
22795 <ErrorReport>prompt</ErrorReport>
\r
22796 <WarningLevel>4</WarningLevel>
\r
22797 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
22800 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
22803 <Folder Include="Properties\" />
\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
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.
22825 diff --git a/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs b/gendarme/rules/Gendarme.Rules.Ui/AddMatchingArrangeMeasureOverrideRule.cs
22826 index 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");
22845 public RuleResult CheckType (TypeDefinition type)
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);
22852 diff --git a/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj b/gendarme/rules/Gendarme.Rules.Ui/Gendarme.Rules.Ui.csproj
22853 index 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">
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>
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>
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>
22915 - <Reference Include="System" />
22916 - <Reference Include="System.Core">
22917 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
22921 - <Compile Include="..\..\AssemblyStaticInfo.cs">
22922 - <Link>AssemblyStaticInfo.cs</Link>
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" />
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>
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>
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
23013 + <Reference Include="System" />
\r
23014 + <Reference Include="System.Core">
\r
23015 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
23019 + <Compile Include="..\..\AssemblyStaticInfo.cs">
\r
23020 + <Link>AssemblyStaticInfo.cs</Link>
\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
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
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
23048 + <Install>false</Install>
\r
23049 + </BootstrapperPackage>
\r
23050 + <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
23051 + <Visible>False</Visible>
\r
23054 + <Install>false</Install>
\r
23055 + </BootstrapperPackage>
\r
23056 + <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
23057 + <Visible>False</Visible>
\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
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">
23073 <Target Name="AfterBuild">
23076 - <ProjectExtensions>
23079 - <MonoDevelop.Autotools.MakefileInfo IntegrationEnabled="true" RelativeMakefileName="Makefile.am" IsAutotoolsProject="true" RelativeConfigureInPath="../../..">
23080 - <BuildFilesVar Sync="true" Name="rules_sources" />
23081 - <DeployFilesVar />
23086 - <ProjectRefVar />
23087 - </MonoDevelop.Autotools.MakefileInfo>
23091 - </ProjectExtensions>
23093 + <ProjectExtensions>
\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
23103 + <ProjectRefVar />
\r
23104 + </MonoDevelop.Autotools.MakefileInfo>
\r
23107 + <VisualStudio />
\r
23108 + </ProjectExtensions>
\r
23110 \ No newline at end of file
23111 diff --git a/gendarme/rules/Gendarme.Rules.Ui/README.md b/gendarme/rules/Gendarme.Rules.Ui/README.md
23112 new file mode 100644
23113 index 0000000..b107d14
23115 +++ b/gendarme/rules/Gendarme.Rules.Ui/README.md
23117 +# Gendarme.Rules.Ui Rules
23119 +You can access the latest rules documentation from our [[wiki|https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Ui(git)]] pages.
23124 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
23126 diff --git a/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj b/gendarme/rules/Gendarme.Rules.Ui/Test/Tests.Rules.Ui.csproj
23127 index 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
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
23135 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
23136 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
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
23160 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
23161 <DebugSymbols>true</DebugSymbols>
\r
23163 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
23164 <ErrorReport>prompt</ErrorReport>
\r
23165 <WarningLevel>4</WarningLevel>
\r
23166 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23168 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
23169 <DebugType>pdbonly</DebugType>
\r
23171 <DefineConstants>TRACE</DefineConstants>
\r
23172 <ErrorReport>prompt</ErrorReport>
\r
23173 <WarningLevel>4</WarningLevel>
\r
23174 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23177 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
23179 <Reference Include="System.Core">
\r
23180 <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
23182 + <Reference Include="System.Xaml" />
\r
23183 <Reference Include="WindowsBase">
\r
23184 <RequiredTargetFramework>3.0</RequiredTargetFramework>
\r
23186 @@ -94,14 +98,33 @@
23187 </ProjectReference>
\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
23199 + <Install>false</Install>
\r
23200 </BootstrapperPackage>
\r
23201 <BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
\r
23202 <Visible>False</Visible>
\r
23205 + <Install>false</Install>
\r
23206 </BootstrapperPackage>
\r
23207 <BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
\r
23208 <Visible>False</Visible>
\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
23219 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
\r
23220 diff --git a/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs b/gendarme/rules/Gendarme.Rules.Ui/UseSTAThreadAttributeOnSWFEntryPointsRule.cs
23221 index 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 {
23226 private const string SystemWindowsForms = "System.Windows.Forms";
23228 - private const string STAThread = "System.STAThreadAttribute";
23229 - private const string MTAThread = "System.MTAThreadAttribute";
23231 public RuleResult CheckAssembly (AssemblyDefinition assembly)
23233 MethodDefinition entry_point = assembly.EntryPoint;
23234 @@ -115,8 +112,8 @@ namespace Gendarme.Rules.UI {
23235 if (!referencesSWF)
23236 return RuleResult.DoesNotApply;
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");
23243 // success if only [STAThread] attribute is present
23244 if (hasSTA && !hasMTA)
23245 diff --git a/gendarme/rules/README.md b/gendarme/rules/README.md
23246 new file mode 100644
23247 index 0000000..30a91a3
23249 +++ b/gendarme/rules/README.md
23251 +# Gendarme Rules Assemblies
23253 +Documentation for each assembly is available on [[Gendarme|http://www.mono-project.com/Gendarme]]'s wiki.
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)]]
23280 +Please report any documentation errors, typos or suggestions to the [[Gendarme Mailing List|https://groups.google.com/forum/?fromgroups#!forum/gendarme]]. Thanks!
23282 diff --git a/gendarme/rules/Test.Rules/Makefile.am b/gendarme/rules/Test.Rules/Makefile.am
23283 index 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 =
23289 framework=../../bin/Gendarme.Framework.dll
23290 -common_tests=../Test.Rules/Test.Rules.dll
23291 +common_tests=Test.Rules.dll
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 = \
23297 test_build_sources = $(addprefix $(srcdir)/, $(test_sources))
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)
23304 all: $(common_tests)
23306 diff --git a/gendarme/rules/Test.Rules/Test.Rules.csproj b/gendarme/rules/Test.Rules/Test.Rules.csproj
23307 index 8da60d8..9ee6d88 100755
23308 --- a/gendarme/rules/Test.Rules/Test.Rules.csproj
23309 +++ b/gendarme/rules/Test.Rules/Test.Rules.csproj
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
23315 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
23316 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
23345 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
23346 <DebugSymbols>true</DebugSymbols>
\r
23348 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
23349 <ErrorReport>prompt</ErrorReport>
\r
23350 <WarningLevel>4</WarningLevel>
\r
23351 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23353 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
23354 <DebugType>pdbonly</DebugType>
\r
23356 <DefineConstants>TRACE</DefineConstants>
\r
23357 <ErrorReport>prompt</ErrorReport>
\r
23358 <WarningLevel>4</WarningLevel>
\r
23359 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23362 <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
\r
23364 <Name>Gendarme.Framework</Name>
\r
23365 </ProjectReference>
\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
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
23387 diff --git a/gendarme/rules/common.make b/gendarme/rules/common.make
23388 index 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
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)
23399 tests_build_sources = $(addprefix $(srcdir)/Test/, $(tests_sources))
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)
23407 @@ -54,7 +54,7 @@ test: $(tests_dll)
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)
23414 self-test: $(rules_dll)
23415 mono --debug $(console_runner) $(rules_dll)
23416 diff --git a/gendarme/self-test.ignore b/gendarme/self-test.ignore
23417 index 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)
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
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
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
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)
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)
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)
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
23549 -# FX4 related - will be fixed once we move to FX4 (likely for Gendarme 3.0)
23550 -R: Gendarme.Rules.Maintainability.AvoidUnnecessarySpecializationRule
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)
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
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)
23571 diff --git a/gendarme/swf-wizard-runner/GuiRunner.cs b/gendarme/swf-wizard-runner/GuiRunner.cs
23572 index 385406e..b34d5cb 100644
23573 --- a/gendarme/swf-wizard-runner/GuiRunner.cs
23574 +++ b/gendarme/swf-wizard-runner/GuiRunner.cs
23578 using System.Collections.Generic;
23579 +using System.Globalization;
23581 using System.Reflection;
23583 @@ -110,11 +111,11 @@ namespace Gendarme {
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);
23599 diff --git a/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs b/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
23602 index c588026..9a1518f
23603 --- a/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
23604 +++ b/gendarme/swf-wizard-runner/Properties/Resources.Designer.cs
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
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 {
23624 diff --git a/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs b/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
23627 index c7479ed..ad7c2d2
23628 --- a/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
23629 +++ b/gendarme/swf-wizard-runner/Properties/Settings.Designer.cs
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
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 {
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 {
23647 private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
23648 diff --git a/gendarme/swf-wizard-runner/Wizard.Designer.cs b/gendarme/swf-wizard-runner/Wizard.Designer.cs
23649 index 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";
23659 // welcome_link_label
23661 diff --git a/gendarme/swf-wizard-runner/Wizard.cs b/gendarme/swf-wizard-runner/Wizard.cs
23662 index 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;
23671 using System.Windows.Forms;
23673 @@ -98,7 +99,7 @@ namespace Gendarme {
23674 if ((v.Major == 0) && (v.Minor == 0))
23675 welcome_gendarme_label.Text = "Gendarme (development snapshot)";
23677 - welcome_gendarme_label.Text = String.Format ("Gendarme, version {0}", v);
23678 + welcome_gendarme_label.Text = String.Format (CultureInfo.CurrentCulture, "Gendarme, version {0}", v);
23680 assembly_loader = UpdateAssemblies;
23682 @@ -265,7 +266,7 @@ namespace Gendarme {
23683 next_button.Enabled = has_files;
23684 remove_file_button.Enabled = 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");
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);
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");
23701 @@ -390,7 +392,8 @@ namespace Gendarme {
23702 parent.Checked = true;
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);
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 {
23724 private bool ConfirmAnalyzeAbort (bool quit)
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)
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;
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)
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);
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;
23764 diff --git a/gendarme/swf-wizard-runner/swf-wizard-runner.csproj b/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
23765 index b54da3b..4f52a11 100644
23766 --- a/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
23767 +++ b/gendarme/swf-wizard-runner/swf-wizard-runner.csproj
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
23773 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
23774 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
23804 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
23805 <DebugSymbols>true</DebugSymbols>
\r
23807 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
23808 <ErrorReport>prompt</ErrorReport>
\r
23809 <WarningLevel>4</WarningLevel>
\r
23810 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23812 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
23813 <DebugType>pdbonly</DebugType>
\r
23815 <DefineConstants>TRACE;RELEASE</DefineConstants>
\r
23816 <ErrorReport>prompt</ErrorReport>
\r
23817 <WarningLevel>4</WarningLevel>
\r
23818 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
23821 <Reference Include="System" />
\r
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
23830 <Compile Include="..\AssemblyStaticInfo.cs" />
\r
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
23840 + <Compile Include="Properties\Settings.Designer.cs">
\r
23841 + <AutoGen>True</AutoGen>
\r
23842 + <DesignTimeSharedInput>True</DesignTimeSharedInput>
\r
23843 + <DependentUpon>Settings.settings</DependentUpon>
\r
23845 <Compile Include="Wizard.cs">
\r
23846 <SubType>Form</SubType>
\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
23857 <None Include="Properties\Settings.settings">
\r
23858 <Generator>SettingsSingleFileGenerator</Generator>
\r
23859 + <LastGenOutput>Settings.Designer.cs</LastGenOutput>
\r
23861 - <Compile Include="Properties\Settings.Designer.cs">
\r
23862 - <DependentUpon>Settings.settings</DependentUpon>
\r
23864 <EmbeddedResource Include="..\console\gendarme.xsl" />
\r
23865 <None Include="Resources\gendarme.png" />
\r
23867 @@ -90,6 +118,23 @@
23869 <Content Include="Resources\gendarme.ico" />
\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
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
23891 diff --git a/gendarme/tools/supported/Makefile.am b/gendarme/tools/supported/Makefile.am
23892 index 4f8f0a9..8590cf2 100644
23893 --- a/gendarme/tools/supported/Makefile.am
23894 +++ b/gendarme/tools/supported/Makefile.am
23897 +SUBDIRS = gd2i templates
23899 diff --git a/gendarme/tools/supported/gd2i/Makefile.am b/gendarme/tools/supported/gd2i/Makefile.am
23900 index 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 = \
23906 $(gd2i_SCRIPTS): $(gd2i_sources)
23907 - $(GMCS) -d:CODE_ANALYSIS -debug $^ -out:$@
23908 + $(MCS) -d:CODE_ANALYSIS -debug $^ -out:$@
23910 update: $(gd2i_SCRIPTS)
23911 mono --debug $(gd2i_SCRIPTS) ../../../bin/self-test.xml ../../../self-test.ignore
23912 diff --git a/gendarme/tools/supported/gd2i/gd2i.csproj b/gendarme/tools/supported/gd2i/gd2i.csproj
23913 index ec2aa2d..84105de 100644
23914 --- a/gendarme/tools/supported/gd2i/gd2i.csproj
23915 +++ b/gendarme/tools/supported/gd2i/gd2i.csproj
23917 -<?xml version="1.0" encoding="utf-8"?>
23918 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
23950 - <Reference Include="System" />
23951 - <Reference Include="System.Core">
23952 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
23954 - <Reference Include="System.Xml" />
23957 - <Compile Include="..\..\..\AssemblyStaticInfo.cs">
23958 - <Link>AssemblyStaticInfo.cs</Link>
23960 - <Compile Include="..\..\..\console\Options.cs">
23961 - <Link>Options.cs</Link>
23963 - <Compile Include="gd2i.cs" />
23966 - <Folder Include="Properties\" />
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
24024 + <Reference Include="System" />
\r
24025 + <Reference Include="System.Core">
\r
24026 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
24028 + <Reference Include="System.Xml" />
\r
24031 + <Compile Include="..\..\..\AssemblyStaticInfo.cs">
\r
24032 + <Link>AssemblyStaticInfo.cs</Link>
\r
24034 + <Compile Include="..\..\..\console\Options.cs">
\r
24035 + <Link>Options.cs</Link>
\r
24037 + <Compile Include="gd2i.cs" />
\r
24040 + <Folder Include="Properties\" />
\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
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">
24064 <Target Name="AfterBuild">
24069 \ No newline at end of file
24070 diff --git a/gendarme/tools/supported/templates/.gitignore b/gendarme/tools/supported/templates/.gitignore
24071 new file mode 100644
24072 index 0000000..c4c4ffc
24074 +++ b/gendarme/tools/supported/templates/.gitignore
24077 diff --git a/gendarme/tools/supported/templates/AssemblyRule.cs b/gendarme/tools/supported/templates/AssemblyRule.cs
24078 new file mode 100644
24079 index 0000000..80e77c1
24081 +++ b/gendarme/tools/supported/templates/AssemblyRule.cs
24084 +// $rootnamespace$.$safeitemname$
24087 +// $name$ <$email$>
24089 +// Copyright (C) $year$ $name$
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:
24098 +// The above copyright notice and this permission notice shall be included in
24099 +// all copies or substantial portions of the Software.
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
24112 +using Mono.Cecil.Cil;
24114 +using Gendarme.Framework;
24115 +using Gendarme.Framework.Engines;
24116 +using Gendarme.Framework.Helpers;
24117 +using Gendarme.Framework.Rocks;
24119 +namespace $rootnamespace$ {
24122 + /// TODO: Add a summary of the rule.
24127 + /// TODO: Add an example where the rule would fail.
24131 + /// Good example:
24133 + /// TODO: Show how to fix the bad example.
24137 + // TODO: Describe the problem and solution
24140 + public class $safeitemname$ : Rule, IAssemblyRule {
24141 + public RuleResult CheckAssembly (AssemblyDefinition assembly)
24143 + // TODO: Write the rule.
24144 + return RuleResult.Success;
24148 diff --git a/gendarme/tools/supported/templates/AssemblyRule.vstemplate b/gendarme/tools/supported/templates/AssemblyRule.vstemplate
24149 new file mode 100644
24150 index 0000000..9715194
24152 +++ b/gendarme/tools/supported/templates/AssemblyRule.vstemplate
24154 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
24166 + <Assembly>Mono.Cecil</Assembly>
\r
24169 + <Assembly>Gendarme.Framework</Assembly>
\r
24172 + <Assembly>System.Core</Assembly>
\r
24175 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">AssemblyRule.cs</ProjectItem>
\r
24176 + </TemplateContent>
\r
24178 \ No newline at end of file
24179 diff --git a/gendarme/tools/supported/templates/AssemblyTest.cs b/gendarme/tools/supported/templates/AssemblyTest.cs
24180 new file mode 100644
24181 index 0000000..77d5c06
24183 +++ b/gendarme/tools/supported/templates/AssemblyTest.cs
24186 +// $rootnamespace$.$safeitemname$
24189 +// $name$ <$email$>
24191 +// Copyright (C) $year$ $name$
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:
24200 +// The above copyright notice and this permission notice shall be included in
24201 +// all copies or substantial portions of the Software.
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
24212 +using System.Reflection;
24215 +// TODO: Add using for the project of the rule being tested.
24216 +// using Gendarme.Rules. ;
24218 +using NUnit.Framework;
24219 +using Test.Rules.Fixtures;
24220 +using Test.Rules.Helpers;
24221 +using Test.Rules.Definitions;
24223 +namespace $rootnamespace$ {
24226 + public class $safeitemname$ : AssemblyRuleTestFixture</* TODO: Add rule's type */> {
24228 + public void DoesNotApply ()
24230 + // TODO: Write tests that don't apply.
24231 + // AssertRuleDoesNotApply (assembly);
24235 + public void Good ()
24237 + // TODO: Write tests that should succeed.
24238 + // AssertRuleSuccess (assembly);
24242 + public void Bad ()
24244 + // TODO: Write tests that should fail.
24245 + // AssertRuleFailure (assembly);
24249 diff --git a/gendarme/tools/supported/templates/AssemblyTest.vstemplate b/gendarme/tools/supported/templates/AssemblyTest.vstemplate
24250 new file mode 100644
24251 index 0000000..9c8c0f0
24253 +++ b/gendarme/tools/supported/templates/AssemblyTest.vstemplate
24255 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
24267 + <Assembly>Mono.Cecil</Assembly>
\r
24270 + <Assembly>Gendarme.Framework</Assembly>
\r
24273 + <Assembly>Test.Rules</Assembly>
\r
24276 + <Assembly>System.Core</Assembly>
\r
24279 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">AssemblyTest.cs</ProjectItem>
\r
24280 + </TemplateContent>
\r
24282 \ No newline at end of file
24283 diff --git a/gendarme/tools/supported/templates/Makefile.am b/gendarme/tools/supported/templates/Makefile.am
24284 new file mode 100644
24285 index 0000000..885e9e8
24287 +++ b/gendarme/tools/supported/templates/Makefile.am
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
24299 +GENDARME_ICON = ../../../swf-wizard-runner/Resources/gendarme.ico
24301 +vsnet-item-assembly-rule:
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/*
24309 +vsnet-item-assembly-test:
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/*
24317 +vsnet-item-method-rule:
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/*
24325 +vsnet-item-method-test:
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/*
24333 +vsnet-item-type-rule:
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/*
24341 +vsnet-item-type-test:
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/*
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
24353 +vsnet-project-rules:
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/*
24361 +vsnet-project-tests:
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/*
24369 +vsnet-project-templates: vsnet-project-rules vsnet-project-tests
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"
24383 +gendarme-vsnet-templates.zip: vsnet
24385 +all: gendarme-vsnet-templates.zip
24391 diff --git a/gendarme/tools/supported/templates/MethodRule.cs b/gendarme/tools/supported/templates/MethodRule.cs
24392 new file mode 100644
24393 index 0000000..bd0911a
24395 +++ b/gendarme/tools/supported/templates/MethodRule.cs
24398 +// $rootnamespace$.$safeitemname$
24401 +// $name$ <$email$>
24403 +// Copyright (C) $year$ $name$
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:
24412 +// The above copyright notice and this permission notice shall be included in
24413 +// all copies or substantial portions of the Software.
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
24426 +using Mono.Cecil.Cil;
24428 +using Gendarme.Framework;
24429 +using Gendarme.Framework.Engines;
24430 +using Gendarme.Framework.Helpers;
24431 +using Gendarme.Framework.Rocks;
24433 +namespace $rootnamespace$ {
24436 + /// TODO: Add a summary of the rule.
24441 + /// TODO: Add an example where the rule would fail.
24445 + /// Good example:
24447 + /// TODO: Show how to fix the bad example.
24451 + // TODO: Describe the problem and solution
24454 + public class $safeitemname$ : Rule, IMethodRule {
24455 + public RuleResult CheckMethod (MethodDefinition method)
24457 + // TODO: Write the rule.
24458 + return RuleResult.Success;
24462 diff --git a/gendarme/tools/supported/templates/MethodRule.vstemplate b/gendarme/tools/supported/templates/MethodRule.vstemplate
24463 new file mode 100644
24464 index 0000000..5942dbd
24466 +++ b/gendarme/tools/supported/templates/MethodRule.vstemplate
24468 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
24480 + <Assembly>Mono.Cecil</Assembly>
\r
24483 + <Assembly>Gendarme.Framework</Assembly>
\r
24486 + <Assembly>System.Core</Assembly>
\r
24489 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">MethodRule.cs</ProjectItem>
\r
24490 + </TemplateContent>
\r
24492 \ No newline at end of file
24493 diff --git a/gendarme/tools/supported/templates/MethodTest.cs b/gendarme/tools/supported/templates/MethodTest.cs
24494 new file mode 100644
24495 index 0000000..4f70412
24497 +++ b/gendarme/tools/supported/templates/MethodTest.cs
24500 +// $rootnamespace$.$safeitemname$
24503 +// $name$ <$email$>
24505 +// Copyright (C) $year$ $name$
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:
24514 +// The above copyright notice and this permission notice shall be included in
24515 +// all copies or substantial portions of the Software.
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
24526 +using System.Reflection;
24529 +// TODO: Add using for the project of the rule being tested.
24530 +// using Gendarme.Rules. ;
24532 +using NUnit.Framework;
24533 +using Test.Rules.Fixtures;
24534 +using Test.Rules.Helpers;
24535 +using Test.Rules.Definitions;
24537 +namespace $rootnamespace$ {
24540 + public class $safeitemname$ : MethodRuleTestFixture</* TODO: Add rule's type */> {
24542 + public void DoesNotApply ()
24544 + // TODO: Write tests that don't apply.
24545 + // AssertRuleDoesNotApply (method);
24549 + public void Good ()
24551 + // TODO: Write tests that should succeed.
24552 + // AssertRuleSuccess (method);
24556 + public void Bad ()
24558 + // TODO: Write tests that should fail.
24559 + // AssertRuleFailure (method);
24563 diff --git a/gendarme/tools/supported/templates/MethodTest.vstemplate b/gendarme/tools/supported/templates/MethodTest.vstemplate
24564 new file mode 100644
24565 index 0000000..c9e9cd7
24567 +++ b/gendarme/tools/supported/templates/MethodTest.vstemplate
24569 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
24581 + <Assembly>Mono.Cecil</Assembly>
\r
24584 + <Assembly>Gendarme.Framework</Assembly>
\r
24587 + <Assembly>Test.Rules</Assembly>
\r
24590 + <Assembly>System.Core</Assembly>
\r
24593 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">MethodTest.cs</ProjectItem>
\r
24594 + </TemplateContent>
\r
24596 \ No newline at end of file
24597 diff --git a/gendarme/tools/supported/templates/README b/gendarme/tools/supported/templates/README
24598 new file mode 100644
24599 index 0000000..13a814b
24601 +++ b/gendarme/tools/supported/templates/README
24603 +Here are uncompressed C# templates for Gendarme rules, tests and projects.
24605 +To build the compressed templates required by VS.NET (2008/2010) just issue a:
24609 +and read the README.vsnet file (also part of the archive).
24611 diff --git a/gendarme/tools/supported/templates/README.vsnet b/gendarme/tools/supported/templates/README.vsnet
24612 new file mode 100644
24613 index 0000000..9ffcf5e
24615 +++ b/gendarme/tools/supported/templates/README.vsnet
24617 +Gendarme Item/Project Templates for Visual Studio
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
24630 diff --git a/gendarme/tools/supported/templates/Templates.RuleProject.csproj b/gendarme/tools/supported/templates/Templates.RuleProject.csproj
24631 new file mode 100644
24632 index 0000000..4208f3e
24634 +++ b/gendarme/tools/supported/templates/Templates.RuleProject.csproj
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
24672 + <Reference Include="System" />
\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
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
24689 + <Target Name="AfterBuild">
\r
24693 \ No newline at end of file
24694 diff --git a/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate b/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate
24695 new file mode 100644
24696 index 0000000..41afb51
24698 +++ b/gendarme/tools/supported/templates/Templates.RuleProject.vstemplate
24700 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
\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
24719 \ No newline at end of file
24720 diff --git a/gendarme/tools/supported/templates/Templates.TestProject.csproj b/gendarme/tools/supported/templates/Templates.TestProject.csproj
24721 new file mode 100644
24722 index 0000000..6dd3298
24724 +++ b/gendarme/tools/supported/templates/Templates.TestProject.csproj
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
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
24776 + <Reference Include="nunit.framework, Version=2.5.3.9345, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
\r
24777 + <Reference Include="System" />
\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
24784 + <Target Name="AfterBuild">
\r
24788 \ No newline at end of file
24789 diff --git a/gendarme/tools/supported/templates/Templates.TestProject.vstemplate b/gendarme/tools/supported/templates/Templates.TestProject.vstemplate
24790 new file mode 100644
24791 index 0000000..2d87449
24793 +++ b/gendarme/tools/supported/templates/Templates.TestProject.vstemplate
24795 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
\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
24814 \ No newline at end of file
24815 diff --git a/gendarme/tools/supported/templates/TypeRule.cs b/gendarme/tools/supported/templates/TypeRule.cs
24816 new file mode 100644
24817 index 0000000..fce1256
24819 +++ b/gendarme/tools/supported/templates/TypeRule.cs
24822 +// $rootnamespace$.$safeitemname$
24825 +// $name$ <$email$>
24827 +// Copyright (C) $year$ $name$
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:
24836 +// The above copyright notice and this permission notice shall be included in
24837 +// all copies or substantial portions of the Software.
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
24850 +using Mono.Cecil.Cil;
24852 +using Gendarme.Framework;
24853 +using Gendarme.Framework.Engines;
24854 +using Gendarme.Framework.Helpers;
24855 +using Gendarme.Framework.Rocks;
24857 +namespace $rootnamespace$ {
24860 + /// TODO: Add a summary of the rule.
24865 + /// TODO: Add an example where the rule would fail.
24869 + /// Good example:
24871 + /// TODO: Show how to fix the bad example.
24875 + // TODO: Describe the problem and solution
24878 + public class $safeitemname$ : Rule, ITypeRule {
24879 + public RuleResult CheckType (TypeDefinition type)
24881 + // TODO: Write the rule.
24882 + return RuleResult.Success;
24886 diff --git a/gendarme/tools/supported/templates/TypeRule.vstemplate b/gendarme/tools/supported/templates/TypeRule.vstemplate
24887 new file mode 100644
24888 index 0000000..3a0e9c1
24890 +++ b/gendarme/tools/supported/templates/TypeRule.vstemplate
24892 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
24904 + <Assembly>Mono.Cecil</Assembly>
\r
24907 + <Assembly>Gendarme.Framework</Assembly>
\r
24910 + <Assembly>System.Core</Assembly>
\r
24913 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">TypeRule.cs</ProjectItem>
\r
24914 + </TemplateContent>
\r
24916 \ No newline at end of file
24917 diff --git a/gendarme/tools/supported/templates/TypeTest.cs b/gendarme/tools/supported/templates/TypeTest.cs
24918 new file mode 100644
24919 index 0000000..92af871
24921 +++ b/gendarme/tools/supported/templates/TypeTest.cs
24924 +// $rootnamespace$.$safeitemname$
24927 +// $name$ <$email$>
24929 +// Copyright (C) $year$ $name$
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:
24938 +// The above copyright notice and this permission notice shall be included in
24939 +// all copies or substantial portions of the Software.
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
24950 +using System.Reflection;
24953 +// TODO: Add using for the project of the rule being tested.
24954 +// using Gendarme.Rules. ;
24956 +using NUnit.Framework;
24957 +using Test.Rules.Fixtures;
24958 +using Test.Rules.Helpers;
24959 +using Test.Rules.Definitions;
24961 +namespace $rootnamespace$ {
24964 + public class $safeitemname$ : TypeRuleTestFixture</* TODO: Add rule's type */> {
24966 + public void DoesNotApply ()
24968 + // TODO: Write tests that don't apply.
24969 + // AssertRuleDoesNotApply<type> ();
24973 + public void Good ()
24975 + // TODO: Write tests that should succeed.
24976 + // AssertRuleSuccess<type> ();
24980 + public void Bad ()
24982 + // TODO: Write tests that should fail.
24983 + // AssertRuleFailure<type> ();
24987 diff --git a/gendarme/tools/supported/templates/TypeTest.vstemplate b/gendarme/tools/supported/templates/TypeTest.vstemplate
24988 new file mode 100644
24989 index 0000000..2e0c866
24991 +++ b/gendarme/tools/supported/templates/TypeTest.vstemplate
24993 +<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
\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
25005 + <Assembly>Mono.Cecil</Assembly>
\r
25008 + <Assembly>Gendarme.Framework</Assembly>
\r
25011 + <Assembly>Test.Rules</Assembly>
\r
25014 + <Assembly>System.Core</Assembly>
\r
25017 + <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">TypeTest.cs</ProjectItem>
\r
25018 + </TemplateContent>
\r
25020 \ No newline at end of file
25021 diff --git a/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs b/gendarme/tools/unsupported/mapper/FxCopMapBuilder.cs
25022 index 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);
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)");
25033 return String.Empty;
25035 diff --git a/gendarme/tools/unsupported/mapper/Makefile.am b/gendarme/tools/unsupported/mapper/Makefile.am
25036 index 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 = \
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)
25048 diff --git a/gendarme/tools/unsupported/mapper/fxcop.missing b/gendarme/tools/unsupported/mapper/fxcop.missing
25049 index 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
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
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
25089 diff --git a/gendarme/tools/unsupported/typeref/Makefile.am b/gendarme/tools/unsupported/typeref/Makefile.am
25090 index 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 = \
25096 typeref.exe: $(typeref_sources)
25097 - $(GMCS) -debug $^ -out:$@ -r:$(CECIL_ASM)
25098 + $(MCS) -debug $^ -out:$@ -r:$(CECIL_ASM)
25102 diff --git a/gendarme/tools/unsupported/typeref/typeref.csproj b/gendarme/tools/unsupported/typeref/typeref.csproj
25103 index 25854ee..09d805d 100644
25104 --- a/gendarme/tools/unsupported/typeref/typeref.csproj
25105 +++ b/gendarme/tools/unsupported/typeref/typeref.csproj
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
25111 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
\r
25112 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
\r
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
25141 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
\r
25142 <DebugSymbols>true</DebugSymbols>
\r
25144 <DefineConstants>DEBUG;TRACE</DefineConstants>
\r
25145 <ErrorReport>prompt</ErrorReport>
\r
25146 <WarningLevel>4</WarningLevel>
\r
25147 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
25149 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
\r
25150 <DebugType>pdbonly</DebugType>
\r
25152 <DefineConstants>TRACE</DefineConstants>
\r
25153 <ErrorReport>prompt</ErrorReport>
\r
25154 <WarningLevel>4</WarningLevel>
\r
25155 + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
\r
25158 <Reference Include="System" />
\r
25161 <Folder Include="Properties\" />
\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
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.
25183 diff --git a/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am b/gendarme/tools/unsupported/xmldoc2wiki/Makefile.am
25184 index 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 = \
25190 xmldoc2wiki.exe: $(xmldoc2wiki_sources)
25191 - $(GMCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll
25192 + $(MCS) -debug $^ -out:$@ -r:System.Xml.Linq.dll
25195 rm -f xmldoc2wiki.exe*
25196 diff --git a/gendarme/tools/unsupported/xmldoc2wiki/README b/gendarme/tools/unsupported/xmldoc2wiki/README
25197 index 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
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.
25207 + a) Install gollum (https://github.com/github/gollum#readme). This requires Ruby.
25209 + % gem install gollum
25211 + b) Install rdiscount (http://daringfireball.net/projects/markdown/) for Markdown support
25213 + % gem install rdiscount
25215 + c) Install Pygments (http://pygments.org/) for syntax highlightning. This requires Python.
25217 + % easy_install Pygments
25219 diff --git a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25220 index 4fbca7f..5fbc2dd 100644
25221 --- a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25222 +++ b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.cs
25225 +// Gendarme's xmldoc2wiki tool
25228 +// Sebastien Pouliot <sebastien@ximian.com>
25229 +// Yuri Stuken <stuken.yuri@gmail.com>
25231 +// Copyright (C) 2010-2011 Novell, Inc (http://www.novell.com)
25232 +// Copyright (C) 2010 Yuri Stuken
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:
25241 +// The above copyright notice and this permission notice shall be included in
25242 +// all copies or substantial portions of the Software.
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
25254 using System.Collections.Generic;
25255 @@ -11,6 +39,7 @@ static class Program {
25256 static HashSet<string> assembliesIndex = new HashSet<string> ();
25258 static string outputdir;
25259 + static string version = "git";
25261 static string CleanUp (this string s)
25263 @@ -18,20 +47,6 @@ static class Program {
25264 return Regex.Replace (s, @"([\`\*])", @"\$1");
25267 - static void Header (TextWriter tw)
25269 - // tw.WriteLine ("# Rules");
25270 - // tw.WriteLine ();
25273 - static void Footer (TextWriter tw)
25275 - tw.WriteLine (@"## Feedback
25277 -Please report any documentation errors, typos or suggestions to the
25278 -[[Gendarme Google Group|http://groups.google.com/group/gendarme]]. Thanks!");
25281 static void AppendIndentedLine (StringBuilder sb, string line, int indentation)
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 ());
25288 + tw.AppendLine (); // make sure the following text is not part of the last item on the list
25291 static void ProcessRules (IEnumerable<XElement> rules, string assembly)
25292 @@ -207,83 +223,104 @@ Please report any documentation errors, typos or suggestions to the
25294 rulesIndex.Add (name);
25296 - TextWriter writer = File.CreateText (Path.Combine(Path.Combine(outputdir, assembly), Path.ChangeExtension (name, "md")));
25299 - rsb.AppendFormat ("# {0}", name);
25300 - rsb.AppendFormat ("{1}**{0}**{1}{1}", assembly, Environment.NewLine);
25301 - rsb.AppendLine ("## Description");
25303 - // tw.WriteLine (ProcessSummary (item));
25304 - ProcessText (rsb, item.Nodes ());
25305 - rsb.AppendLine ();
25306 - rsb.AppendLine ();
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);
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");
25327 + // tw.WriteLine (ProcessSummary (item));
25328 + ProcessText (rsb, item.Nodes ());
25329 + rsb.AppendLine ();
25330 + rsb.AppendLine ();
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);
25344 + XElement code = (example as XElement);
25345 + if (code == null)
25348 - XElement code = (example as XElement);
25349 - if (code == null)
25352 - switch (code.Name.LocalName) {
25354 - rsb.AppendFormat ("```csharp{1}{0}{1}```{1}{1}", ProcessCode (code.Value),
25355 - Environment.NewLine);
25358 - rsb.AppendFormat (" {0}{1}{1}", code.Value, Environment.NewLine);
25360 + switch (code.Name.LocalName) {
25362 + rsb.AppendFormat ("```csharp{1}{0}{1}```{1}{1}", ProcessCode (code.Value),
25363 + Environment.NewLine);
25366 + rsb.AppendFormat (" {0}{1}{1}", code.Value, Environment.NewLine);
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 ("* ");
25385 - ProcessText (rsb, remarks);
25386 + ProcessText (rsb, remarks);
25387 + rsb.AppendLine ();
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);
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 ();
25407 + writer.WriteLine (rsb);
25409 - writer.WriteLine (rsb);
25410 + if (version == "git") {
25411 + writer.WriteLine ();
25412 + writer.WriteLine (@"## Source code
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);
25422 from rule in rulesIndex
25425 - TextWriter indexWriter = File.CreateText (Path.Combine(outputdir, Path.Combine(assembly, assembly + ".md")));
25427 - foreach (var rule in rulesList) {
25428 - indexWriter.WriteLine ("[[{0}]] ", rule);
25430 + string assembly_index = String.Format ("{0}{1}{2}{1}{3}({2}).md",
25431 + outputdir, Path.DirectorySeparatorChar, version, assembly);
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);
25443 + if (version == "git") {
25444 + writer.WriteLine ();
25445 + writer.WriteLine (@"## Source code
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);
25451 + writer.WriteLine ();
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
25460 - string assembly =
25461 + string assembly = Path.GetFileName (
25462 (from a in doc.Descendants ("assembly")
25463 - select a.Element ("name").Value).FirstOrDefault();
25465 - if (assembly == null || !assembly.StartsWith("Gendarme"))
25466 + select a.Element ("name").Value).FirstOrDefault ());
25468 + if (assembly == null || !assembly.StartsWith ("Gendarme"))
25471 assembliesIndex.Add (assembly);
25472 - Directory.CreateDirectory (Path.Combine(outputdir, assembly));
25473 ProcessRules (members, assembly);
25476 @@ -310,40 +346,99 @@ Please report any documentation errors, typos or suggestions to the
25479 if (args.Length < 1) {
25480 - Console.WriteLine ("Usage: xmldoc2wiki filepattern [outputdir]");
25481 + Console.WriteLine ("Usage: xmldoc2wiki filepattern [--out outputdir] [--version version]");
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);
25492 - pattern = args [0];
25496 + List<string> filenames = new List<string> ();
25497 + for (int i = 0; i < args.Length; i++) {
25498 + string arg = args [i];
25500 + case "--version":
25501 + version = args [++i];
25504 + outputdir = args [++i];
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);
25517 + files = Directory.GetFiles (dir, pattern);
25518 + foreach (string file in files) {
25519 + filenames.Add (file);
25525 - files = Directory.GetFiles (dir, pattern);
25526 - if (args.Length >= 2)
25527 - outputdir = args [1];
25530 + string subdir = Path.Combine (outputdir, version);
25531 + if (!Directory.Exists (subdir))
25532 + Directory.CreateDirectory (subdir);
25534 - foreach (string file in files) {
25535 + foreach (string file in filenames) {
25536 + Console.WriteLine ("processing {0}", file);
25537 ProcessFile (file);
25540 - TextWriter writer = File.CreateText (Path.Combine(outputdir, "index.md"));
25541 + CreateVersionIndex ();
25542 + CreateFooterFile ();
25545 + static void CreateVersionIndex ()
25547 + string rules_index = String.Format ("{0}{1}{2}{1}Gendarme.Rules({2}).md",
25548 + outputdir, Path.DirectorySeparatorChar, version);
25550 + using (TextWriter writer = File.CreateText (rules_index)) {
25551 + writer.WriteLine ("# Gendarme Rules Documentation Index");
25552 + writer.WriteLine ();
25555 + from assembly in assembliesIndex
25559 + writer.WriteLine ("The following ({0}) assemblies are available in version {1}:",
25560 + assemblies.Count (), version);
25561 + writer.WriteLine ();
25563 + foreach (var assembly in assemblies) {
25564 + writer.WriteLine ("* [[{0}|{0}({1})]] ", assembly, version);
25567 + if (version == "git") {
25568 + writer.WriteLine ();
25569 + writer.WriteLine (@"## Source code
25572 - from assembly in assembliesIndex
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");
25579 - foreach (var assembly in assemblies) {
25580 - writer.WriteLine ("[[{0}]] ", assembly);
25581 + writer.WriteLine ();
25586 \ No newline at end of file
25588 + static void CreateFooterFile ()
25590 + string footer = String.Format ("{0}{1}{2}{1}_Footer.md", outputdir, Path.DirectorySeparatorChar, version);
25592 + using (TextWriter writer = File.CreateText (footer)) {
25593 + writer.WriteLine (@"## Feedback
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);
25601 diff --git a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25602 index db2fbf3..ee295fe 100644
25603 --- a/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25604 +++ b/gendarme/tools/unsupported/xmldoc2wiki/xmldoc2wiki.csproj
25606 -<?xml version="1.0" encoding="utf-8"?>
25607 -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
25639 - <Reference Include="System" />
25640 - <Reference Include="System.Core">
25641 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
25643 - <Reference Include="System.Xml.Linq">
25644 - <RequiredTargetFramework>3.5</RequiredTargetFramework>
25646 - <Reference Include="System.Xml" />
25649 - <Compile Include="..\..\..\AssemblyStaticInfo.cs">
25650 - <Link>AssemblyStaticInfo.cs</Link>
25652 - <Compile Include="xmldoc2wiki.cs" />
25655 - <Folder Include="Properties\" />
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
25713 + <Reference Include="System" />
\r
25714 + <Reference Include="System.Core">
\r
25715 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
25717 + <Reference Include="System.Xml.Linq">
\r
25718 + <RequiredTargetFramework>3.5</RequiredTargetFramework>
\r
25720 + <Reference Include="System.Xml" />
\r
25723 + <Compile Include="..\..\..\AssemblyStaticInfo.cs">
\r
25724 + <Link>AssemblyStaticInfo.cs</Link>
\r
25726 + <Compile Include="xmldoc2wiki.cs" />
\r
25729 + <Folder Include="Properties\" />
\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
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">
25753 <Target Name="AfterBuild">
25758 \ No newline at end of file
25759 diff --git a/gendarme/wix/Product.wxs b/gendarme/wix/Product.wxs
25760 index cce4d8d..cd04e05 100644
25761 --- a/gendarme/wix/Product.wxs
25762 +++ b/gendarme/wix/Product.wxs
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
25773 @@ -92,10 +92,10 @@
25774 <RemoveExistingProducts After="InstallValidate" />
\r
25775 </InstallExecuteSequence>
\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
25787 <!-- This enables the license screen and where to install screen -->
\r
25788 diff --git a/gendarme/wix/license.rtf b/gendarme/wix/license.rtf
25789 index 8bd49b0..45c52b3 100644
25790 --- a/gendarme/wix/license.rtf
25791 +++ b/gendarme/wix/license.rtf
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
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
25799 @@ -7,4 +7,4 @@ The above copyright notice and this permission notice shall be included in all c
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
25804 \ No newline at end of file
25806 diff --git a/gsharp/Main.cs b/gsharp/Main.cs
25807 index 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;
25816 public static void ShowHelp (OptionSet p)
25818 @@ -59,10 +60,10 @@ namespace Mono.CSharp.Gui
25820 Start ("C# InteractiveBase Shell", extra);
25824 static void AssemblyLoaded (object sender, AssemblyLoadEventArgs e)
25826 - Evaluator.ReferenceAssembly (e.LoadedAssembly);
25827 + evaluator.ReferenceAssembly (e.LoadedAssembly);
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 {
25835 - Evaluator.Init (new string [0]);
25836 + evaluator = new Evaluator (new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter ()));
25840 @@ -103,7 +104,7 @@ namespace Mono.CSharp.Gui
25842 // Add all currently loaded assemblies
25843 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ())
25844 - Evaluator.ReferenceAssembly (a);
25845 + evaluator.ReferenceAssembly (a);
25847 Start (String.Format ("Attached C# Interactive Shell at Process {0}", Process.GetCurrentProcess ().Id), null);
25849 @@ -129,7 +130,6 @@ namespace Mono.CSharp.Gui
25851 m.LoadFiles (files, false);
25853 - Evaluator.DescribeTypeExpressions = true;
25855 if (!HostHasGtkRunning){
25857 @@ -146,4 +146,4 @@ namespace Mono.CSharp.Gui
25862 \ No newline at end of file
25864 diff --git a/gsharp/MainWindow.cs b/gsharp/MainWindow.cs
25865 index 34c24e4..f5da16a 100644
25866 --- a/gsharp/MainWindow.cs
25867 +++ b/gsharp/MainWindow.cs
25868 @@ -80,7 +80,7 @@ namespace Mono.CSharp.Gui
25871 foreach (string file in libraries){
25872 - Evaluator.LoadAssembly (file);
25873 + Shell.Evaluator.LoadAssembly (file);
25876 foreach (string file in sources){
25877 @@ -101,7 +101,7 @@ namespace Mono.CSharp.Gui
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);
25886 diff --git a/gsharp/Shell.cs b/gsharp/Shell.cs
25887 index 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
25893 TextMark end_of_last_processing;
25894 - string expr = null;
25896 + Evaluator evaluator;
25897 + CompilerContext context;
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);
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;");
25910 + context = new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter ());
25911 + evaluator = new Evaluator (context);
25912 + evaluator.DescribeTypeExpressions = true;
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;");
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
25923 StringWriter errorwriter = new StringWriter ();
25925 - Evaluator.MessageOutput = errorwriter;
25927 + var old_printer = context.Report.SetPrinter (new StreamReportPrinter (errorwriter));
25930 - res = Evaluator.Evaluate (s, out result, out result_set);
25931 + res = evaluator.Evaluate (s, out result, out result_set);
25932 } catch (Exception e){
25934 ShowError (e.ToString ());
25935 ShowPrompt (true, false);
25938 + context.Report.SetPrinter (old_printer);
25942 @@ -262,7 +270,7 @@ namespace Mono.CSharp.Gui
25944 string saved_text = InputLine;
25946 - string [] completions = Evaluator.GetCompletions (LineUntilCursor, out prefix);
25947 + string [] completions = evaluator.GetCompletions (LineUntilCursor, out prefix);
25948 if (completions == null)
25951 @@ -405,6 +413,12 @@ namespace Mono.CSharp.Gui
25953 get { return Buffer.GetIterAtMark(Buffer.InsertMark); }
25956 + public Evaluator Evaluator {
25958 + return evaluator;
25963 get { return Buffer.GetText(InputLineBegin, InputLineEnd, false); }
25964 diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25965 index 21e9c5b..7e04ad0 100644
25966 --- a/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25967 +++ b/gsharp/gtk-gui/Mono.CSharp.Gui.DescribeType.cs
25969 -// ------------------------------------------------------------------------------
25970 -// <autogenerated>
25971 -// This code was generated by a tool.
25974 -// Changes to this file may cause incorrect behavior and will be lost if
25975 -// the code is regenerated.
25976 -// </autogenerated>
25977 -// ------------------------------------------------------------------------------
25979 -namespace Mono.CSharp.Gui {
25982 - public partial class DescribeType {
25984 - private Gtk.HBox hbox1;
25986 - private Gtk.Label label1;
25988 - private Gtk.Entry entry1;
25990 - private Gtk.Button buttonCancel;
25992 - private Gtk.Button buttonOk;
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]));
26016 - w2.Expand = 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]));
26028 - w1.Add(this.hbox1);
26029 - Gtk.Box.BoxChild w4 = ((Gtk.Box.BoxChild)(w1[this.hbox1]));
26031 - w4.Expand = false;
26033 - // Internal child Mono.CSharp.Gui.DescribeType.ActionArea
26034 - Gtk.HButtonBox w5 = this.ActionArea;
26035 - w5.Name = "dialog1_ActionArea";
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;
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]));
26062 - w7.Expand = false;
26064 - if ((this.Child != null)) {
26065 - this.Child.ShowAll();
26067 - this.DefaultWidth = 284;
26068 - this.DefaultHeight = 133;
26070 - this.entry1.Activated += new System.EventHandler(this.OnEntry1Activated);
26073 +// This file has been generated by the GUI designer. Do not modify.
26074 +namespace Mono.CSharp.Gui
26076 + public partial class DescribeType
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;
26084 + protected virtual void Build ()
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]));
26107 + w2.Expand = 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]));
26119 + w1.Add (this.hbox1);
26120 + global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(w1 [this.hbox1]));
26122 + w4.Expand = false;
26124 + // Internal child Mono.CSharp.Gui.DescribeType.ActionArea
26125 + global::Gtk.HButtonBox w5 = this.ActionArea;
26126 + w5.Name = "dialog1_ActionArea";
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;
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]));
26153 + w7.Expand = false;
26155 + if ((this.Child != null)) {
26156 + this.Child.ShowAll ();
26158 + this.DefaultWidth = 284;
26159 + this.DefaultHeight = 133;
26161 + this.entry1.Activated += new global::System.EventHandler (this.OnEntry1Activated);
26165 diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.MainWindow.cs
26166 index 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.
26175 -// Changes to this file may cause incorrect behavior and will be lost if
26176 -// the code is regenerated.
26177 -// </autogenerated>
26178 -// ------------------------------------------------------------------------------
26180 -namespace Mono.CSharp.Gui {
26183 - public partial class MainWindow {
26185 - private Gtk.UIManager UIManager;
26187 - private Gtk.Action FileAction;
26189 - private Gtk.Action QuitAction;
26191 - private Gtk.Action AttachToProcessAction;
26193 - private Gtk.Action HelpAction;
26195 - private Gtk.Action AboutAction;
26197 - private Gtk.Action ViewAction;
26199 - private Gtk.ToggleAction gtkpane;
26201 - private Gtk.Action ToolsAction;
26203 - private Gtk.Action DescribeTypeAction;
26205 - private Gtk.VBox vbox1;
26207 - private Gtk.MenuBar menubar1;
26209 - private Gtk.Notebook notebook1;
26211 - private Gtk.HPaned hpaned;
26213 - private Gtk.EventBox paned_container;
26215 - private Gtk.VBox vbox2;
26217 - private Gtk.Expander expander1;
26219 - private Gtk.Label label4;
26221 - private Gtk.Label GtkLabel4;
26223 - private Gtk.EventBox eventbox;
26225 - private Gtk.Label label1;
26227 - private Gtk.EventBox standalone_container;
26229 - private Gtk.Notebook shellnotebook;
26231 - private Gtk.ScrolledWindow sw;
26233 - private Gtk.Label label3;
26235 - private Gtk.Label label2;
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]));
26287 - w2.Expand = 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]));
26334 - w5.Expand = 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]));
26342 - this.hpaned.Add(this.vbox2);
26343 - this.notebook1.Add(this.hpaned);
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);
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;
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();
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);
26395 +// This file has been generated by the GUI designer. Do not modify.
26396 +namespace Mono.CSharp.Gui
26398 + public partial class MainWindow
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;
26427 + protected virtual void Build ()
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]));
26478 + w2.Expand = 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]));
26525 + w5.Expand = 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]));
26533 + this.hpaned.Add (this.vbox2);
26534 + this.notebook1.Add (this.hpaned);
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);
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;
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 ();
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);
26587 diff --git a/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs b/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26588 index 3ae7cd7..fed8491 100644
26589 --- a/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26590 +++ b/gsharp/gtk-gui/Mono.CSharp.Gui.ProcessSelector.cs
26592 -// ------------------------------------------------------------------------------
26593 -// <autogenerated>
26594 -// This code was generated by a tool.
26597 -// Changes to this file may cause incorrect behavior and will be lost if
26598 -// the code is regenerated.
26599 -// </autogenerated>
26600 -// ------------------------------------------------------------------------------
26602 -namespace Mono.CSharp.Gui {
26605 - public partial class ProcessSelector {
26607 - private Gtk.Frame frame1;
26609 - private Gtk.Alignment GtkAlignment;
26611 - private Gtk.ScrolledWindow GtkScrolledWindow;
26613 - private Gtk.TreeView treeview;
26615 - private Gtk.Label GtkLabel;
26617 - private Gtk.Button buttonCancel;
26619 - private Gtk.Button buttonOk;
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]));
26659 - w5.Padding = ((uint)(3));
26660 - // Internal child Mono.CSharp.Gui.ProcessSelector.ActionArea
26661 - Gtk.HButtonBox w6 = this.ActionArea;
26662 - w6.Name = "dialog1_ActionArea";
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;
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]));
26688 - w8.Expand = false;
26690 - if ((this.Child != null)) {
26691 - this.Child.ShowAll();
26693 - this.DefaultWidth = 400;
26694 - this.DefaultHeight = 300;
26696 - this.Close += new System.EventHandler(this.OnClose);
26699 +// This file has been generated by the GUI designer. Do not modify.
26700 +namespace Mono.CSharp.Gui
26702 + public partial class ProcessSelector
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;
26712 + protected virtual void Build ()
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]));
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";
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;
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]));
26780 + w8.Expand = false;
26782 + if ((this.Child != null)) {
26783 + this.Child.ShowAll ();
26785 + this.DefaultWidth = 400;
26786 + this.DefaultHeight = 300;
26788 + this.Close += new global::System.EventHandler (this.OnClose);
26792 diff --git a/gsharp/gtk-gui/generated.cs b/gsharp/gtk-gui/generated.cs
26793 index 8b467a5..9ef3363 100644
26794 --- a/gsharp/gtk-gui/generated.cs
26795 +++ b/gsharp/gtk-gui/generated.cs
26797 -// ------------------------------------------------------------------------------
26798 -// <autogenerated>
26799 -// This code was generated by a tool.
26802 -// Changes to this file may cause incorrect behavior and will be lost if
26803 -// the code is regenerated.
26804 -// </autogenerated>
26805 -// ------------------------------------------------------------------------------
26807 -namespace Stetic {
26810 - internal class Gui {
26812 - private static bool initialized;
26814 - internal static void Initialize(Gtk.Widget iconRenderer) {
26815 - if ((Stetic.Gui.initialized == false)) {
26816 - Stetic.Gui.initialized = true;
26821 - internal class ActionGroups {
26823 - public static Gtk.ActionGroup GetActionGroup(System.Type type) {
26824 - return Stetic.ActionGroups.GetActionGroup(type.FullName);
26827 - public static Gtk.ActionGroup GetActionGroup(string name) {
26831 +// This file has been generated by the GUI designer. Do not modify.
26834 + internal class Gui
26836 + private static bool initialized;
26838 + internal static void Initialize (Gtk.Widget iconRenderer)
26840 + if ((Stetic.Gui.initialized == false)) {
26841 + Stetic.Gui.initialized = true;
26846 + internal class ActionGroups
26848 + public static Gtk.ActionGroup GetActionGroup (System.Type type)
26850 + return Stetic.ActionGroups.GetActionGroup (type.FullName);
26853 + public static Gtk.ActionGroup GetActionGroup (string name)
26859 diff --git a/gui-compare/CecilMetadata.cs b/gui-compare/CecilMetadata.cs
26860 index 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 ()
26871 @@ -1011,15 +1012,24 @@ namespace GuiCompare {
26873 bool first_p = true;
26874 foreach (ParameterDefinition p in method_def.Parameters) {
26875 + TypeReference paramType = p.ParameterType;
26881 - else if (p.IsOut)
26882 + else if (paramType.IsByReference) {
26884 + sb.Append (p.IsOut ? "out " : "ref ");
26885 + paramType = paramType.GetElementType ();
26886 + } else if (p.IsOut) {
26887 + sb.Append ("out ");
26889 + } else if (p.IsOut) {
26890 sb.Append ("out ");
26892 sb.Append (beautify
26893 - ? CecilUtils.PrettyType (p.ParameterType)
26894 + ? CecilUtils.PrettyType (paramType)
26895 : CecilUtils.FormatTypeLikeCorCompare (p.ParameterType));
26898 @@ -1179,55 +1189,213 @@ namespace GuiCompare {
26899 public CecilAttribute (CustomAttribute ca)
26900 : base (ca.Constructor.DeclaringType.FullName)
26902 - var sb = new StringBuilder ("[" + ca.Constructor.DeclaringType.FullName);
26903 - bool first = true;
26905 - var cargs = ca.ConstructorArguments;
26906 - if (cargs != null && cargs.Count > 0) {
26907 - foreach (var argument in cargs) {
26909 - sb.Append (" (");
26912 - sb.Append (", ");
26913 + Dictionary<string, object> attribute_mapping = CreateAttributeMapping (ca);
26915 + foreach (string name in attribute_mapping.Keys) {
26916 + if (name == "TypeId")
26919 + object o = attribute_mapping[name];
26920 + Properties.Add (name, o == null ? "null" : o.ToString ());
26924 + static Dictionary<string, object> CreateAttributeMapping (CustomAttribute attribute)
26926 + var mapping = new Dictionary<string, object> ();
26928 + PopulateMapping (mapping, attribute);
26930 + var constructor = attribute.Constructor.Resolve ();
26931 + if (constructor == null || constructor.Parameters.Count == 0)
26934 + PopulateMapping (mapping, constructor, attribute);
26939 + static void PopulateMapping (Dictionary<string, object> mapping, CustomAttribute attribute)
26941 + foreach (var named_argument in attribute.Properties) {
26942 + var name = named_argument.Name;
26943 + var arg = named_argument.Argument;
26945 + if (arg.Value is CustomAttributeArgument)
26946 + arg = (CustomAttributeArgument) arg.Value;
26948 + mapping.Add (name, GetArgumentValue (arg.Type, arg.Value));
26952 - sb.Append (FormatValue (argument.Value));
26953 + static Dictionary<FieldReference, int> CreateArgumentFieldMapping (MethodDefinition constructor)
26955 + Dictionary<FieldReference, int> field_mapping = new Dictionary<FieldReference, int> ();
26957 + int? argument = null;
26959 + foreach (Instruction instruction in constructor.Body.Instructions) {
26960 + switch (instruction.OpCode.Code) {
26961 + case Code.Ldarg_1:
26964 + case Code.Ldarg_2:
26967 + case Code.Ldarg_3:
26971 + case Code.Ldarg_S:
26972 + argument = ((ParameterDefinition) instruction.Operand).Index + 1;
26976 + FieldReference field = (FieldReference) instruction.Operand;
26977 + if (field.DeclaringType.FullName != constructor.DeclaringType.FullName)
26980 + if (!argument.HasValue)
26983 + if (!field_mapping.ContainsKey (field))
26984 + field_mapping.Add (field, (int) argument - 1);
26991 + return field_mapping;
26994 + static Dictionary<PropertyDefinition, FieldReference> CreatePropertyFieldMapping (TypeDefinition type)
26996 + Dictionary<PropertyDefinition, FieldReference> property_mapping = new Dictionary<PropertyDefinition, FieldReference> ();
26998 + foreach (PropertyDefinition property in type.Properties) {
26999 + if (property.GetMethod == null)
27001 + if (!property.GetMethod.HasBody)
27004 + foreach (Instruction instruction in property.GetMethod.Body.Instructions) {
27005 + if (instruction.OpCode.Code != Code.Ldfld)
27008 + FieldReference field = (FieldReference) instruction.Operand;
27009 + if (field.DeclaringType.FullName != type.FullName)
27012 + property_mapping.Add (property, field);
27017 + return property_mapping;
27020 + static void PopulateMapping (Dictionary<string, object> mapping, MethodDefinition constructor, CustomAttribute attribute)
27022 + if (!constructor.HasBody)
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);
27031 + mapping.Add ("Value", dca.Value);
27035 + var field_mapping = CreateArgumentFieldMapping (constructor);
27036 + var property_mapping = CreatePropertyFieldMapping ((TypeDefinition) constructor.DeclaringType);
27038 + foreach (var pair in property_mapping) {
27040 + if (!field_mapping.TryGetValue (pair.Value, out argument))
27043 + var ca_arg = attribute.ConstructorArguments[argument];
27044 + if (ca_arg.Value is CustomAttributeArgument)
27045 + ca_arg = (CustomAttributeArgument) ca_arg.Value;
27047 + mapping[pair.Key.Name] = GetArgumentValue (ca_arg.Type, ca_arg.Value);
27051 - var properties = ca.Properties;
27052 - if (properties != null && properties.Count > 0) {
27053 - foreach (var namedArg in properties) {
27055 - sb.Append (" (");
27058 - sb.Append (", ");
27060 - sb.AppendFormat ("{0}={1}", namedArg.Name, FormatValue (namedArg.Argument.Value));
27061 + static object GetArgumentValue (TypeReference reference, object value)
27063 + var type = reference.Resolve ();
27064 + if (type == null)
27067 + if (type.IsEnum) {
27068 + if (IsFlaggedEnum (type))
27069 + return GetFlaggedEnumValue (type, value);
27071 + return GetEnumValue (type, value);
27077 + static bool IsFlaggedEnum (TypeDefinition type)
27079 + if (!type.IsEnum)
27082 + if (type.CustomAttributes.Count == 0)
27085 + foreach (CustomAttribute attribute in type.CustomAttributes)
27086 + if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
27092 + static object GetFlaggedEnumValue (TypeDefinition type, object value)
27094 + long flags = Convert.ToInt64 (value);
27095 + var signature = new StringBuilder ();
27097 + for (int i = type.Fields.Count - 1; i >= 0; i--) {
27098 + FieldDefinition field = type.Fields[i];
27100 + if (!field.HasConstant)
27103 + long flag = Convert.ToInt64 (field.Constant);
27108 + if ((flags & flag) == flag) {
27109 + if (signature.Length != 0)
27110 + signature.Append (", ");
27112 + signature.Append (field.Name);
27121 - ExtraInfo = sb.ToString ();
27123 + return signature.ToString ();
27126 - string FormatValue (object o)
27127 + static object GetEnumValue (TypeDefinition type, object value)
27131 + foreach (FieldDefinition field in type.Fields) {
27132 + if (!field.HasConstant)
27136 - return "\"" + o + "\"";
27137 + if (Comparer.Default.Compare (field.Constant, value) == 0)
27138 + return field.Name;
27142 - return o.ToString ().ToLowerInvariant ();
27144 - return o.ToString ();
27149 diff --git a/gui-compare/CompareContext.cs b/gui-compare/CompareContext.cs
27150 index 8a3b932..b171ef8 100644
27151 --- a/gui-compare/CompareContext.cs
27152 +++ b/gui-compare/CompareContext.cs
27155 using System.Collections.Generic;
27156 using System.Threading;
27157 +using System.Linq;
27159 namespace GuiCompare {
27161 @@ -153,7 +154,7 @@ namespace GuiCompare {
27162 void CompareBaseTypes (ComparisonNode parent, ICompHasBaseType reference_type, ICompHasBaseType target_type)
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()));
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";
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 {
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))
27187 - if (r.Count != t.Count) {
27188 - throw new NotImplementedException (string.Format ("Should never happen with valid data ({0} != {1})", r.Count, t.Count));
27191 for (int i = 0; i < r.Count; ++i) {
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),
27201 @@ -324,13 +321,42 @@ namespace GuiCompare {
27203 List<CompNamed> reference_attrs = reference_container.GetAttributes ();
27204 List<CompNamed> target_attrs = target_container.GetAttributes ();
27206 - reference_attrs.Sort (CompNamed.Compare);
27207 - target_attrs.Sort (CompNamed.Compare);
27209 + Comparison<CompNamed> comp = (x, y) => {
27210 + var r = CompNamed.Compare (x, y);
27214 + var xa = ((CompAttribute)x).Properties.Values.ToList ();
27215 + var ya = ((CompAttribute)y).Properties.Values.ToList ();
27217 + for (int i = 0; i < Math.Min (xa.Count, ya.Count); ++i) {
27218 + r = xa[i].CompareTo (ya[i]);
27226 + reference_attrs.Sort (comp);
27227 + target_attrs.Sort (comp);
27229 while (m < reference_attrs.Count || a < target_attrs.Count) {
27230 if (m == reference_attrs.Count) {
27231 - AddExtra (parent, target_attrs[a]);
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
27241 + AddExtra (parent, target_attrs[a]);
27248 @@ -345,10 +371,9 @@ namespace GuiCompare {
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]);
27260 @@ -364,27 +389,120 @@ namespace GuiCompare {
27265 + void CompareAttributeArguments (ComparisonNode parent, CompAttribute referenceAttribute, CompAttribute actualAttribute)
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":
27280 + // Don't care about these for now
27281 + case "System.ComponentModel.EditorAttribute":
27282 + case "System.ComponentModel.DesignerAttribute":
27286 + foreach (var entry in referenceAttribute.Properties) {
27287 + if (!actualAttribute.Properties.ContainsKey (entry.Key)) {
27290 + // Ignore missing value difference for default values
27292 + switch (referenceAttribute.Name) {
27293 + case "System.AttributeUsageAttribute":
27294 + // AllowMultiple defaults to false
27295 + if (entry.Key == "AllowMultiple" && entry.Value == "False")
27297 + // Inherited defaults to true
27298 + if (entry.Key == "Inherited" && entry.Value == "True")
27301 + case "System.ObsoleteAttribute":
27302 + if (entry.Key == "IsError" && entry.Value == "False")
27305 + if (entry.Key == "Message")
27311 + parent.AddError (String.Format ("Property `{0}' value is not set. Expected value: {1}", entry.Key, entry.Value));
27312 + parent.Status = ComparisonStatus.Error;
27316 + var target_value = actualAttribute.Properties[entry.Key];
27318 + switch (referenceAttribute.Name) {
27319 + case "System.Runtime.CompilerServices.TypeForwardedFromAttribute":
27320 + if (entry.Key == "AssemblyFullName")
27321 + target_value = target_value.Replace ("neutral", "Neutral");
27323 + case "System.Runtime.InteropServices.GuidAttribute":
27324 + if (entry.Key == "Value")
27325 + target_value = target_value.ToUpperInvariant ();
27327 + case "System.ObsoleteAttribute":
27328 + if (entry.Key == "Message")
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;
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;
27355 void CompareMembers (ComparisonNode parent,
27356 ICompMemberContainer reference_container, ICompMemberContainer target_container)
27358 + bool is_sealed = reference_container.IsSealed;
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);
27380 void CompareMemberLists (ComparisonNode parent,
27381 List<CompNamed> reference_list,
27382 - List<CompNamed> target_list)
27383 + List<CompNamed> target_list,
27388 @@ -427,9 +545,9 @@ namespace GuiCompare {
27389 // Try to give some hints to the developer, best we can do with
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";
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 {
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;
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
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";
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;
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]);
27435 + CompareAttributes (comparison, (ICompAttributeContainer)m1[0], (ICompAttributeContainer)m2[1]);
27436 + if (m1.Count > 1)
27437 + CompareAttributes (comparison, (ICompAttributeContainer)m1[1], (ICompAttributeContainer)m2[0]);
27441 + // Compare indexer parameters
27442 + if (m1.Count == m2.Count)
27443 + CompareParameters (comparison, (ICompParameters) m1[0], (ICompParameters) m2[0]);
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;
27455 @@ -476,13 +634,23 @@ namespace GuiCompare {
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
27464 + /* reference name is before target name, reference name is missing from target */
27465 + AddMissing (parent, reference_list[m]);
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
27476 + /* reference name is after target name, target name is extra */
27477 + AddExtra (parent, target_list[a]);
27483 diff --git a/gui-compare/InfoManager.cs b/gui-compare/InfoManager.cs
27484 index 1f8199d..246b2cd 100644
27485 --- a/gui-compare/InfoManager.cs
27486 +++ b/gui-compare/InfoManager.cs
27487 @@ -205,6 +205,7 @@ namespace GuiCompare
27489 "System.AddIn.Contract",
27490 "System.Configuration",
27491 + "System.ComponentModel.DataAnnotations",
27493 // "System.Configuration.Install",
27495 @@ -364,12 +365,132 @@ namespace GuiCompare
27501 + string [] api_4_5 = {
27504 + "System.Activities",
27505 + "System.Activities.Core.Presentation",
27506 + "System.Activities.DurableInstancing",
27507 + "System.Activities.Design",
27508 + "System.AddIn.Contract",
27510 + "System.ComponentModel.Composition",
27511 + "System.ComponentModel.DataAnnotations",
27512 + "System.configuration",
27513 + // "System.Configuration.Install",
27515 + "System.Data.DataSetExtensions",
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",
27528 + // "System.DirectoryServices.AccountManagement",
27529 + "System.DirectoryServices",
27530 + // "System.DirectoryServices.Protocols",
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",
27541 + "System.IO.Compression",
27542 + "System.IO.Compression.FileSystem",
27543 + "System.Management",
27544 + // "System.Management.Instrumentation",
27545 + "System.Messaging",
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",
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",
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",
27591 + "System.Xaml.Hosting",
27593 + "System.Xml.Linq",
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",
27607 + "PresentationBuildTasks",
27608 + "PresentationCore",
27609 + "PresentationFramework.Aero",
27610 + "PresentationFramework.Classic",
27611 + "PresentationFramework",
27612 + "PresentationFramework.Luna",
27613 + "PresentationFramework.Royale",
27614 + "PresentationUI",
27615 + "ReachFramework",
27618 + // "XamlBuildTask"
27621 const string masterinfos_version = "2.8";
27623 static Uri GetMasterInfoUri (string file)
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));
27629 public static void Init ()
27630 @@ -417,9 +538,13 @@ namespace GuiCompare
27634 - u = GetMasterInfoUri ("masterinfos-4.0.tar.gz");
27635 + u = GetMasterInfoUri ("masterinfos-4.0.tar.gz");
27640 + u = GetMasterInfoUri ("masterinfos-4.5.tar.gz");
27644 u = GetMasterInfoUri ("masterinfos-SL2.tar.gz");
27646 @@ -564,6 +689,8 @@ namespace GuiCompare
27647 main.Title = String.Format ("{0} to {1}", assemblyfile, masterinfo);
27651 + main.SetComparedProfile (profile);
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;
27659 - if (MONO_GAC_PREFIX != null)
27660 + if (!string.IsNullOrEmpty (MONO_GAC_PREFIX))
27661 gac_prefixes = MONO_GAC_PREFIX.Split (':');
27663 MenuItem item = new MenuItem (caption);
27664 @@ -671,12 +798,17 @@ namespace GuiCompare
27668 - public InfoManager (MainWindow main)
27669 + public InfoManager (MainWindow main, string profilePath)
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, ".."));
27679 + monodir = profilePath;
27682 moondir = System.IO.Path.Combine (monodir, @"../moonlight/plugin");
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);
27695 - static string GetVersionPath (string version, string profile)
27696 + string GetVersionPath (string version, string profile)
27698 - if (string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_PATH")))
27699 + if (!monodir.Contains (Path.Combine ("mcs", "class", "lib")))
27702 // Developer's version pointing to /mcs/class/lib/<profile>/
27703 diff --git a/gui-compare/Main.cs b/gui-compare/Main.cs
27704 index 49c4617..e522501 100644
27705 --- a/gui-compare/Main.cs
27706 +++ b/gui-compare/Main.cs
27707 @@ -36,7 +36,7 @@ namespace GuiCompare
27709 Application.Init ();
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
27720 - MainWindow win = new MainWindow ();
27722 + string profile_path = null;
27723 + if (args.Length != 0 && args[0].StartsWith ("--profile-path="))
27724 + profile_path = args[0].Substring (15);
27726 + MainWindow win = new MainWindow (profile_path);
27728 if (args.Length == 2 && File.Exists (args [0]) && File.Exists (args [1])){
27729 win.ComparePaths (args [0], args [1]);
27730 diff --git a/gui-compare/MainWindow.cs b/gui-compare/MainWindow.cs
27731 index 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;
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);
27746 - public MainWindow () : base(Gtk.WindowType.Toplevel)
27747 + public MainWindow (string profilePath) : base(Gtk.WindowType.Toplevel)
27750 notebook1.Page = 1;
27751 @@ -113,7 +114,7 @@ public partial class MainWindow: Gtk.Window
27753 // Configure the GUI
27755 - info_manager = new InfoManager (this);
27756 + info_manager = new InfoManager (this, profilePath);
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
27762 string msdnUrl = n != null ? n.MSDNUrl : null;
27763 if (!String.IsNullOrEmpty (msdnUrl))
27764 - Status = msdnUrl;
27765 + Status = GetMSDNVersionedUrl (msdnUrl);
27767 Status = String.Empty;
27769 @@ -261,7 +262,7 @@ public partial class MainWindow: Gtk.Window
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;
27778 @@ -361,6 +362,22 @@ public partial class MainWindow: Gtk.Window
27779 tag.Underline = Pango.Underline.Single;
27780 buffer.TagTable.Add (tag);
27783 + string GetMSDNVersionedUrl (string url)
27785 + switch (active_profile) {
27787 + return url.Replace (".aspx", "(v=VS.80).aspx");
27789 + return url.Replace (".aspx", "(v=VS.90).aspx");
27791 + return url.Replace (".aspx", "(v=VS.100).aspx");
27793 + return url.Replace (".aspx", "(v=VS.110).aspx");
27799 void InsertWithMarkup (TextBuffer buffer, ref TextIter iter, string text)
27801 @@ -509,6 +526,11 @@ public partial class MainWindow: Gtk.Window
27802 SetTarget (delegate { return new CecilAssembly (cd.TargetPath); });
27805 + public void SetComparedProfile (string profile)
27807 + active_profile = profile;
27810 public void StartCompare (WaitCallback done)
27812 AdditionalInfoWindow.Visible = false;
27813 diff --git a/gui-compare/Makefile.am b/gui-compare/Makefile.am
27814 index 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)))
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)
27823 diff --git a/gui-compare/MasterMetadata.cs b/gui-compare/MasterMetadata.cs
27824 index 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)
27831 + foreach (var entry in props)
27832 + Properties.Add (entry.Key, entry.Value);
27834 if (name == "System.Runtime.CompilerServices.TypeForwardedToAttribute") {
27836 if (props.TryGetValue ("Destination", out dest) && !String.IsNullOrEmpty (dest))
27837 diff --git a/gui-compare/Masterinfo.cs b/gui-compare/Masterinfo.cs
27838 index 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");
27851 + keys.Add (key, name);
27854 LoadExtraData (key, n);
27857 @@ -532,24 +537,10 @@ namespace GuiCompare {
27859 public class XMLAttributeProperties: XMLNameGroup
27861 - static Dictionary <string, string> ignored_properties;
27862 SortedDictionary <string, string> properties;
27864 static XMLAttributeProperties ()
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");
27876 - ignored_properties.Add ("System.ObsoleteAttribute", "Message");
27877 - ignored_properties.Add ("System.IO.IODescriptionAttribute", "Description");
27878 - ignored_properties.Add ("System.Diagnostics.MonitoringDescriptionAttribute", "Description");
27882 @@ -571,15 +562,9 @@ namespace GuiCompare {
27883 if (node.ChildNodes == null)
27888 - if (!ignored_properties.TryGetValue (attribute, out ignored))
27891 foreach (XmlNode n in node.ChildNodes) {
27892 string name = n.Attributes["name"].Value;
27893 - if (ignored != null && ignored == name)
27896 if (n.Attributes["null"] != null) {
27897 Properties.Add (name, null);
27898 @@ -1045,9 +1030,11 @@ namespace GuiCompare {
27900 public override string GetNodeKey (string name, XmlNode node)
27902 - if (genericParameters != null)
27903 - name = name + ":" + genericParameters.Count;
27905 + XmlNode genericNode = node.SelectSingleNode ("generic-parameters");
27906 + if (genericNode != null) {
27907 + name = name + "`" + genericNode.ChildNodes.Count;
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
27913 diff --git a/gui-compare/Metadata.cs b/gui-compare/Metadata.cs
27914 index f365f7c..a04f39e 100644
27915 --- a/gui-compare/Metadata.cs
27916 +++ b/gui-compare/Metadata.cs
27917 @@ -69,6 +69,8 @@ namespace GuiCompare {
27919 public interface ICompMemberContainer
27921 + bool IsSealed { get; }
27923 List<CompNamed> GetInterfaces ();
27924 List<CompNamed> GetConstructors();
27925 List<CompNamed> GetMethods();
27926 @@ -130,27 +132,33 @@ namespace GuiCompare {
27928 public static int Compare (CompNamed x, CompNamed y)
27930 - int res = string.Compare (x.Name, y.Name);
27934 var x_g = x as CompMethod;
27935 var y_g = y as CompMethod;
27937 if (x_g == null || y_g == null)
27939 + return string.Compare (x.Name, y.Name);
27941 var x_tp = x_g.GetTypeParameters ();
27942 + if (x_tp != null && x_tp.Count == 0)
27945 var y_tp = y_g.GetTypeParameters ();
27946 + if (y_tp != null && y_tp.Count == 0)
27949 if (x_tp == null && y_tp != null)
27952 if (x_tp != null && y_tp == null)
27955 - if (x_tp == null && y_tp == null)
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);
27965 + return string.Compare (x.Name, y.Name);
27968 string displayName;
27969 @@ -338,7 +346,10 @@ namespace GuiCompare {
27970 public CompAttribute (string typename)
27971 : base (typename, CompType.Attribute)
27973 + Properties = new SortedDictionary<string, string> ();
27976 + public IDictionary<string, string> Properties { get; private set; }
27979 public abstract class CompGenericParameter : CompNamed, ICompAttributeContainer {
27980 diff --git a/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs b/gui-compare/gtk-gui/GuiCompare.CustomCompare.cs
27981 index 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
27987 private global::Gtk.HBox hbox1;
27989 private global::Gtk.Frame frame1;
27991 private global::Gtk.Alignment GtkAlignment2;
27993 private global::guicompare.ProviderSelector reference;
27995 private global::Gtk.Label GtkLabel4;
27997 private global::Gtk.Frame frame2;
27999 private global::Gtk.Alignment GtkAlignment3;
28001 private global::guicompare.ProviderSelector target;
28003 private global::Gtk.Label GtkLabel9;
28005 private global::Gtk.Button buttonCancel;
28007 private global::Gtk.Button buttonOk;
28010 protected virtual void Build ()
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 ();
28035 diff --git a/gui-compare/gtk-gui/MainWindow.cs b/gui-compare/gtk-gui/MainWindow.cs
28036 index 6e2d738..addb7cd 100644
28037 --- a/gui-compare/gtk-gui/MainWindow.cs
28038 +++ b/gui-compare/gtk-gui/MainWindow.cs
28040 public partial class MainWindow
28042 private global::Gtk.UIManager UIManager;
28044 private global::Gtk.Action File;
28046 private global::Gtk.Action quit;
28048 private global::Gtk.Action Compare;
28050 private global::Gtk.Action Custom;
28052 private global::Gtk.Action a;
28054 private global::Gtk.Action b;
28056 private global::Gtk.Action View;
28058 private global::Gtk.ToggleAction ShowMissing;
28060 private global::Gtk.ToggleAction ShowExtra;
28062 private global::Gtk.ToggleAction ShowPresent;
28064 private global::Gtk.ToggleAction ShowErrors;
28066 private global::Gtk.Action Refresh;
28068 private global::Gtk.ToggleAction ShowTodo;
28070 private global::Gtk.Action RecentComparisonsAction;
28072 private global::Gtk.ToggleAction ShowNotImplemented;
28074 private global::Gtk.Action ToggleRowExpansionAction;
28076 private global::Gtk.VBox vbox1;
28078 private global::Gtk.MenuBar menubar1;
28080 private global::Gtk.Notebook notebook1;
28082 private global::Gtk.ScrolledWindow GtkScrolledWindow;
28084 private global::Gtk.TreeView tree;
28086 private global::Gtk.Label label1;
28088 private global::Gtk.Label label3;
28090 private global::Gtk.Label label2;
28092 private global::Gtk.ScrolledWindow AdditionalInfoWindow;
28094 private global::Gtk.TextView AdditionalInfoText;
28096 private global::Gtk.Expander expander1;
28098 private global::Gtk.Table table1;
28100 private global::Gtk.Label label4;
28102 private global::Gtk.Label label5;
28104 private global::Gtk.Label label6;
28106 private global::Gtk.Label label7;
28108 private global::Gtk.Label label8;
28110 private global::Gtk.Label label9;
28112 private global::Gtk.Image legendImageError;
28114 private global::Gtk.Image legendImageExtra;
28116 private global::Gtk.Image legendImageMissing;
28118 private global::Gtk.Image legendImageNIEX;
28120 private global::Gtk.Image legendImageOK;
28122 private global::Gtk.Image legendImageTODO;
28124 private global::Gtk.VSeparator vseparator1;
28126 private global::Gtk.VSeparator vseparator2;
28128 private global::Gtk.VSeparator vseparator3;
28130 private global::Gtk.Label GtkLabel4;
28132 private global::Gtk.Statusbar statusbar1;
28134 private global::Gtk.ProgressBar progressbar1;
28137 protected virtual void Build ()
28139 global::Stetic.Gui.Initialize (this);
28140 diff --git a/gui-compare/gtk-gui/generated.cs b/gui-compare/gtk-gui/generated.cs
28141 index 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
28147 private static bool initialized;
28150 internal static void Initialize (Gtk.Widget iconRenderer)
28152 if ((Stetic.Gui.initialized == false)) {
28153 @@ -13,12 +13,13 @@ namespace Stetic
28159 internal class BinContainer
28161 private Gtk.Widget child;
28163 private Gtk.UIManager uimanager;
28166 public static BinContainer Attach (Gtk.Bin bin)
28168 BinContainer bc = new BinContainer ();
28169 @@ -27,32 +28,32 @@ namespace Stetic
28170 bin.Added += new Gtk.AddedHandler (bc.OnAdded);
28175 private void OnSizeRequested (object sender, Gtk.SizeRequestedArgs args)
28177 if ((this.child != null)) {
28178 args.Requisition = this.child.SizeRequest ();
28183 private void OnSizeAllocated (object sender, Gtk.SizeAllocatedArgs args)
28185 if ((this.child != null)) {
28186 this.child.Allocation = args.Allocation;
28191 private void OnAdded (object sender, Gtk.AddedArgs args)
28193 this.child = args.Widget;
28197 public void SetUiManager (Gtk.UIManager uim)
28199 this.uimanager = uim;
28200 this.child.Realized += new System.EventHandler (this.OnRealized);
28204 private void OnRealized (object sender, System.EventArgs args)
28206 if ((this.uimanager != null)) {
28207 @@ -65,14 +66,14 @@ namespace Stetic
28213 internal class ActionGroups
28215 public static Gtk.ActionGroup GetActionGroup (System.Type type)
28217 return Stetic.ActionGroups.GetActionGroup (type.FullName);
28221 public static Gtk.ActionGroup GetActionGroup (string name)
28224 diff --git a/gui-compare/gtk-gui/gui.stetic b/gui-compare/gtk-gui/gui.stetic
28225 index ce143e5..da239dc 100644
28226 --- a/gui-compare/gtk-gui/gui.stetic
28227 +++ b/gui-compare/gtk-gui/gui.stetic
28229 <?xml version="1.0" encoding="utf-8"?>
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>
28238 <widget-library name="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
28239 diff --git a/gui-compare/gtk-gui/guicompare.ProviderSelector.cs b/gui-compare/gtk-gui/guicompare.ProviderSelector.cs
28240 index 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
28246 private global::Gtk.Table table2;
28248 private global::Gtk.FileChooserButton filechooserbutton1;
28250 private global::Gtk.FileChooserButton filechooserbutton2;
28252 private global::Gtk.Label label2;
28254 private global::Gtk.RadioButton radiobutton1;
28256 private global::Gtk.RadioButton radiobutton2;
28259 protected virtual void Build ()
28261 global::Stetic.Gui.Initialize (this);
28262 diff --git a/gui-compare/gui-compare.csproj b/gui-compare/gui-compare.csproj
28263 new file mode 100644
28264 index 0000000..33408f6
28266 +++ b/gui-compare/gui-compare.csproj
28268 +<?xml version="1.0" encoding="utf-8"?>
28269 +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
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>
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>
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>
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>
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>
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" />
28405 + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
28407 + <Folder Include="cm\" />
28410 \ No newline at end of file
28411 diff --git a/gui-compare/gui-compare.in b/gui-compare/gui-compare.in
28412 index 456a9fa..aa39b8f 100644
28413 --- a/gui-compare/gui-compare.in
28414 +++ b/gui-compare/gui-compare.in
28418 +export DYLD_FALLBACK_LIBRARY_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib:/usr/lib
28420 exec mono $MONO_OPTIONS "@prefix@/lib/gui-compare/gui-compare.exe" "$@"