Fix for google-code-prettify w/ c# - c#

Prettify gives types and methods the same class when tokenizing c# so they are colored the same. This is because methods are pascal case in c# instead of camel case like in java. This affects my blog and all stackoverflow c# code since they use prettify too.
Does anyone have a fix for this?
If not, you can at least star/vote the official bug that was reported in Mar/2009 so the authors take another look.

It is possible for identical syntax to have different meanings. There just isn't enough information to properly syntax highlight everything.
Take a look at this example:
static class Program
{
class Foo { public class Bar { public static void Func() { } } }
class Foo2 { public static Baz Bar2 { get; set; } }
class Baz { public void Func2() { } }
static void Main()
{
Foo.Bar.Func();
Foo2.Bar2.Func2();
}
}
In the first line, Bar is an inner class, and should be highlighted green. In the second line, Bar2 is a property of type Foo2, and should be highlighted black. Both Func and Func2 are functions, and should be highlighted black.
Here's how Visual Studio highlights that code.

I actually wrote my own syntax highlighting library to solve problems like this. It's pretty similar to prettify but you have to specify the language explicitly.
Website
Demo

The problem is that without context, it's impossible to find out whether it's a method or a type.
Take the following example:
var value = new Test();
Test();
This example instantiates a new Test and then calls the method Test. The only way to find out which is a class and which is a type is by having 1. the entire code base and 2. a compiler.
And then I haven't even touched invalid code.
That being said, I think that the current prettifier as used by SO does a terrific job of highlighting the code samples without any context whatsoever.

TextMate (OS X) or E-TextEditor (Windows)
TextMate/E-TextEditor will generate HTML & CSS from syntax highlighting for many, many languages.
Here is what you do:
Open the file in TextMate/E-TextEditor
Select the language from the menu at the bottom of the screen if it doesn't choose it automatically
Go to Bundles->TextMate->Create HTML From Document
This will create all the HTMl/CSS in a new document.
Note: Windows users also choose the 'TextMate' bundle (not 'E-TextEditor')
Profit!
Note: You will have to install the C# bundle for C# syntax (every other common language is included). To do this, install the "Get Bundles" bundle, and use that to install the C# bundle.
EDIT: Reading the comments I realized TextMate is only a solution for Mac users. Sometimes I forget about Windows.
You can also use E-TextEditor for Windows. The steps are the same.

Related

Find usages of a generic class with specific constraint

As per title, how can I find usages of the method Process for Processor<int> rather than Processor<string>?
internal class Program
{
private static void Main()
{
var processorInt = new Processor<int>();
var processorString = new Processor<string>();
processorInt.Process();
processorString.Process();
}
}
internal class Processor<T>
{
public void Process() => Console.WriteLine(typeof(T).Name);
}
ReSharper can handle this out of the box. If you try to perform a search for references, it'll actually ask you what you want to look for. Just declare a dummy variable of the type you want to look for, and call Find Usages, on the type name.
Note that this works for generic classes and generic methods, but it won't help you if you're looking for usages of a method in a generic class with a given type parameter.
Or just use Right click -> Find usages advanced:
You can't using standard tools.
You either have to:
Press Ctrl+K, Ctrl+R to find all references to Processor<T>.
Visually filter on Processor<int> yourself.
Or:
Find all using text search on Processor<int>. This is not very useful when you have SomeOtherProcessor<int> too, since that would match too.
This are the only options I have come up with. Other developer tools, like Resharper, might have an option that is better.
I fear the only way to achieve this is by directly searching for Processor<int>() within the search-and-replace-tool. Quite annoying though. However this won´t help ypu much if your generic class has a generic interface-parameter instead of a struct or class. Thus you cannot search for usages of Processor<MyInterface>() when you are interested on occurences of all Processor with a generic parameter of that interface.
You can use my tool built with Roslyn APIs:
https://github.com/UnoSD/SubTypeReferencesAnalysis

How to Move a class to another dll and change the namespace without altering the method usage

I have a dll where I have one class which logs to a "channel", another Program listens to the "channel" and writes the logs to the screen.
The problem with the dll is that its grown over time and now there are many dependecies in it. I want to remove the logging part from this dll and place it in a debugging and logging dll.
The problem is that the debugging and logging dll has another namespace which I want to use in the class or rather I want to use the class in the namespace. My problem with this is that some developers used the namespace nearly exclusively when calling the methods instead of using it in the top of their classes.
It looks like the following for a static method:
Base.Manager.Logging.Send("Log something");
The other Dll has the simple namespace Trace
so it should look like this:
Trace.Logging.Send("Log something");
My question is, is there an elegant way to move the class and change the namespace without altering all the uses of the Methods ?
I could simply copy the class to the other dll and then use the old class as a wrapper which forwards all the calls to the other class in the Trace.dll but this approach seems a little bit hacky.
I hope this grafik illustrates what I mean because I think the simple text may be somewhat confusing
FYI: I don't have ReSharper
Unfortunately you can't. If you keep same namespace then you can use TypeForwardAttribute but if you also change namespace (not just assembly) then it doesn't work.
What I suggest is to move it to new class, keep old class to don't break code both at run-time & compile-time and forward all calls. Mark all old methods as obsolete (at least they'll be warned that code will change in future). Just to clarify:
namespace Base.Manager {
public static class Logger {
public static void Send(string message) {
// Do things
}
}
Step 1: empty your old deprecated class and forward calls to new class. Mark old methods as obsolete.
Will then be refactored to:
namespace Base.Manager {
[EditorBrowsable(EditorBrowsableState.Never)]
public static class Logger {
[Obsolete("This method is deprecated, please use Trace.Logger.Send")]
public static void Send(string message) {
// Delegate work to someone else...
Trace.Logger.Send(message);
}
}
It'll generate a warning (with given message) during compilation. Compile-time compatibility is saved. Note we also added EditorBrowsableAttribute, IntelliSense won't propose that Logger class when they start typing. This reduces (little bit) chances they will still use Base.Manager.Logger for new code.
Step 2: someday in future you'll change that warning to an error:
[Obsolete("This method is obsolete, use Trace.Logger.Send", true)]
This will break compilation but it'll preserve binaries compatibility. Other DLLs will still run (so you don't have to wait other developers complete this refactoring task) but they won't be able to compile unless they update.
Step 3: when all has been done and everyone moved to new class then simply remove Base.Manager.Logger class from your code.
Notes: that all process can be spanned across various releases: in 2.0 you deprecate old methods, in 2.1 you break compilation, in 3.0 you remove it from your code (this is especially useful if releases of your code and its users aren't in sync).
Just a word about name collisions: be aware that same class name (and methods) in two different namespace may lead to annoying name collisions. Imagine they have this code:
using Base.Manager;
void DoSomething() {
Logger.Send("I'm doing something.");
}
After your change (until Base.Manager.Logger isn't removed) they can't simply add another using:
using Base.Manager;
using Trace;
void DoSomething() {
Base.Manager.SomethingElse.DoIt();
// Compiler is confused: Base.Manager.Logger or Trace.Logger?
Logger.Send("I'm doing something.");
}
They need to full qualify which logger class they want to use:
Trace.Logger.Send("I'm doing something.");
Warning: be aware that if Trace isn't a new namespace then name collision may even break compilation immediately if they had both usings in their code (making ObsoleteAttribute useless).
If it's an issue or not for you/your users...I can't say.

C# attribute formatting conventions

Lately I've seen attribute tags formatted into two ways in C# (even in the official microsoft guide):
[foo]
public class bar {...}
and
[foo] public datatype bar;
Is there any advantage to where the tag is placed? Should the tag be placed in a certain position based on whether it is over a class or a datatype?
it's personal preference, it's not going to make any difference to the compiler, pick one and be consistent.
That said, I prefer the 1st format in both cases because it's possible to have multiple attributes on both classes and datatypes - and I find it easier to read spread out.
it would get messy quickly if you did that in-line.
take the following sample code for a class for example:
[Author("P. Ackerman", version = 1.1)]
[Author("R. Koch", version = 1.2)]
class SampleClass
{
// P. Ackerman's code goes here...
// R. Koch's code goes here...
}
putting it inline just makes it unreadable.

In C#, what is a good way to exclude a class when outputting code from textfile

What I want to do may seem like a weird scenario. Please keep in mind that I need to do this for a Demo project, where I output c# code to the user to teach them how certain controls are coded.
I am given a .cs file and I need to output the contents. There is at least one class in the file, and at most...a lot. I need to output the whole file, EXCEPT one type of class. The specific type of class that I want to prevent being outputted all inherit a certain base class, so they should be easy to distinguish.
Here is an example:
public abstract class A{}
public class B{]
public class C{}
Assume these are the base-types that some of my classes may inherit. I want to prevent outputting all classes that inherit from A. A is probably going to be the only abstract base class so if that can help in anyway, that would be awesome.
Let's say I'm given a file, example.cs:
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
And the output should be
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
The only way I have thought of is brute-force string manipulation. I can't, however, use whitespace as a separator between classes because there is no guarantee if there will even be white space between classes. I will need to keep track of open and closed curly brackets to discover where one class begins and another end. I also need to test for the base class of each class by testing the string tokens before the first {} pair.
Also I need to prevent the attributes of AA from outputted too.
Since there are many brighter minds out there, I am here to ask if there is another simpler/cleaner method for doing what I need.
Thanks for reading!
Edit after YetAnotherUser's answer: The output should be exactly the same as the file, which includes all comments.
Another edit: Instead of answering with certain software or libraries that could do this, I would more prefer algorithms. Maybe regular expressions? I am not good with them so I do not know the extend that they can be used for.
Could you wrap everything you need to exclude with:
#region ExcludeRegion
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
#endregion
See the #region documentation
This should be relatively easy to scan for and exclude. It also gives you the added benefit of showing what you're hiding in the IDE.
You can try to use open-source lib NRefactory. It supports parsing the code into AST which you can modify afterwards and generate output code. It also can retain your comments as shown on their wiki page.
Found it here: An alternative for "CSharpCodeProvider.Parse"
Update: Apparently there's no implementation of CodeDomProvider that supports parsing. Hence this is invalid - I'll keep this post to ensure this is highlighted to someone thinking on same lines.
You can parse the code using CodeDomProvider and then remove the required classes and regenerate the code file.
If it is for educational purpose, this might not exactly fit your needs as generated file might not exactly match with the original source file.
See -
System.CodeDom Namespace
Using the CodeDOM
Microsoft .NET CodeDom Technology - Part 1

Find usage of a particular method when called with a particular subtype

I'm refactoring the nasty out of a largeish codebase and need to find where a particular method, accepting instances of a fairly general interface, is called with a particular implementation of that interface.
For example, in the NastyStatic is the DoBadThings(IBusinessObject) method. I have about 50 classes that implement IBusinessObject in my business library, including DontHurtMe : IBusinessObject.
How can I find every call to NastyStatic.DoBadThings(foo), but only where foo is an instance of DontHurtMe?
EDIT: I'm after some sort of static analysis tool. Setting a dynamic watch in DoBadThings (or similar) and running the application isn't really an option. It will already throw an exception due to changes I've made to DontHurtMe, and there are far too many code paths to find all usages that way (at least until it goes live and my users start complaining).
Easy. Write an overload of DoBadThings that takes a DontHurtMe as a parameter. Now see where it's called. This won't detect the cases where the method is called with a declared IBusinessObject that happens to be a DontHurtMe - but I don't think static analysis can detect that. This gets all the calls of your method with a declared DontHurtMe.
ReSharper 5's Structural Search can do this. Supposing the following code:
class Program
{
static void Main(string[] args)
{
var hm = new HurtMe();
var dhm = new DontHurtMe();
DoBadThings(hm);
DoBadThings(dhm);
}
static void DoBadThings(IBusinessObject ibo) { }
}
interface IBusinessObject { }
class DontHurtMe : IBusinessObject { }
class HurtMe : IBusinessObject { }
Now, as noted, a R# Find Usages on DoBadThings, no matter what options we specify, will find both the invocations in Main.
But if we
Go to ReSharper | Find | Search with Pattern....
Add Placeholder | Expression, name it dhm and specify DontHurtMe as the type
In Search pattern, type DoBadThings($dbm$)
Click Find
we get in our results only the invocation of DoBadThings on the object with type statically identifiable as a DontHurtMe, and not the invocation on a HurtMe.
I do like the neatness of the procedure offered by #Carl Manaster, but this way gives an option for when you can't overload the method in question.
I can't come up with solution for static analysis. I just re-examined the options of ReSharper's "Find usages advanced..." and didn't find anything. You could put a condition breakpoint on this method with a condition like foo is DontHurtMe, but I suppose you know that already and it's better suited for the cases when you try to locate a bug than for refactoring purposes.

Categories

Resources