In my program, I need Memory Scanner. I've used this one: http://www.codeproject.com/Articles/716227/Csharp-How-to-Scan-a-Process-Memory
I've created a new C# file named MemoryScanner.cs and copied the code there.
How to run it from here:
private void startButton_Click(object sender, EventArgs e)
{
//here I would like to invoke the MemoryScanner
}
Thanks in advance for every help. :)
Apparently (from looking at the code of the link your provided), the entry point of the program is the static method Main in class Program in namespace MemoryScanner. Call this method to start the code.
Some points should be noted:
The implementation is left as an exercise. (If you really don't know how to call a static method in C#, please start with a good, basic C# tutorial.)
Currently, the code analyzes a process called notepad, outputs the result to dump.txt and waits for Console entry before returning. If you want to use that as part of your program, you will need to change these things. (Hint: Remove the Console parts and pass the values, which are currently hard-coded, as method parameters.)
In a nutshell: If you want to use the code, you won't get around reading and (at least partly) understanding it.
You need to add a using statement at the top of your page.
using MemoryScanner;
I am building a logging control for a C# project and would like to be able to call it with the name of the current source code File, Line, Class, Function, etc. PHP uses "magic constants" that have all of this info: http://php.net/manual/en/language.constants.predefined.php but I don't see anything like that in the C# compiler language.
Am I looking for something that doesn't exist?
Using the StackTrace/StackFrame classes, you can have your control find out where it's been called from, rather than passing it that information:
private static StringBuilder ListStack(out string sType)
{
StringBuilder sb = new StringBuilder();
sType = "";
StackTrace st = new StackTrace(true);
foreach (StackFrame f in st.GetFrames())
{
MethodBase m = f.GetMethod();
if (f.GetFileName() != null)
{
sb.AppendLine(string.Format("{0}:{1} {2}.{3}",
f.GetFileName(), f.GetFileLineNumber(),
m.DeclaringType.FullName, m.Name));
if (!string.IsNullOrEmpty(m.DeclaringType.Name))
sType = m.DeclaringType.Name;
}
}
return sb;
}
(I used this code to get the call stack of the currently executed method, so it does more than you asked for)
The StackTrace/StackFrame classes will give you quite a bit of this, though they can be quite expensive to construct.
You can ask the system for a stack trace, and you can use reflection. Details are coming.
__LINE__
__FILE__
__DIR__
__FUNCTION__ (does not really exist in C#)
__CLASS__
__METHOD__
__NAMESPACE__
This is a start:
http://www.csharp-examples.net/reflection-callstack/
http://www.csharp-examples.net/reflection-calling-method-name/
Assembly.GetExecutingAssembly().FullName
System.Reflection.MethodBase.GetCurrentMethod().Name
You will get better information in Debug (non-optimized) build. PhP might always have access to all that stuff, but it ain't the fastest gun on this planet. Play with it and let me know what is missing.
There are methods to get this type of data. It depends on what data you want.
__CLASS__ : If you want the current classname you'll need to use reflection.
__LINE__ : I'm not sure what "The current line number of the file" means, I'll take a guess and say it's how many lines in the file. That can be done by opening the file and doing a line count. This can be done via the File class, the FileInfo class may also work.
__DIR__ :Getting the directory of the file is done by using the DirectoryInfo class.
__FUNCTION__ and __METHOD__: Function name (method name), this can be retrieved via reflection.
__NAMESPACE__ :Namespace an be retrieved via reflection
Using Type, the best you can really do is get information about the current class. There is no means to get the file (though you should generally stick to one class per file), nor line number, nor function using Type.
Getting a type is simple, for example, this.getType(), or typeof(MyClass).
You can get the more specific details by generating a StackTrace object and retrieving a StackFrame from it, but doing so repeatedly is a bad idea.
I think a more important question is perhaps: why do you need them? For trace debugging, your output is supposedly temporary, so whether it reflects an accurate line number or not shouldn't matter (in fact, I rarely ever include a line number in trace debugging). Visual Studio is also very useful as a true step debugger. What do you really need File, Class, Function, and Line Number for?
Edit: For error checking, use exceptions like they're meant to be used: for exceptional (wrong) cases. The exception will generate a stack trace pointing you right at the problem.
Many of the previous responders have provided excellent information; however, I just wanted to point out that accessing the StackFrame is exorbitantly expensive and probably shouldn't be done except for special cases. Those cases being an extremely chatty verbose mode for debugging corner cases or error logging and for an error you probably already have an Exception instance which provides the StackTrace. Your best performance will be as Bring S suggested by using Type. Also as another design consideration logging to the console can slow your application down by several orders of magnitude depending on the volume of data to display. So if there is a console sink having the writer operating on a worker thread helps tremendously.
I got one problem while doing one TAPI application based project in C#. I'm using ITAPI3.dll
My problem is.. i'm not getting incoming call information. To get the incoming call information, i'm using the get_callinfo function, but it is showing empty message.
Did you try a different modem?
TAPI is very hardware dependent
This might be a useful MSDN starting point:
http://msdn.microsoft.com/en-us/library/ms726262%28VS.85%29.aspx
(if you didn't already have that url)
I'm just experiencing the same problem. When i debug, a openfiledialog opens asking me to open a file. i'm no sure what it is right now, will get back when i find something. So i just skips the line of code, what causes it to be empty.
I found what was causing the problem for me :
get_callInfo has 3 constructors : one returning object, one returning int and one returning string. For some reason, the one returning object is failing. So i tried the string constructor. This gave me all the information i need. I'll give an overview of all attributes you can choose from :
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLEDIDNUMBER);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLEDIDNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLEDPARTYFRIENDLYNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNUMBER);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLINGPARTYID);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_COMMENT);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CONNECTEDIDNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_CONNECTEDIDNUMBER);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_DISPLAYABLEADDRESS);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_REDIRECTINGIDNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_REDIRECTINGIDNUMBER);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_REDIRECTIONIDNAME);
e.Call.get_CallInfo(CALLINFO_STRING.CIS_REDIRECTIONIDNUMBER);
hope this still helps
I am getting the following error:
Error 49 No overload for method 'getData' takes '1' arguments
With this method on the 5th line.
[WebMethod]
public string getVerzekerde(int bsn)
{
ZDFKoppeling koppeling = new ZDFKoppeling();
return koppeling.getData(bsn);
}
The getData method looks like this:
public string getData(int bsn)
{
using (new SessionScope())
{
ZorgVerzekerde verzekerde = PolisModule.GetVerzekerde(bsn);
return "Verzekerde " + verzekerde.Naam;
}
}
I realy don't understand what is going wrong here.. The description of this error on the msdn site didn't help me.. http://msdn.microsoft.com/en-us/library/d9s6x486%28VS.80%29.aspx
Someone who has a solution?
Yeah; somehow you're compiling against a different version of that class. Do a clean build, and double check your references.
Put an error in the GetData() method, then do a full build and confirm that the compiler find the errors. You may be editing the wrong file if you have more then one copy of the source code on your machine, and this will show you if you are.
Also try renaming the ZDFKoppeling class without updating getVerzekerde() and check you get a compiler error. If not you are not picking up the changed class for some reason.
If the above does not give a compiler error, try a rebook, as a process my have the dll locked, and also try a complete rebuild.
These problems normally turn out to be very simple once you have tracked them down. But get take forever to track down.
If another programmer works in the same office, ask for his/her help, as often a 2nd set of eye on the machine can find it quickly.
(I am assuming that GetData() is defined in the ZDFKoppeling class, not some other calss)
This generally indicates that it's not referencing the method you thought it was, but instead a different one. You can generally find out what method that is in Visual Studio by right clicking the method call and selecting "Go to definition". This should help work out why it's calling the one it is and not the one you expect.
Where is the getData method defined? Is it in another assembly? Have you tried rebuilding?
It doesn't look like anything's wrong with your the code.
In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :)
I am using C#.
Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it).
Public Module ClassBreak
Public Sub BreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim sel As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Dim editPoint As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
Dim classElem As EnvDTE.CodeElement = editPoint.CodeElement(vsCMElement.vsCMElementClass)
If Not classElem Is Nothing Then
For Each member As EnvDTE.CodeElement In classElem.Children
If member.Kind = vsCMElement.vsCMElementFunction Then
debugger.Breakpoints.Add(member.FullName)
End If
Next
End If
End Sub
End Module
Edit: Updated to add breakpoint by function name, rather than file/line number. It 'feels' better and will be easier to recognise in the breakpoints window.
You could start by introducing some sort of Aspect-Oriented Programming - see for instance
this explanation - and then put a breakpoint in the single OnEnter method.
Depending on which AOP framework you choose, it'd require a little decoration in your code and introduce a little overhead (that you can remove later) but at least you won't need to set breakpoints everywhere. In some frameworks you might even be able to introduce it with no code change at all, just an XML file on the side?
Maybe you could use an AOP framework such as PostSharp to break into the debugger whenever a method is entered. Have a look at the very short tutorial on this page for an example, how you can log/trace whenever a method is entered.
Instead of logging, in your case you could put the Debugger.Break() statement into the OnEntry-handler. Although, the debugger would not stop in your methods, but in the OnEntry-handler (so I'm not sure if this really helps).
Here's a very basic sample:
The aspect class defines an OnEntry handler, which calls Debugger.Break():
[Serializable]
public sealed class DebugBreakAttribute : PostSharp.Laos.OnMethodBoundaryAspect
{
public DebugBreakAttribute() {}
public DebugBreakAttribute(string category) {}
public string Category { get { return "DebugBreak"; } }
public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)
{
base.OnEntry(eventArgs);
// debugger will break here. Press F10 to continue to the "real" method
System.Diagnostics.Debugger.Break();
}
}
I can then apply this aspect to my class, where I want the debugger to break whenever a method is called:
[DebugBreak("DebugBreak")]
public class MyClass
{
public MyClass()
{
// ...
}
public void Test()
{
// ...
}
}
Now if I build and run the application, the debugger will stop in the OnEntry() handler whenever one of the methods of MyClass is called. All I have to do then, is to press F10, and I'm in the method of MyClass.
Well, as everyone is saying, it involves setting a breakpoint at the beginning of every method. But you're not seeing the bigger picture.
For this to work at all, a breakpoint has to be set at the beginning of every method. Whether you do it manually, or the debugger does it automatically, those breakpoints must be set for this to work.
So, the question really becomes, "If there enough of a need for this functionality, that it is worth building into the debugger an automatic means of setting all those breakpoints?". And the answer is, "Not Really".
This feature is implemented in VS for native C++. crtl-B and specify the 'function' as "Classname::*", this sets a breakpoint at the beginning of every method on the class. The breakpoints set are grouped together in the breakpoints window (ctrl-alt-B) so they can be enabled, disabled, and removed as a group.
Sadly the macro is likely the best bet for managed code.
This works fine in WinDbg:
bm exename!CSomeClass::*
(Just to clarify, the above line sets a breakpoint on all functions in the class, just like the OP is asking for, without resorting to CRT hacking or macro silliness)
You could write a Visual Studio macro that obtained a list of all of the class methods (say, by reading the .map file produced alongside the executable and searching it for the proper symbol names (and then demangling those names)), and then used Breakpoints.add() to programmatically add breakpoints to those functions.
System.Diagnostics.Debugger.Break();
(at the beginning of every method)
No. Or rather, yes, but it involves setting a breakpoint at the beginning of every method.
Use Debugger.Break(); (from the System.Diagnostics namespace)
Put it at the top of each function you wish to have "broken"
void MyFunction()
{
Debugger.Break();
Console.WriteLine("More stuff...");
}
Isn't the simplest method to get closest to this to simply set a break point in the constructor (assuming you have only one - or each of them in the case of multiple constructors) ?
This will break into debugging when the class is first instantiated in the case of a non-static constructor, and in the case of a static constructor/class, you'll break into debugging as soon as Visual Studio decides to initialize your class.
This certainly prevents you from having to set a breakpoint in every method within the class.
Of course, you won't continue to break into debugging on subsequent re-entry to the class's code (assuming you're using the same instantiated object the next time around), however, if you re-instantiate a new object each time from within the calling code, you could simulate this.
However, in conventional terms, there's no simple way to set a single break point in one place (for example) and have it break into debugging every time a class's code (from whichever method) is entered (as far as I know).
Assuming that you're only interested in public methods i.e. when the class methods are called "from outside", I will plug Design by Contract once more.
You can get into the habit of writing your public functions like this:
public int Whatever(int blah, bool duh)
{
// INVARIANT (i)
// PRECONDITION CHECK (ii)
// BODY (iii)
// POSTCONDITION CHECK (iv)
// INVARIANT (v)
}
Then you can use the Invariant() function that you will call in (i) and set a breakpoint in it. Then inspect the call stack to know where you're coming from. Of course you will call it in (v), too; if you're really interested in only entry points, you could use a helper function to call Invariant from (i) and another one from (v).
Of course this is extra code but
It's useful code anyway, and the structure is boilerplate if you use Design by Contract.
Sometimes you want breakpoints to investigate some incorrect behaviour eg invalid object state, in that case invariants might be priceless.
For an object which is always valid, the Invariant() function just has a body that returns true. You can still put a breakpoint there.
It's just an idea, it admittedly has a footstep, so just consider it and use it if you like it.
Joel, the answer seems to be "no". There isn't a way without a breakpoint at every method.
To remove the breakpoints set by the accepted answer add another macro with the following code
Public Sub RemoveBreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim bps As Breakpoints
bps = debugger.Breakpoints
If (bps.Count > 0) Then
Dim bp As Breakpoint
For Each bp In bps
Dim split As String() = bp.File.Split(New [Char]() {"\"c})
If (split.Length > 0) Then
Dim strName = split(split.Length - 1)
If (strName.Equals(DTE.ActiveDocument.Name)) Then
bp.Delete()
End If
End If
Next
End If
End Sub
Not that I'm aware of. The best you can do is to put a breakpoint in every method in the file or class. What are you trying to do? Are you trying to figure out what method is causing something to change? If so, perhaps a data breakpoint will be more appropriate.
You could write a wrapper method through which you make EVERY call in your app. Then you set a breakpoint in that single method. But... you'd be crazy to do such a thing.
You could put a memory break point on this, and set it to on read. I think there should be a read most of the time you call a member function. I'm not sure about static functions.
you can use the following macro:
#ifdef _DEBUG
#define DEBUG_METHOD(x) x DebugBreak();
#else
#define DEBUG_METHOD(x) x
#endif
#include <windows.h>
DEBUG_METHOD(int func(int arg) {)
return 0;
}
on function enter it will break into the debugger
IF this is C++ you are talking about, then you could probably get away with, (a hell of a lot of work) setting a break point in the preamble code in the CRT, or writing code that modifies the preamble code to stick INT 3's in there only for functions generated from the class in question... This, BTW, CAN be done at runtime... You'd have to have the PE file that's generated modify itself, possibly before relocation, to stick all the break's in there...
My only other suggestion would be to write a Macro that uses the predefined macro __FUNCTION__, in which you look for any function that's part of the class in question, and if necessary, stick a
__asm { int 3 }
in your macro to make VS break... This will prevent you from having to set break points at the start of every function, but you'd still have to stick a macro call, which is a lot better, if you ask me. I think I read somewhere on how you can define, or redefine the preamble code that's called per function.. I'll see what I can find.
I would think I similar hack could be used to detect which FILE you enter, but you STILL have to place YOUR function macro's all over your code, or it will never get called, and, well, that's pretty much what you didn't want to do.
If you are willing to use a macro then the accepted answer from this question
Should be trivially convertible to you needs by making the search function searching for methods, properties and constructors (as desired), there is also quite possibly a way to get the same information from the the ide/symbols which will be more stable (though perhaps a little more complex).
You can use Debugger.Launch() and Debugger.Break() in the assembly System.Diagnostics
Files have no existence at runtime (consider that partial classes are no different -- in terms of code -- from putting everything in a single file). Therefore a macro approach (or code in every method) is required.
To do the same with a type (which does exist at runtime) may be able to be done, but likely to be highly intrusive, creating more potential for heisenbugs. The "easiest" route to this is likely to be making use of .NET remoting's proxy infrastructure (see MOQ's implementation for an example of using transparent proxy).
Summary: use a macro, or select all followed by set breakpoint (ctrl-A, F9).
Mad method using reflection. See the documentation for MethodRental.SwapMethodBody for details. In pseudocode:
void SetBreakpointsForAllMethodsAndConstructorsInClass (string classname)
{
find type information for class classname
for each constructor and method
get MSIL bytes
prepend call to System.Diagnostics.Debugger.Break to MSIL bytes
fix up MSIL code (I'm not familiar with the MSIL spec. Generally, absolute jump targets need fixing up)
call SwapMethodBody with new MSIL
}
You can then pass in classname as a runtime argument (via the command line if you want) to set breakpoints on all methods and constructors of the given class.