Ask a chain/multiple questions together (Voice Recognition) - c#

I need help asking my program a series of questions.
For example:
I may say "hi computer" and I want my computer to respond saying "Hi, Sir. How are you?" Then my computer would say "Fine and yourself?" and my computer would say something else.
As of now I'm using Case statements. An example of my code below:
//Kindness
case "thank you":
case "thank you jarvis":
case "thanks":
case "thanks jarvis":
if (ranNum <= 3) { QEvent = ""; JARVIS.Speak("You're Welcome Sir"); }
else if (ranNum <= 6) { QEvent = ""; JARVIS.Speak("Anytime"); }
else if (ranNum <= 10) { QEvent = ""; JARVIS.Speak("No problem boss"); }
break;

An approach I've had good success with is to create 'Contexts', which are (nested) collections of responses and scripts. When you find a matching Context, you push that Context onto a stack, and start looking for responses in the inner Contexts. If no response matches the current set of contexts, you pop the stack and retry. If the stack is empty, you generate a default "I don't understand" response.
An interesting implementation of this could be based on the answers to this question, particularly this answer, which nicely maps the response/action pairs.

A factory pattern is what you need.
The factory simply reflects on all the methods in MySpeechMethods, looks for ones with SpeechAttributes and sends back the MethodInfo to invoke.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MyApp.SpeechMethods;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
var methods = new MySpeechMethods();
MethodInfo myMethod;
myMethod = SpeechFactory.GetSpeechMethod("Thank you");
myMethod.Invoke(methods, null);
myMethod = SpeechFactory.GetSpeechMethod("Say something funny");
myMethod.Invoke(methods, null);
myMethod = SpeechFactory.GetSpeechMethod("I said funny dammit!");
myMethod.Invoke(methods, null);
}
}
public static class SpeechFactory
{
private static Dictionary<string, MethodInfo> speechMethods = new Dictionary<string, MethodInfo>();
public static MethodInfo GetSpeechMethod(string speechText)
{
MethodInfo methodInfo;
var mySpeechMethods = new MySpeechMethods();
if (speechMethods.Count == 0)
{
var methodNames =
typeof (MySpeechMethods).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
var speechAttributeMethods = methodNames.Where(y => y.GetCustomAttributes().OfType<SpeechAttribute>().Any());
foreach (var speechAttributeMethod in speechAttributeMethods)
{
foreach (var attribute in speechAttributeMethod.GetCustomAttributes(true))
{
speechMethods.Add(((SpeechAttribute)attribute).SpeechValue, speechAttributeMethod);
}
}
methodInfo = speechMethods[speechText];
}
else
{
methodInfo = speechMethods[speechText];
}
return methodInfo;
}
}
}
namespace MyApp.SpeechMethods
{
public class MySpeechMethods
{
[Speech("Thank you")]
[Speech("Thank you Jarvis")]
[Speech("Thanks")]
public void YourWelcome()
{
JARVIS.Speak("You're Welcome Sir");
}
[Speech("Say something funny")]
public void SayFunny()
{
JARVIS.Speak("A priest, a rabbi and a cabbage walk into a bar");
}
[Speech("I said funny dammit!")]
public void TryFunnyAgain()
{
JARVIS.Speak("My apologies sir.");
}
}
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true)]
public class SpeechAttribute : System.Attribute
{
public string SpeechValue { get; set; }
public SpeechAttribute(string textValue)
{
this.SpeechValue = textValue;
}
}
}

Related

How to subscribe to an event with reflection. C#

I can't seem to figure out why this is throwing "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type." Specifically this part method.CreateDelegate(eventInfos[0].EventHandlerType, new Commands());
//These are defined at the top of the class
public delegate Task MessageReceivedAsyncDelegate(SocketMessage arg);
public delegate void MessageReceivedDelegate(SocketMessage arg);
public event MessageReceivedAsyncDelegate MessageReceivedCommandAsync;
public event MessageReceivedDelegate MessageReceivedCommand;
//These are defined at the top of the class
Type B = typeof(Base);
Type C = typeof(Commands);
MethodInfo[] methods = C.GetMethods();
foreach (MethodInfo method in methods)
{
EventInfo[] eventInfos = B.GetEvents();
if(method.GetCustomAttributes(typeof(SubscribeToMessageRecivedAttribute)).Any()
{
if (method.ReturnType == typeof(Task))
{
try { eventInfos[0].AddEventHandler(C, method.CreateDelegate(eventInfos[0].EventHandlerType, new Commands())); }
catch(Exception exception) { Console.WriteLine(exception); }
}
else eventInfos[1].AddEventHandler(C, method.CreateDelegate(eventInfos[1].EventHandlerType, new Commands()));
}
}
Method which it's trying to add
public partial class Commands : ModuleBase<SocketCommandContext>
{
[SubscribeToMessageRecived]
public static async Task Mock(SocketMessage arg)
{
Console.WriteLine("Mocking");
if (Base.mockList.Contains((int)arg.Author.Id))
{
char[] msgArray = arg.Content.ToCharArray();
for (int i = 0; i < arg.Content.Length; i++)
{
if (DaMef.RandomRange(0,3) == 1) msgArray[i] = msgArray[i].ToString().ToLower().ToCharArray()[0];
else msgArray[i] = msgArray[i].ToString().ToUpper().ToCharArray()[0];
}
string finalString = msgArray.ToString();
await arg.Channel.SendMessageAsync(finalString + "\nhttps://imgur.com/a/HsiBmYc");
}
}
}
I'm trying to subscribe all methods in the Commands with "SubscribeToMessageRecivedAttribute" to an event.
There are answers online but none seem to be it. (Or maybe I just didn't understand them.) I've never used reflections and have barely used events so sorry if it's something stupid.

How do i get symbol references in a diagnostic without SymbolFinder?

Currently i've got this code:
private async Task<bool> IsMentionedInDisposeCallAsync(SyntaxNodeAnalysisContext context, FieldDeclarationSyntax fieldDeclarationSyntax)
{
foreach (var variableDeclaratorSyntax in fieldDeclarationSyntax.Declaration.Variables)
{
var declaredSymbol = context.SemanticModel.GetDeclaredSymbol(variableDeclaratorSyntax);
if (declaredSymbol is IFieldSymbol fieldSymbol)
{
// SymbolFinder.FindReferencesAsync()
var b = fieldSymbol.Locations;
// context.SemanticModel.Compilation.
}
}
return false;
}
And this scenario:
private static readonly string TestSourceImplementsDisposableAndDoesMentionDisposableField = #"
using System;
using System.IO;
namespace ConsoleApplication1
{
public class SampleDisposable : IDisposable
{
public void Dispose()
{
}
}
public class SampleConsumer : IDisposable
{
private SampleDisposable _disposable = new SampleDisposable();
private IDisposable _ms = new MemoryStream();
public void Dispose()
{
_disposable?.Dispose();
_ms?.Dispose();
}
}
}";
Ultimately my desire is to figure out whether a dispose method is accessing a disposable field. Unfortunately i can't seem to find a way to get this working without using SymbolFinder, which requires a solution.
I did something similar with SymbolFinder and it was an easy thing to do - but how do i do it from the functionality available within a diagnostic?
Am i missing something obvious here?
You could simply use the SemanticModel to analyse the type used for the field like this:
private async Task<bool> IsMentionedInDisposeCallAsync(SyntaxNodeAnalysisContext context, FieldDeclarationSyntax fieldDeclarationSyntax)
{
foreach (var variableDeclaratorSyntax in fieldDeclarationSyntax.Declaration.Variables)
{
var declaredSymbol = context.SemanticModel.GetDeclaredSymbol(variableDeclaratorSyntax);
if (declaredSymbol is IFieldSymbol fieldSymbol)
{
var isDisposeable = CheckIsTypeIDisposeable(fieldSymbol.Type as INamedTypeSymbol);
// SymbolFinder.FindReferencesAsync()
var b = fieldSymbol.Locations;
// context.SemanticModel.Compilation.
}
}
return false;
}
private string fullQualifiedAssemblyNameOfIDisposeable = typeof(IDisposable).AssemblyQualifiedName;
private bool CheckIsTypeIDisposeable(INamedTypeSymbol type)
{
// Identify the IDisposable class. You can use any method to do this here
// A type.ToDisplayString() == "System.IDisposable" might do it for you
if(fullQualifiedAssemblyNameOfIDisposeable ==
type.ToDisplayString() + ", " + type.ContainingAssembly.ToDisplayString())
{
return true;
}
if(type.BaseType != null)
{
if (CheckIsTypeIDisposeable(type.BaseType))
{
return true;
}
}
foreach(var #interface in type.AllInterfaces)
{
if (CheckIsTypeIDisposeable(#interface))
{
return true;
}
}
return false;
}
Basically you would search through all interfaces of the class and the base class recursively to find the type corresponding to IDisposeable - which should be somewhere in the hierarchy.

Call a method dynamically based on some other variable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to Call method using its name?
Getting sick of using switch/case statements. I'm wondering if there is some way to call a method based on the value provided by the user. Understand that there could be a million reasons why this is a bad idea, but here's what I'm thinking:
Console.Write("What method do you want to call? ");
string method_name = Console.ReadLine();
then somehow call the method contained in 'method_name'. Is this even possible?
You can use reflection:
var type = typeof(MyClass);
var method = type.GetMethod(method_name);
method.Invoke(obj, params);
If you want the type to be dynamic as well as the method then use this instead of typeof(MyClass):
var type = Type.GetType(type_name);
Many times you can refactor switch statements to dictionaries...
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
}
can become ...
var replaceSwitch = new Dictionary<int, Action>
{
{ 1, () => Console.WriteLine("Case 1") }
{ 2, () => Console.WriteLine("Case 2") }
{ 3, () => Console.WriteLine("Case 3") }
}
...
replaceSwitch[value]();
This is a very subtle shift that doesn't seem to gain much, but in reality it's much, much better. If you want to know why, this blog post explains it very well.
Instead of reflection, if you have to act on the user's input value w/o using switch statement, you could use a dictionary having the list of methods mapped against the input value.
private static void Method1(int x)
{
Console.WriteLine(x);
}
private static void Method2(int x)
{
}
private static void Method3(int x)
{
}
static void Main(string[] args)
{
Dictionary<int, Action<int>> methods = new Dictionary<int, Action<int>>();
methods.Add(1, Method1);
methods.Add(2, Method2);
methods.Add(3, Method3);
(methods[1])(1);
}
Your sample
public class Boss
{
public void Kick()
{
Console.WriteLine("Kick");
}
public void Talk(string message)
{
Console.WriteLine("Talk " + message);
}
public void Run()
{
Console.WriteLine("Run");
}
}
class Program
{
static void AutoSwitch(object obj, string methodName, params object[] parameters)
{
var objType = typeof(obj);
var method = objType.GetMethod(methodName);
method.Invoke(obj, parameters);
}
static void Main(string[] args)
{
var obj = new Boss();
AutoSwitch(obj, "Talk", "Hello World");
AutoSwitch(obj, "Kick");
}
}
Another interesting way I have seen to handle(read avoid) switch statements differently is to use a dictionary of methods. I stole this from http://www.markhneedham.com/blog/2010/05/30/c-using-a-dictionary-instead-of-if-statements/ and it looks like they are using the MVC framework but the same basic principal applies
public class SomeController
{
private Dictionary<string, Func<UserData,ActionResult>> handleAction =
new Dictionary<string, Func<UserData,ActionResult>>
{ { "Back", SaveAction },
{ "Next", NextAction },
{ "Save", SaveAction } };
public ActionResult TheAction(string whichButton, UserData userData)
{
if(handleAction.ContainsKey(whichButton))
{
return handleAction[whichButton](userData);
}
throw Exception("");
}
private ActionResult NextAction(UserData userData)
{
// do cool stuff
}
}
If you're thinking you could somehow do this:
Console.Write("What method do you want to call? ");
string method_name = Console.ReadLine();
method_name();
You are mistaken. You have to analyze the user input and call a method based on that.
Sure, reflection is your friend. Have a look at Type.GetMethod().

Copy two identical object with different namespaces (recursive reflection)

I'm working in c# with several workspaces that have one specific class which his always the same in each workspace.
I would like to be able have a copy of this class to be able to work with it without dealing with namespaces differences.
example :
namespace1 {
class class1{
public class2;
}
class class2{
public string;
}
}
namespace2 {
class class1{
public class2;
}
class class2{
public string;
}
}
In my copied Class I've got a function to copy all data's to one of the namespace's class.
It's working if i only have c# standard types. I got exeption ( "Object does not match target type." ) as soon as I'm dealing with class2 object (which is also from different namespaces)
public Object toNamespaceClass(Object namespaceClass)
{
try
{
Type fromType = this.GetType();
Type toType = namespaceClass.GetType();
PropertyInfo[] fromProps = fromType.GetProperties();
PropertyInfo[] toProps = toType.GetProperties();
for (int i = 0; i < fromProps.Length; i++)
{
PropertyInfo fromProp = fromProps[i];
PropertyInfo toProp = toType.GetProperty(fromProp.Name);
if (toProp != null)
{
toProp.SetValue(this, fromProp.GetValue(namespaceClass, null), null);
}
}
}
catch (Exception ex)
{
}
return namespaceClass;
}
Anyone do have any idea of how to deal with this kind of "recursivity reflection".
I hope eveything is understandable.
Thanks, Bye!
Edit :
I think i got it solved (at least in my mind), I'll try the solution back at work tomorrow. Taking my function out of my class and using it recursively if a property is not a standard type is maybe the solution.
BinaryFormatter does not work in .Net 4.5 as it remembers from what type of class the instance was created. But with JSON format, it does not. JSON serializer is implemented by Microsoft in DataContractJosnSerializer.
This works:
public static T2 DeepClone<T1, T2>(T1 obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T1));
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T2));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;
return (T2)deserializer.ReadObject(ms);
}
}
and uses as follows:
var b = DeepClone<A, B>(a);
I had the similar problem. I got to use similar classes but different in terms of namespace only. As a quick solution I performed below steps and it works.
Serialize source class into XML.
In SerializedXML replace source namespace with the target one.
DeSerialize with target type.
I know there is performance overhead with above way but it is quick to implement and error free.
I got it solved , just to let you know how I did it :
This solution is sot perfect because it handle only 1 dimensions array not more.
public static Object CopyObject(Object from , Object to)
{
try
{
Type fromType = from.GetType();
Type toType = to.GetType();
PropertyInfo[] fromProps = fromType.GetProperties();
PropertyInfo[] toProps = toType.GetProperties();
for (int i = 0; i < fromProps.Length; i++)
{
PropertyInfo fromProp = fromProps[i];
PropertyInfo toProp = toType.GetProperty(fromProp.Name);
if (toProp != null)
{
if (toProp.PropertyType.Module.ScopeName != "CommonLanguageRuntimeLibrary")
{
if (!toProp.PropertyType.IsArray)
{
ConstructorInfo ci = toProp.PropertyType.GetConstructor(new Type[0]);
if (ci != null)
{
toProp.SetValue(to, ci.Invoke(null), null);
toProp.SetValue(to, gestionRefelexion.CopyObject(fromProp.GetValue(from, null), toProp.GetValue(to, null)), null);
}
}
else
{
Type typeToArray = toProp.PropertyType.GetElementType();
Array fromArray = fromProp.GetValue(from, null) as Array;
toProp.SetValue(to, copyArray(fromArray, typeToArray), null);
}
}
else
{
toProp.SetValue(to, fromProp.GetValue(from, null), null);
}
}
}
}
catch (Exception ex)
{
}
return to;
}
public static Array copyArray(Array from, Type toType)
{
Array toArray =null;
if (from != null)
{
toArray= Array.CreateInstance(toType, from.Length);
for (int i = 0; i < from.Length; i++)
{
ConstructorInfo ci = toType.GetConstructor(new Type[0]);
if (ci != null)
{
toArray.SetValue(ci.Invoke(null), i);
toArray.SetValue(gestionRefelexion.CopyObject(from.GetValue(i), toArray.GetValue(i)), i);
}
}
}
return toArray;
}
Hope this can help some people.
Thanks for helping everyone.
Cheers
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
from here
Two identical or similar objects from different namespaces ?
You have this:
namespace Cars
{
public class car {
public string Name;
public void Start() { ... }
}
}
namespace Planes
{
public class plane {
public string Name;
public void Fly() { ... }
}
}
Time to apply some class inheritance:
namespace Vehicles
{
public class vehicle
{
public string Name;
} // class
} // namespace
using Vehicles;
namespace Cars
{
public class car: vehicle
{
public string Name;
public void Start() { ... }
} // class
} // namespace
using Vehicles;
namespace Planes
{
public class plane: vehicle
{
public void Fly() { ... }
}
}
And to copy, there is a copy method or constructor, but, I prefer a custom one:
namespace Vehicles
{
public class vehicle {
public string Name;
public virtual CopyFrom (vehicle Source)
{
this.Name = Source.Name;
// other fields
}
} // class
} // namespace
Cheers.
You either need to refactor all of your duplicate classes into a single shared class or implement a common interface that all of your various classes implement. If you really can't modify the underlying types, create a subclass for each that implements your common interface.
Yes, you can do it with reflection... but you really shouldn't because you end up with brittle, error prone, code.
This problem can be elegantly solves using Protocol Buffers because Protocol Buffers do not hold any metadata about the type they serialize. Two classes with identical fields & properties serialize to the exact same bits.
Here's a little function that will change from O the original type to C the copy type
static public C DeepCopyChangingNamespace<O,C>(O original)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, original);
ms.Position = 0;
C c = Serializer.Deserialize<C>(ms);
return c;
}
}
usage would be
namespace1.class1 orig = new namespace1.class1();
namespace2.class1 copy =
DeepCopyChangingNamespace<namespace1.class1, namespace2.class1>(orig);

Extract xml comments for public members only

I'm using xml comments to document public as well as internal and private members of my components. I would like to package the generated documentation xml files with component assemblies in order to enable "rich" (e.g. with method, exceptions and parameter descriptions) Visual Studio Intellisense with the end product. The problem with it is that the C# compiler creates documentation entries for everything (including internal classes, methods, private fields of internal enums etc.) and there seems to be no switch to "only public members" mode.
Now I don't want to go over 50 files with XX methods in each and remove all comments for private and internal members. Even if I did that, I probably would not have much success with auto-gen'd resource files, because these strongly-typed resource classes are automatically commented and non-public.
My question is: is there some option/flag that I'm overlooking? If no, are there some tools that could help separate public members from the rest (before I start to code one)?
SandCastle Help File Builder has an option to recreate the xml files containing only the configured access modes for methods, properties, etc...
The only "downside" is that you'll have to generate a documentation.
EDIT
Since it's been a long time ago I forgot that I added a "component" to SHFB to generate the XML.
The good news is that this component is included in SHFB.
You have to add the "Intellisense Component" to the SHFB project. It will then generate the XML according to the configured SHFB project.
For more info: Intellisense Component in SHFB
There is a tool inside the eazfuscator that can remove non-public documentation. You can see an example here
I've given this some thought and I decided to change the way I go about solving this particular problem. Instead of finding type/member within the assembly trying to parse the XML documentation notation. I decided to simply build a string set (of XML documentation notation) for the public API that can then be used to tes wheter a member isn't public.
It's really simple. Send an assembly to the XmlDocumentationStringSet and it will build a string set of the public API and delete the elements that aren't public.
static void Main(string[] args)
{
var el = XElement.Load("ConsoleApplication18.XML");
// obviously, improve this if necessary (might not work like this if DLL isn't already loaded)
// you can use file paths
var assemblyName = el.Descendants("assembly").FirstOrDefault();
var assembly = Assembly.ReflectionOnlyLoad(assemblyName.Value);
var stringSet = new XmlDocumentationStringSet(assembly);
foreach (var member in el.Descendants("member").ToList()) // .ToList enables removing while traversing
{
var attr = member.Attribute("name");
if (attr == null)
{
continue;
}
if (!stringSet.Contains(attr.Value))
{
member.Remove();
}
}
el.Save("ConsoleApplication18-public.XML");
}
And here's the class that builds the XML documentation names (it's a bit large but I thought I post the entire source here anyway):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication18
{
public class XmlDocumentationStringSet : IEnumerable<string>
{
private HashSet<string> stringSet = new HashSet<string>(StringComparer.Ordinal);
public XmlDocumentationStringSet(Assembly assembly)
{
AddRange(assembly.GetExportedTypes());
}
public bool Contains(string name)
{
return stringSet.Contains(name);
}
/// <summary>
/// Heelloasdasdasd
/// </summary>
/// <param name="types"></param>
public void AddRange(IEnumerable<Type> types)
{
foreach (var type in types)
{
Add(type);
}
}
public void Add(Type type)
{
// Public API only
if (!type.IsVisible)
{
return;
}
var members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var member in members)
{
Add(type, member);
}
}
StringBuilder sb = new StringBuilder();
private void Add(Type type, MemberInfo member)
{
Type nestedType = null;
sb.Length = 0;
switch (member.MemberType)
{
case MemberTypes.Constructor:
sb.Append("M:");
AppendConstructor(sb, (ConstructorInfo)member);
break;
case MemberTypes.Event:
sb.Append("E:");
AppendEvent(sb, (EventInfo)member);
break;
case MemberTypes.Field:
sb.Append("F:");
AppendField(sb, (FieldInfo)member);
break;
case MemberTypes.Method:
sb.Append("M:");
AppendMethod(sb, (MethodInfo)member);
break;
case MemberTypes.NestedType:
nestedType = (Type)member;
if (IsVisible(nestedType))
{
sb.Append("T:");
AppendNestedType(sb, (Type)member);
}
break;
case MemberTypes.Property:
sb.Append("P:");
AppendProperty(sb, (PropertyInfo)member);
break;
}
if (sb.Length > 0)
{
stringSet.Add(sb.ToString());
}
if (nestedType != null)
{
Add(nestedType);
}
}
private bool IsVisible(Type nestedType)
{
return nestedType.IsVisible;
}
private void AppendProperty(StringBuilder sb, PropertyInfo propertyInfo)
{
if (!IsVisible(propertyInfo))
{
sb.Length = 0;
return;
}
AppendType(sb, propertyInfo.DeclaringType);
sb.Append('.').Append(propertyInfo.Name);
}
private bool IsVisible(PropertyInfo propertyInfo)
{
var getter = propertyInfo.GetGetMethod();
var setter = propertyInfo.GetSetMethod();
return (getter != null && IsVisible(getter)) || (setter != null && IsVisible(setter));
}
private void AppendNestedType(StringBuilder sb, Type type)
{
AppendType(sb, type.DeclaringType);
}
private void AppendMethod(StringBuilder sb, MethodInfo methodInfo)
{
if (!IsVisible(methodInfo) || (methodInfo.IsHideBySig && methodInfo.IsSpecialName))
{
sb.Length = 0;
return;
}
AppendType(sb, methodInfo.DeclaringType);
sb.Append('.').Append(methodInfo.Name);
AppendParameters(sb, methodInfo.GetParameters());
}
private bool IsVisible(MethodInfo methodInfo)
{
return methodInfo.IsFamily || methodInfo.IsPublic;
}
private void AppendParameters(StringBuilder sb, ParameterInfo[] parameterInfo)
{
if (parameterInfo.Length == 0)
{
return;
}
sb.Append('(');
for (int i = 0; i < parameterInfo.Length; i++)
{
if (i > 0)
{
sb.Append(',');
}
var p = parameterInfo[i];
AppendType(sb, p.ParameterType);
}
sb.Append(')');
}
private void AppendField(StringBuilder sb, FieldInfo fieldInfo)
{
if (!IsVisible(fieldInfo))
{
sb.Length = 0;
return;
}
AppendType(sb, fieldInfo.DeclaringType);
sb.Append('.').Append(fieldInfo.Name);
}
private bool IsVisible(FieldInfo fieldInfo)
{
return fieldInfo.IsFamily || fieldInfo.IsPublic;
}
private void AppendEvent(StringBuilder sb, EventInfo eventInfo)
{
if (!IsVisible(eventInfo))
{
sb.Length = 0;
return;
}
AppendType(sb, eventInfo.DeclaringType);
sb.Append('.').Append(eventInfo.Name);
}
private bool IsVisible(EventInfo eventInfo)
{
return true; // hu?
}
private void AppendConstructor(StringBuilder sb, ConstructorInfo constructorInfo)
{
if (!IsVisible(constructorInfo))
{
sb.Length = 0;
return;
}
AppendType(sb, constructorInfo.DeclaringType);
sb.Append('.').Append("#ctor");
AppendParameters(sb, constructorInfo.GetParameters());
}
private bool IsVisible(ConstructorInfo constructorInfo)
{
return constructorInfo.IsFamily || constructorInfo.IsPublic;
}
private void AppendType(StringBuilder sb, Type type)
{
if (type.DeclaringType != null)
{
AppendType(sb, type.DeclaringType);
sb.Append('.');
}
else if (!string.IsNullOrEmpty(type.Namespace))
{
sb.Append(type.Namespace);
sb.Append('.');
}
sb.Append(type.Name);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
// Remove "`1" suffix from type name
while (char.IsDigit(sb[sb.Length - 1]))
sb.Length--;
sb.Length--;
{
var args = type.GetGenericArguments();
sb.Append('{');
for (int i = 0; i < args.Length; i++)
{
if (i > 0)
{
sb.Append(',');
}
AppendType(sb, args[i]);
}
sb.Append('}');
}
}
}
public IEnumerator<string> GetEnumerator()
{
return stringSet.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
Oh, and I haven't figured out how to handle events yet, they are always visible in this example.
#John Leidegren
I've got the same requirement, and I've found the answer to the missing bit of your code. An Event has 2 methods, Add and Remove, and is considered public if either of them is public. So it would be something like:
private bool IsVisible(EventInfo eventInfo)
{
return eventInfo.GetAddMethod(false) != null
|| eventInfo.GetRemoveMethod(false) != null;
}
although I can't think of any reason why one would be public and not the other.
What tool are you using to generate the documentation? I use Sandcastle and that gives you the option to select members to include by accessability.
In general it seems expected that the XML would contain all info that could be needed and its up to the processing tool to select from it what is needed.
I was facing the same problem. SHFB is slow as hell and since we have another documentation code-base we did not need it to generate the documentation for us.
I ended up using XMLStarlet plus a separate namespace for internal classes. For example, all my internal classes would reside in MyCompany.MyProduct.Internal. Then I can use one simple command
xml ed -L -d "//member[contains(#name, 'MyCompany.MyProduct.Internal')]" MyProduct.xml
to cleanse the XML. This of course is not bullet-proof -- it does not cover internal members in public classes, and it does require some discipline to remember to put internal classes into internal. But this is the cleanest and least intrusive method which works for me. It is also a standalone EXE file easily checked into build server, no sweat.

Categories

Resources