Suppress Console.WriteLine for portion of program - c#

For some reason unknown to me, the developer of a library I am using has decided to Console.WriteLine tons of information whenever a method is called within the library, essentially explaining every step of what is going on.
This is fine, but during development I don't need to be seeing this all of the time, so my question is can I suppress Console.WriteLine from being used when I don't want it to be? I still wish to be able to see my own Console.WriteLines, but not the ones within the Library.
Goes without saying I do not have source for the library.
Regards,
AK

You can use Console.SetOut to redirect Console.Out to something of your choosing (e.g. something that discards all input) before calling into that library and then do the same to set the original value back. It's going to be awkward to do that all the time though.
To make things a bit more manageable, you can create another class that implements IDisposable and use it like this:
using(new StandardOutSink()) {
// call into the third party library
}
The constructor of StandardOutSink (which you need to write) would redirect the output stream to a specially-crafted TextWriter (which you also need to write) and then the Dispose method would set it back to the original stream.

Related

Is there a way to tell if a method has a call path to another method?

Say I have a very high level method A and I just want to know if there is a some way down the call stack a reference to method B but don't know (yet) the input data required to actually hit method B. Is there a quick way of determining this without debugging or jumping through all the possible call stacks?
A code map might help - have a look at this article. You need Enterprise for the built in one though. Alternatively, you could try this; I've not used it but it seems to do a similar thing.

How do I get an instance of IVsExpansionClient in VSPackage?

Documentation for extending Visual Studio is virtually nonexistent, and I managed to assemble a few lines of functioning code hacked together from a dozen or more obscure sources around the interwebs before crashing into a brick wall.
All I need to do is subscribe to an event that is fired after a snippet is inserted. Sounds easy enough, or so I thought. Almost immediately into my research I stumbled upon the following morsel:
IVsExpansionClient.OnAfterInsertion
That describes perfectly my intention, so this MUST be the answer! After looking around my SDK assemblies for longer than I would like to admit, I finally ended up yanking the assembly (Microsoft.VisualStudio.TextManager.Interop.8.0.dll) out of my GAC so that I could reference it explicitly in my solution.
Now that I have access to the interface, I just need to figure out how to get an instance of it.
IVsExpansionManager
Ah HA! That MUST somehow provide me with a mechanism for obtaining an instance of IVsExpansionClient, right? Well, not exactly. At least not in a way that I can see. I have stitched together the following code:
IVsExpansionManager expansionManager = null; IVsTextManager2
textManager =
(IVsTextManager2)Package.GetGlobalService(typeof(SVsTextManager)); int
manager = textManager.GetExpansionManager(out expansionManager);
Which gives me a IVsExpansionManager COM object, but that is about as far as I can get.
I have taken notice of another potential provider:
IVsExpansionEvents
I thought perhaps like solution events, document events, window events or text events, I might be able to invoke DTE to hook these events, but they appear to be absent.
There are methods that accept IVsExpansionClient as a parameter such as:
IVsExpansion.InsertNamedExpansion
So there simply must be a way to fetch an instance of this object, right? I suppose it's possible to create my own class that implements the IVsExpansionClient interface, but I wouldn't know where to begin with implementing the interface members, and I still wouldn't know how to instantiate it in a meaningful way within my package.
I am grateful to anyone who can point me in a different direction, or provide a working sample that I can adapt for my needs. Thanks for taking the time to read through this, I appreciate your time.
EDIT: I want to receive a notification that a snippet has been inserted into the active document window. Ideally, I would like the snippet itself to be included in the delegate event args, as I have some processing to do on the inserted snippet...and it would be cumbersome to process the entire document, or try to identify the recently inserted snippet without context.
Maybe you want to explain what you actually want to achieve. The documentation of the IVsExpansionClient interface states:
Notes to implementers
This interface is implemented by a VSPackage that supports insertion of code snippets.
I don´t see why one would like to consume an instance of it, because it´s an interface allowing the package to receive notifications/callbacks, if something related to code-snippets is going to happen (it provides nohting else than callback functions).
It states furthermore...
Notes to Callers
This interface is instantiated and passed to the InvokeInsertionUI method in the IVsExpansionManager interface. This interface is also instantiated and passed to the methods in the IVsExpansion interface.

Will the compiler only compile code that can get executed?

I have a class library and am using only part of it. Is there a need to delete what isn't being used in order to shrink the size of the created code (in release configuration)?
As far as I've seen, the compiler takes care of that, and removing the code doesn't change the EXE file size. Will this always be true? Removing all unneeded code would take very long, so I want to know if there's need for that.
More information: there are methods and classes in the class library that aren't called from the executing code, but are referenced by other parts of code in the class library (which themselves are never called).
No, the compiler includes the "dead" code as well. A simple reason for this is that it's not always possible to know exactly what code will and won't be executed. For example, even a private method that is never referenced could be called via reflection, and public methods could be referenced by external assemblies.
You can use a tool to help you find and remove unused methods (including ones only called by other unused methods). Try What tools and techniques do you use to find dead code? and Find unused code to get you started.
It all gets compiled. Regardless of whether it is called or not. The code may be called by an external library.
The only way to make the compiler ignore code is by using Compiler Preprocessor Directives. More about those here.
I doubt the compiler will remove anything. The fact is, the compiler can't tell what is used and what is not, as types can be instantiated and methods called by name, thanks to reflection.
Let's suppose there is a class library called Utility. You created a new project and added this class library to that project. Even if your EXE calls only 1-2 methods from the class library, it's never a good idea to delete the unreferenced code.
It would go against the principle of reusablity. Despite the fact that there would be some classes present in the library unreferenced from the EXE, it would not have any bad impact on performance or size of the program.
Determining all and only dead code is (if one makes the idealization that one has a "math world" like language) recursively undecidable, in most languages. (A few rare ones like the Blaise language are decidable.)
to the question of whether there is a "need to delete what isn't being used in order to shrink the size of the created code": i think this would only be useful to save network bandwidth. removing unused code is crucial in web applications to improve loading speeds etc.
if you're code is an exe or a library, the only reason i see to remove dead code, is to improve your code quality. so that someone looking at your code 2 years down the line won't scratch their heads wondering what it does.

Is there an equivalent to Java's ClassFileTransformer in .NET? (a way to replace a class)

I've been searching for this for quite a while with no luck so far. Is there an equivalent to Java's ClassFileTransformer in .NET? Basically, I want to create a class CustomClassFileTransformer (which in Java would implement the interface ClassFileTransformer) that gets called whenever a class is loaded, and is allowed to tweak it and replace it with the tweaked version.
I know there are frameworks that do similar things, but I was looking for something more straightforward, like implementing my own ClassFileTransformer. Is it possible?
EDIT #1. More details about why I need this:
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place.
I know how to do this (except for the part where I need to be invoked to replace the class): for every method whose code I want to monitor, I must:
Get the method's MethodBody using MethodBase.GetMethodBody()
Transform it to byte array with MethodBody.GetILAsByteArray(). The byte[] it returns contains the bytecode.
Analyse the bytecode as explained here, possibly inserting new instructions or deleting/modifying existing ones by changing the contents of the array.
Create a new method and use the new bytecode to create its body, with MethodBuilder.CreateMethodBody(byte[] il, int count), where il is the array with the bytecode.
I put all these tweaked methods in a new class and use the new class to replace the one that was originally going to be loaded.
An alternative to replacing classes would be somehow getting notified whenever a method is invoked. Then I'd replace the call to that method with a call to my own tweaked method, which I would tweak only the first time is invoked and then I'd put it in a dictionary for future uses, to reduce overhead (for future calls I'll just look up the method and invoke it; I won't need to analyse the bytecode again). I'm currently investigating ways to do this and LinFu looks pretty interesting, but if there was something like a ClassFileTransformer it would be much simpler: I just rewrite the class, replace it, and let the code run without monitoring anything.
An additional note: the classes may be sealed. I want to be able to replace any kind of class, I cannot impose restrictions on their attributes.
EDIT #2. Why I need to do this at runtime.
I need to monitor everything that is going on so that I can detect every access to data. This applies to the code of library classes as well. However, I cannot know in advance which classes are going to be used, and even if I knew every possible class that may get loaded it would be a huge performance hit to tweak all of them instead of waiting to see whether they actually get invoked or not.
POSSIBLE (BUT PRETTY HARDCORE) SOLUTION. In case anyone is interested (and I see the question has been faved, so I guess someone is), this is what I'm looking at right now. Basically I'd have to implement the profiling API and I'll register for the events that I'm interested in, in my case whenever a JIT compilation starts. An extract of the blogpost:
In your ICorProfilerCallback2::ModuleLoadFinished callback, you call ICorProfilerInfo2::GetModuleMetadata to get a pointer to a metadata interface on that module.
QI for the metadata interface you want. Search MSDN for "IMetaDataImport", and grope through the table of contents to find topics on the metadata interfaces.
Once you're in metadata-land, you have access to all the types in the module, including their fields and function prototypes. You may need to parse metadata signatures and this signature parser may be of use to you.
In your ICorProfilerCallback2::JITCompilationStarted callback, you may use ICorProfilerInfo2::GetILFunctionBody to inspect the original IL, and ICorProfilerInfo2::GetILFunctionBodyAllocator and then ICorProfilerInfo2::SetILFunctionBody to replace that IL with your own.
The great news: I get notified when a JIT compilation starts and I can replace the bytecode right there, without having to worry about replacing the class, etc. The not-so-great news: you cannot invoke managed code from the API's callback methods, which makes sense but means I'm on my own parsing the IL code, etc, as opposed to be able to use Cecil, which would've been a breeze.
I don't think there's a simpler way to do this without using AOP frameworks (such as PostSharp). If anyone has any other idea please let me know. I'm not marking the question as answered yet.
I don't know of a direct equivalent in .NET for this.
However, there are some ways to implement similar functionality, such as using Reflection.Emit to generate assemblies and types on demand, uing RealProxy to create proxy objects for interfaces and MarshalByRefObject objects. However, to advise what to use, it would be important to know more about the actual use case.
After quite some research I'm answering my own question: there isn't an equivalent to the ClassFileTransformer in .NET, or any straightforward way to replace classes.
It's possible to gain control over the class-loading process by hosting the CLR, but this is pretty low-level, you have to be careful with it, and it's not possible in every scenario. For example if you're running on a server you may not have the rights to host the CLR. Also if you're running an ASP.NET application you cannot do this because ASP.NET already provides a CLR host.
It's a pity .NET doesn't support this; it would be so easy for them to do this, they just have to notify you before a class is loaded and give you the chance to modify the class before passing it on the CLR to load it.

C# code re-use via namespaces

I like to create a file full of custom functions which I have made, which I may use in another project or something. Now I don't fully understand how to go about this, normally in a language like php, you'd just create the php file and then go include("cust_lib.php") or whatever the file is called.
Now I think that the process involves the library having its own namespace, then either go using custom_lib; or custom_lib:: within the script (I don't want to get into a discussion over which is the best way to go here).
Is this right? Or should I create the library and convert it to a .dll, if so how do I go about this, what sort of syntax does a dll have inside it etc.
However if its just file within one project then I don't need to go down that route do I? I can just create the namespace and use that?
This is what I'm working for at the moment, and thought it would be something like this
namespace Custom_Lib{
~~functions to go here~~
}
However the functions have to exist within a class don't they? So that becomes something like
namespace Custom_Lib{
class custom_lib{
public string function1(string input){
return input;
}
}
}
So some help, pointers, examples would be appreciated so I can wrap my head around this
Thanks,
Psy.
(Yes I call them functions, that just comes from a long php/js etc background)
The normal approach would be to create a Class Library project, put your classes and methods in that project, making sure that those you want to expose are public. Then you add a reference to the resulting dll file in the client projects and you will have the functionality from the class library available to you.
Even if you decide to put it all into one single file, I would still recommend you to make it a class library since I imagine that will make it easier to maintain. For instance, consider the following scenarios:
You decide to put it in a file and include a copy of that file in all projects where you want to use it. Later you find a bug in the code. Now you will have a number of copies of the file in which to correct the bug.
You decide to put it in a file and include that same file in all projects. Now, if you want to change some behaviour in it, you will alter the behavior for all projects using it.
In those two cases, keeping it as a separate project will facilitate things for you:
You will have only one copy of the code to maintain
You can decide whether or not to update the dll used by a certain project when you make updates to the class library.
Regarding the syntax issues: yes all methods must exist within a class. However, if the class is merely a container of the methods, you can make it (and the methods static):
public static class CustomLib
{
public static string GetSomethingInteresting(int input)
{
// your code here...
}
}
That way you will not need to create an instance of CustomLib, but can just call the method:
string meaningOfLife = CustomLib.GetSomethingInteresting(42);
In addition to Fredrik Mörk's well-written and spot-on response, I'd add this:
Avoid creating a single class that is a kitchen-sink collection of functions/methods.
Instead, group related methods into smaller classes so that it's easier for you and consumers of your library to find the functionality they want. Also, if your library makes use of class-level variables, you can limit their scope.
Further, if you decide later on to add threading capabilities to your library, or if your library is used in a multi-threaded application, static methods will likely become a nightmare for you. This is a serious concern, and shouldn't be overlooked.
There no question here. You answered it yourself. Yes, you have to construct a class to include all helper methods. And yes, you can either compile it to a dll if you want to reuse in multiple projects it or just add the source file to the project.
Usually I declare the helper class and all functions as static to avoid initiating the class each time I use it.

Categories

Resources