I haven't been able to find a reference that defines what these methods are made up of.
I kind of get what these methods do and what arguments they take, but I'm hoping to find out how they work.
I'd like to find something that would give me a definition such as
void System.Xml.Xmlreader()
{
//class constructor function
}
for all or most of the methods in this class.
The method signatures are available on MSDN:
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader_methods.aspx
If you click on the method names, you'll see a definition, explanation, and usually some code examples.
Edit: Also, if you right click on the using directive and choose "Go to Definition" in Visual Studio, you can view the metadata for the class.
Related
There is something I don't understand with the NuGet package CommandLineParser. This is the first time I see this?
Let me show you first:
On the left in my Auto Watch frame I can see the Value property. But, on the right, in Immediate Window I cannot access it. How is this possible. How can I use this package and read my Value Path after Parsing?
result.Value
error CS1061: 'ParserResult<Options>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'ParserResult<Options>' could be found (are you missing a using directive or an assembly reference?)
What is this watch folder doing I'm not doing?
By digging into the source code, you can see that ParserResult<T> is an abstract class..
The WithParsed extension method does a check to see if the ParserResult is a concrete type of Parsed, invokes the delegate and returns it https://github.com/commandlineparser/commandline/blob/master/src/CommandLine/ParserResultExtensions.cs
So now you're working with the abstract base class instead of the implementation, that's why you can't just do result.Value as that property is not sitting on the base class but rather the implementation.
My guess is that the Auto watch can know the actual type and show you the entire object and the Immediate window can't.
To work with .Value, you can cast it to Parsed<Options>
The exact example of using this CommandLineParser is used in this project: https://www.dropbox.com/s/nhq9os8dd9fim9u/FloorplanTransformation-3D-Walls.rar?dl=0
This is a visual studio project, check that out you will get a better understanding.
By the way here is a brief explanation:
you will have to create an instance of the Parser class.
Parser parser = Parser.Default;
Then to parse the arguments do the following
PraserResult<object> parser_result = parser.ParseArguments<MeshGenerateOptions, MorphologicalTransformOptions, other options>(args)
Here we have classes MeshGenerateOptions and MorphologicalTransformOptions with Attribute [Verb]
Now do the following to invoke the corresponding callback functions for each parsed arguments
parserResult.WithParsed<MeshGenerateOptions>(VerbHandlers.HandleGenerateMesh);
parserResult.WithParsed<MorphologicalTransformOptions>(VerbHandlers.HandleMorphologicalTransform);
Here, VerbHandlers is a static class not of much interest, HandleGenerateMesh and HandleMorphologicalTransform are Callback functions that are invoked when the corresponding verb is parsed.
You get the demo of How to use the above project you can watch the tutorial: https://www.youtube.com/watch?v=MNILyflAxdY&t=21s But this is just for building and using the above project.
I want to create a custom method that will work when added after “Console” in c#. It would be sort of similar to Console.WriteLine().
It would look something like this: Console.PrintMyName(). And when it is called, it would do this: Console.WriteLine(“James”).
Is there some way to do this by defining a function that only works as a method when put after after “Console”.
In short, no.
The closest thing you can do is approximate what you want.
The Console class (System.Console specifically) is a static class and so cannot have "methods added to it" in the same way as a class that can be instantiated (instantiated classes can have extension methods).
The closest you can come to this is to either
create your own class named Console with it's own PrintMyName method. However, if you use both System.Console and your custom MyCustom.Console in the same compilation unit, you will have to disambiguate them by addressing one or both by their full namespace.
create a new static class with a completely different name.
BACKGROUND
I am seeking to create a Roslyn CodeFix that will respond to a Diagnostic warning from the built in Analyzer shipped with Visual Studio, that will identify the interface that is not - or is partially - implemented, allowing me to loop through the missing members, and generate custom code that delegates a method call to a Member field of a type that implements the interface.
(The Roslyn Analysers and CodeFixes that ship with Visual Studio do offer this functionality, but I need to customise and extend the generation of code, which is not possible as the Microsoft implementations are all marked as internal.)
Please note: The interface is almost always going to be located in an external, third-party assembly, to which I do not have access to the source.
e.g. starting from:
public class CustomDocumentDBClient : IDocumentClient
{
}
The desired outcome would be similar to the following (in practice I will be creating multiple versions that add additional code to wrap the method calls, once the basic principals are working):
public class CustomDocumentDBClient : IDocumentClient
{
// Field to which calls are delegated, initialised by the constructor
private readonly IDocumentClient _documentClientImplementation;
// Constructor
public CustomDocumentDBClient (IDocumentClient documentClientImplementation)
{
_documentClientImplementation = documentClientImplementation;
}
// Interface method that delegates to private field for invocation
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string documentLink, object attachment, RequestOptions options = null)
{
return _documentClientImplementation.CreateAttachmentAsync(documentLink, attachment, options);
}
// Interface method that delegates to private field for invocation
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string documentLink, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null)
{
return _documentClientImplementation.CreateAttachmentAsync(documentLink, mediaStream, options, requestOptions);
}
...
other methods
...
}
WHAT I HAVE TRIED
I have spent some time reading tutorials regarding the Syntax Tree and Semantic Model functionality of Roslyn.
I have also examined the Roslyn source code from GitHub - which does include the exact feature that I wish to implement; however, the code is heavily interwoven throughout various complex classes, and is implemented as internal methods, which cannot be overridden or extended, or indeed extracted into a standalone project.
From investigating multiple samples, and also a related SO question How to see if a class has implemented the interface with Roslyn I have concluded that I must use the Roslyn Semantic Model to obtain information about the interface, and it's declared members.
Once I can obtain the interface Members, I am able to build the required output code using the SyntaxFactory, and I have used the 'Roslyn Quoter' for guidance.
Creating a CodeFix from the default template, that responds to the correct Diagnostic codes is straightforward, and this is functioning.
ISSUES
The problem I am having, is taking the token identified by the Diagnostics Location, which appears to be a SimpleBaseTypeSyntax token, and
Verifying that it is actually representing an interface,
Obtaining a Symbol definition that allows me to enumerate the Members of the third-party interface.
The Syntax Visualizer indicates that the interface declaration node is of type SimpleBaseType.
I am therefore using the following code to obtain the token from the Syntax Tree as SimpleBaseTypeSyntax-
// Find the interface Syntax Token detected by the diagnostic.
var interfaceBaseTypeSyntax =
root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf()
.OfType<SimpleBaseTypeSyntax>().First();
a) This does return a token that contains the information of the relevant node in the Syntax Tree - however, I cannot see any 'InterfaceTypeSyntax' type or IsInterface method to validate that it is actually an interface.
b) I believe I should be able to use semanticModel.GetSymbolInfo(interfaceBaseTypeSyntax), however this always returns null - bear in mind the interface is declared in an external assembly.
Is there something I need to do to make that information available through GetSymbolInfo, or is there another approach I should be taking...?
Many thanks for your advice...
It's rather embarrassing to have found this so quickly after posting, but the solution seems to be to refer to the Identifier which is a descendant of the SimpleBaseTypeSyntax.
var interfaceSymbolInfo =
semanticModel.GetSymbolInfo(interfaceBaseTypeSyntax.DescendantNodes().First());
And, by calling:
var interfaceTypeInfo =
semanticModel.GetTypeInfo(interfaceBaseTypeSyntax.DescendantNodes().First());
I can then use interfaceTypeInfo.Type.IsInterface to verify I have indeed found an interface type, and also access interfaceTypeInfo.Type.GetMembers().
The answer was staring me in the face via the Syntax Visualizer.
I'm leaving this open for now, in case others have a better solution... thanks!
In this case, the syntax node you are looking at refers to a type not a symbol. GetSymbolInfo will return null if the node you pass in is not a symbol. You want to use semanticModel.GetTypeInfo(interfaceBaseTypeSyntax).
I have a class that inherits the TextBox Class, call it MyTextBox
I'd like to redefine the default Background value for this class.
So I looked for a way to do so and found a good option: call BackgroundProperty.OverrideMetadata()
trouble is: where can I put this?
in the App.OnStartup()? Ugly and not practical, I'd like that to be in my Class's code file.
in the Class's contructor? I get an exception:
PropertyMetadata is already registered
for the type 'MyTextBox'.
(seems fine to me, I understand why I get this perfectly)
So I looked again a found about the static constructor in C# (did not no about that earlier, what a pity)
so here's my code:
public class MyTextBox : TextBox
{
static MyTextBox()
{
MyTextBox.BackgroundProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(App.Current.Resources["CustomBackgroundBrush"]));
}
}
now, I'm pretty happy whith this, but Microsoft isn't. Namely, when I use the code analysis feature, I get this:
CA1810: Initialize reference type static fields inline
Hence my question: what can I do about it?
ignore the warning? >> I don't like to ignore warnings
move the call to the overrideMetadata method? >> I'd like to, but where?
any hints welcome, thanks
Edit: I'll add that I don't fully understand why I get this warning, since I am not initializing anything per say in my static constructor, or am I?
Here is the link from MSDN for overridding metadata for overridding metadata for a dependency property:
It states:
"Overriding metadata on a dependency property must be done prior to that property being placed in use by the property system (this equates to the time that specific instances of objects that register the property are instantiated). Calls to OverrideMetadata must be performed within the static constructors of the type that provides itself as the forType parameter of OverrideMetadata."
And the wording from the link you posted to CA1810 about when to suppress warnings:
When to Suppress Warnings
CA1810
It is safe to suppress a warning from this rule if performance is not a concern; or if global state changes that are caused by static initialization are expensive or must be guaranteed to occur before a static method of the type is called or an instance of the type is created.
So, your current implementation and suppression of the warning is probably the correct route.
I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to strongly discourage normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to advertise that there is a way to do something wrong.)
It would be nice to be able to tell Intellisense to not show the function, for instance.
The best solution I have at the moment is to just name the function something like: DangerousSet().
What other options do I have?
Follow-Up
I found Amy B's answer most useful to my situation. Thanks!
Mufasa's suggestion to use reflection was great, but harder to implement (for me).
Chris' suggestion of using a decorator was good, but didn't pan out.
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.
You can use InternalsVisibleToAttribute to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite "friend".
Mark your DangerousSet function internal instead of public.
In Properties\AssemblyInfo.cs of the project containing DangerousSet:
[assembly:InternalsVisibleTo("YourTestAssembly")]
If you have two test assemblies for whatever reason, the syntax is:
[assembly:InternalsVisibleTo("TestAssembly1"),
InternalsVisibleTo("TestAssembly2")]
Decorate your method with this attribute:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
This will hide it from Intellisense.
EDIT:
But apparently this has a rather significant caveat: "In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly." Via MSDN.
Suppose you want to test this object by manipulating its fields.
public class ComplexCalculation
{
protected int favoriteNumber;
public int FavoriteNumber
{
get { return favoriteNumber; }
}
}
Place this object in your test assembly/namespace:
public class ComplexCalculationTest : ComplexCalculation
{
public void SetFavoriteNumber(int newFavoriteNumber)
{
this.favoriteNumber = newFavoriteNumber;
}
}
And write your test:
public void Test()
{
ComplexCalculationTest myTestObject = new ComplexCalculationTest();
myTestObject.SetFavoriteNumber(3);
ComplexCalculation myObject = myTestObject;
if (myObject.FavoriteNumber == 3)
Console.WriteLine("Win!");
}
PS: I know you said internal, but I don't think you meant internal.
It sounds like your real problem is in your reference documents. You shouldn't test cases that are impossible to encounter under proper use of your class. If users shouldn't be allowed to change the state of those variables, then neither should your tests.
You can also use reflection. Google search turned up Unit testing private methods using reflection.
Can your test code include a subclass of the calculations class? If so, you can mark the function protected and only inheritors will be able to use it. I'm pretty sure this also takes it out of intellisense, but I could be wrong about that.
What I've done in the past is I put XML Comments by the method and used the section to write in big bold letters. DON'T USE THIS METHOD or whatever. That way, if someone tried to use it, Intellisense would give them a nice warning.