Search Results

Search found 22 results on 1 pages for 'internalsvisibleto'.

Page 1/1 | 1 

  • InternalsVisibleTo attribute and security vulnerability

    - by Sergey Litvinov
    I found one issue with InternalsVisibleTo attribute usage. The idea of InternalsVisibleTo attribute to allow some other assemblies to use internal classes\methods of this assembly. To make it work you need sign your assemblies. So, if other assemblies isn't specified in main assembly and if they have incorrect public key, then they can't use Internal members. But the issue in Reflection Emit type generation. For example, we have CorpLibrary1 assembly and it has such class: public class TestApi { internal virtual void DoSomething() { Console.WriteLine("Base DoSomething"); } public void DoApiTest() { // some internal logic // ... // call internal method DoSomething(); } } This assembly is marked with such attribute to allow another CorpLibrary2 to make inheritor for that TestAPI and override behaviour of DoSomething method. [assembly: InternalsVisibleTo("CorpLibrary2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100434D9C5E1F9055BF7970B0C106AAA447271ECE0F8FC56F6AF3A906353F0B848A8346DC13C42A6530B4ED2E6CB8A1E56278E664E61C0D633A6F58643A7B8448CB0B15E31218FB8FE17F63906D3BF7E20B9D1A9F7B1C8CD11877C0AF079D454C21F24D5A85A8765395E5CC5252F0BE85CFEB65896EC69FCC75201E09795AAA07D0")] The issue is that I'm able to override this internal DoSomething method and break class logic. My steps to do it: Generate new assembly in runtime via AssemblyBuilder Get AssemblyName from CorpLibrary1 and copy PublikKey to new assembly Generate new assembly that will inherit TestApi class As PublicKey and name of generated assembly is the same as in InternalsVisibleTo, then we can generate new DoSomething method that will override internal method in TestAPI assembly Then we have another assembly that isn't related to this CorpLibrary1 and can't use internal members. We have such test code in it: class Program { static void Main(string[] args) { var builder = new FakeBuilder(InjectBadCode, "DoSomething", true); TestApi fakeType = builder.CreateFake(); fakeType.DoApiTest(); // it will display: // Inject bad code // Base DoSomething Console.ReadLine(); } public static void InjectBadCode() { Console.WriteLine("Inject bad code"); } } And this FakeBuilder class has such code: /// /// Builder that will generate inheritor for specified assembly and will overload specified internal virtual method /// /// Target type public class FakeBuilder { private readonly Action _callback; private readonly Type _targetType; private readonly string _targetMethodName; private readonly string _slotName; private readonly bool _callBaseMethod; public FakeBuilder(Action callback, string targetMethodName, bool callBaseMethod) { int randomId = new Random((int)DateTime.Now.Ticks).Next(); _slotName = string.Format("FakeSlot_{0}", randomId); _callback = callback; _targetType = typeof(TFakeType); _targetMethodName = targetMethodName; _callBaseMethod = callBaseMethod; } public TFakeType CreateFake() { // as CorpLibrary1 can't use code from unreferences assemblies, we need to store this Action somewhere. // And Thread is not bad place for that. It's not the best place as it won't work in multithread application, but it's just a sample LocalDataStoreSlot slot = Thread.AllocateNamedDataSlot(_slotName); Thread.SetData(slot, _callback); // then we generate new assembly with the same nameand public key as target assembly trusts by InternalsVisibleTo attribute var newTypeName = _targetType.Name + "Fake"; var targetAssembly = Assembly.GetAssembly(_targetType); AssemblyName an = new AssemblyName(); an.Name = GetFakeAssemblyName(targetAssembly); // copying public key to new generated assembly var assemblyName = targetAssembly.GetName(); an.SetPublicKey(assemblyName.GetPublicKey()); an.SetPublicKeyToken(assemblyName.GetPublicKeyToken()); AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyBuilder.GetName().Name, true); // create inheritor for specified type TypeBuilder typeBuilder = moduleBuilder.DefineType(newTypeName, TypeAttributes.Public | TypeAttributes.Class, _targetType); // LambdaExpression.CompileToMethod can be used only with static methods, so we need to create another method that will call our Inject method // we can do the same via ILGenerator, but expression trees are more easy to use MethodInfo methodInfo = CreateMethodInfo(moduleBuilder); MethodBuilder methodBuilder = typeBuilder.DefineMethod(_targetMethodName, MethodAttributes.Public | MethodAttributes.Virtual); ILGenerator ilGenerator = methodBuilder.GetILGenerator(); // call our static method that will call inject method ilGenerator.EmitCall(OpCodes.Call, methodInfo, null); // in case if we need, then we put call to base method if (_callBaseMethod) { var baseMethodInfo = _targetType.GetMethod(_targetMethodName, BindingFlags.NonPublic | BindingFlags.Instance); // place this to stack ilGenerator.Emit(OpCodes.Ldarg_0); // call the base method ilGenerator.EmitCall(OpCodes.Call, baseMethodInfo, new Type[0]); // return ilGenerator.Emit(OpCodes.Ret); } // generate type, create it and return to caller Type cheatType = typeBuilder.CreateType(); object type = Activator.CreateInstance(cheatType); return (TFakeType)type; } /// /// Get name of assembly from InternalsVisibleTo AssemblyName /// private static string GetFakeAssemblyName(Assembly assembly) { var internalsVisibleAttr = assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true).FirstOrDefault() as InternalsVisibleToAttribute; if (internalsVisibleAttr == null) { throw new InvalidOperationException("Assembly hasn't InternalVisibleTo attribute"); } var ind = internalsVisibleAttr.AssemblyName.IndexOf(","); var name = internalsVisibleAttr.AssemblyName.Substring(0, ind); return name; } /// /// Generate such code: /// ((Action)Thread.GetData(Thread.GetNamedDataSlot(_slotName))).Invoke(); /// private LambdaExpression MakeStaticExpressionMethod() { var allocateMethod = typeof(Thread).GetMethod("GetNamedDataSlot", BindingFlags.Static | BindingFlags.Public); var getDataMethod = typeof(Thread).GetMethod("GetData", BindingFlags.Static | BindingFlags.Public); var call = Expression.Call(allocateMethod, Expression.Constant(_slotName)); var getCall = Expression.Call(getDataMethod, call); var convCall = Expression.Convert(getCall, typeof(Action)); var invokExpr = Expression.Invoke(convCall); var lambda = Expression.Lambda(invokExpr); return lambda; } /// /// Generate static class with one static function that will execute Action from Thread NamedDataSlot /// private MethodInfo CreateMethodInfo(ModuleBuilder moduleBuilder) { var methodName = "_StaticTestMethod_" + _slotName; var className = "_StaticClass_" + _slotName; TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class); MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public); LambdaExpression expression = MakeStaticExpressionMethod(); expression.CompileToMethod(methodBuilder); var type = typeBuilder.CreateType(); return type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public); } } remarks about sample: as we need to execute code from another assembly, CorpLibrary1 hasn't access to it, so we need to store this delegate somewhere. Just for testing I stored it in Thread NamedDataSlot. It won't work in multithreaded applications, but it's just a sample. I know that we use Reflection to get private\internal members of any class, but within reflection we can't override them. But this issue is allows anyone to override internal class\method if that assembly has InternalsVisibleTo attribute. I tested it on .Net 3.5\4 and it works for both of them. How does it possible to just copy PublicKey without private key and use it in runtime? The whole sample can be found there - https://github.com/sergey-litvinov/Tests_InternalsVisibleTo UPDATE1: That test code in Program and FakeBuilder classes hasn't access to key.sn file and that library isn't signed, so it hasn't public key at all. It just copying it from CorpLibrary1 by using Reflection.Emit

    Read the article

  • InternalsVisibleTo attribute ain't workin'!

    - by skb
    I am trying to use the InternalsVisibleTo assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says: 'MyClassName' is inaccessible due to its protection level Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas?

    Read the article

  • Using [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Windows")] To expose Int

    - by Anthony
    Ok so I had a qustion awhile back regarding Silverlight 4 Data Binding with anonymous types, one of the answers was to use [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Windows")] in your AssemblyInfo.cs file. I tried this and it works! I know I'm making all my internal properties classes and methods visible to the System.Windows Assembley. But what kind of risk is this with the following in mind: The product is a hosted silverlight based web application, so it wont be distributed. Thanks in advance

    Read the article

  • C# InternalsVisibleTo() attribute for VBNET 2.0 while testing?

    - by Will Marcouiller
    I'm building an Active Directory wrapper in VBNET 2.0 (can't use later .NET) in which I have the following: IUtilisateur IGroupe IUniteOrganisation These interfaces are implemented in internal classes (Friend in VBNET), so that I want to implement a façade in order to instiate each of the interfaces with their internal classes. This will allow the architecture a better flexibility, etc. Now, I want to test these classes (Utilisateur, Groupe, UniteOrganisation) in a different project within the same solution. However, these classes are internal. I would like to be able to instantiate them without going through my façade, but only for these tests, nothing more. Here's a piece of code to illustrate it: public static class DirectoryFacade { public static IGroupe CreerGroupe() { return new Groupe(); } } // Then in code, I would write something alike: public partial class MainForm : Form { public MainForm() { IGroupe g = DirectoryFacade.CreerGroupe(); // Doing stuff with instance here... } } // My sample interface: public interface IGroupe { string Domaine { get; set; } IList<IUtilisateur> Membres { get; } } internal class Groupe : IGroupe { private IList<IUtilisateur> _membres; internal Groupe() { _membres = new List<IUtilisateur>(); } public string Domaine { get; set; } public IList<IUtilisateur> Membres { get { return _membres; } } } I heard of InternalsVisibleTo() attribute, recently. I was wondering whether it is available in VBNET 2.0/VS2005 so that I could access the assmebly's internal classes for my tests? Otherwise, how could I achieve this?

    Read the article

  • Hide public method used to help test a .NET assembly

    - by ChrisW
    I have a .NET assembly, to be released. Its release build includes: A public, documented API of methods which people are supposed to use A public but undocumented API of other methods, which exist only in order to help test the assembly, and which people are not supposed to use The assembly to be released is a custom control, not an application. To regression-test it, I run it in a testing framework/application, which uses (in addition to the public/documented API) some advanced/undocumented methods which are exported from the control. For the public methods which I don't want people to use, I excluded them from the documentation using the <exclude> tag (supported by the Sandcastle Help File Builder), and the [EditorBrowsable] attribute, for example like this: /// <summary> /// Gets a <see cref="IEditorTransaction"/> instance, which helps /// to combine several DOM edits into a single transaction, which /// can be undone and redone as if they were a single, atomic operation. /// </summary> /// <returns>A <see cref="IEditorTransaction"/> instance.</returns> IEditorTransaction createEditorTransaction(); /// <exclude/> [EditorBrowsable(EditorBrowsableState.Never)] void debugDumpBlocks(TextWriter output); This successfully removes the method from the API documentation, and from Intellisense. However, if in a sample application program I right-click on an instance of the interface to see its definition in the metadata, I can still see the method, and the [EditorBrowsable] attribute as well, for example: // Summary: // Gets a ModelText.ModelDom.Nodes.IEditorTransaction instance, which helps // to combine several DOM edits into a single transaction, which can be undone // and redone as if they were a single, atomic operation. // // Returns: // A ModelText.ModelDom.Nodes.IEditorTransaction instance. IEditorTransaction createEditorTransaction(); // [EditorBrowsable(EditorBrowsableState.Never)] void debugDumpBlocks(TextWriter output); Questions: Is there a way to hide a public method, even from the meta data? If not then instead, for this scenario, would you recommend making the methods internal and using the InternalsVisibleTo attribute? Or would you recommend some other way, and if so what and why? Thank you.

    Read the article

  • What is [assembly: InternalsVisibleTo("MyAssembly")]? A statement, directive, ...?

    - by Alix
    Hi. Sorry about the vocabulary question but I can't find this anywhere: how do you call this below? [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyAssembly")] Is it a statement, a directive, ... ? I want to indicate that you have to insert that line in order to give MyAssembly access to your assembly's internal members, but I'd like to use a more specific term than "line". Thanks!

    Read the article

  • Unit testing internal methods in a strongly named assembly/project

    - by Rohit Gupta
    If you need create Unit tests for internal methods within a assembly in Visual Studio 2005 or greater, then we need to add an entry in the AssemblyInfo.cs file of the assembly for which you are creating the units tests for. For e.g. if you need to create tests for a assembly named FincadFunctions.dll & this assembly contains internal/friend methods within which need to write unit tests for then we add a entry in the FincadFunctions.dll’s AssemblyInfo.cs file like so : 1: [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests")] where FincadFunctionsTests is the name of the Unit Test project which contains the Unit Tests. However if the FincadFunctions.dll is a strongly named assembly then you will the following error when compiling the FincadFunctions.dll assembly :      Friend assembly reference “FincadFunctionsTests” is invalid. Strong-name assemblies must specify a public key in their InternalsVisibleTo declarations. Thus to add a public key token to InternalsVisibleTo Declarations do the following: You need the .snk file that was used to strong-name the FincadFunctions.dll assembly. You can extract the public key from this .snk with the sn.exe tool from the .NET SDK. First we extract just the public key from the key pair (.snk) file into another .snk file. sn -p test.snk test.pub Then we ask for the value of that public key (note we need the long hex key not the short public key token): sn -tp test.pub We end up getting a super LONG string of hex, but that's just what we want, the public key value of this key pair. We add it to the strongly named project "FincadFunctions.dll" that we want to expose our internals from. Before what looked like: 1: [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests")] Now looks like. 1: [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("FincadFunctionsTests, 2: PublicKey=002400000480000094000000060200000024000052534131000400000100010011fdf2e48bb")] And we're done. hope this helps

    Read the article

  • Friend Assemblies in C#

    - by Tim Long
    I'm trying to create some 'friend assemblies' using the [InternalsVisibleTo()] attribute, but I can't seem to get it working. I've followed Microsoft's instructions for creating signed friend assemblies and I can't see where I'm going wrong. So I'll detail my steps here and hopefully someone can spot my deliberate mistake...? Create a strong name key and extract the public key, thus: sn -k StrongNameKey sn -p public.pk sn -tp public.pk Add the strong name key to each project and enable signing. Create a project called Internals and a class with an internal property: namespace Internals { internal class ClassWithInternals { internal string Message { get; set; } public ClassWithInternals(string m) { Message = m; } } } Create another project called TestInternalsVisibleTo: namespace TestInternalsVisibleTo { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var c = new Internals.ClassWithInternals("Test"); Console.WriteLine(c.Message); } } } Edit the AssemblyInfo.cs file for the Internals project, and add teh necessary attribute: [assembly: AssemblyTitle("AssemblyWithInternals")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Internals")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("41c590dc-f555-48bc-8a94-10c0e7adfd9b")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("TestInternalsVisibleTo PublicKey=002400000480000094000000060200000024000052534131000400000100010087953126637ab27cb375fa917c35b23502c2994bb860cc2582d39912b73740d6b56912c169e4a702bedb471a859a33acbc8b79e1f103667e5075ad17dffda58988ceaf764613bd56fc8f909f43a1b177172bc4143c96cf987274873626abb650550977dcad1bb9bfa255056bb8d0a2ec5d35d6f8cb0a6065ec0639550c2334b9")] And finally... build! I get the following errors: error CS0122: 'Internals.ClassWithInternals' is inaccessible due to its protection level error CS1729: 'Internals.ClassWithInternals' does not contain a constructor that takes 1 arguments error CS1061: 'Internals.ClassWithInternals' does not contain a definition for 'Message' and no extension method 'Message' accepting a first argument of type 'Internals.ClassWithInternals' could be found (are you missing a using directive or an assembly reference?) Basically, it's as if I had not used the InternalsVisibleTo attrbute. Now, I'm not going to fall into the trap of blaming the tools, so what's up here? Anyone?

    Read the article

  • How to define implementation details?

    - by woni
    In our project, an assembly combines logic for the IoC-Container, the project internals and the communication layer. The current version evolved to have only internal classes in addin assemblies. My main problem with this approach is, that the entry point is only available over the IoC-Container. It is not possible to use anything else than reflection to initialize the assembly. Everything behind the IoC-Interface is defined as implementation detail and therefore not intended for usages outside. It is well known that you should not test implementation detail (such as private and internal methods), because they should be tested through the public interface. It is also well known, that your tests should not use the IoC-Container to setup the SUTs, because that would result in too much dependencies. So we are using the InternalsVisibleTo-Attribute to make internals visible to our test assemblies and test the so called implementation details. I recognized that one problem could be the mixup between different concerns in that assembly, changing this would make this discussion useless, because classes have to be defined public. Ignoring my concerns with this, isn't the need to test a class enough reason to make it public, the usages of InternalsVisibleTo seems unintended, and a little bit "hacky". The approach to test only against the publicly available IoC-Container is too costly and would result in integration style tests. The pros of using internals are, that the usages are well known and do not have to be implemented like a public method would have to be (documentation, completeness, versioning,...). Is there a solution, to not test against internals, but keep their advantages over public classes, or do we have to redefine what an implementation detail is.

    Read the article

  • Unity framework DependencyAttribute only works for public properties?

    - by rally25rs
    I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties that I didn't really want exposed outside my DLLs to internal. Then I started getting exceptions. So it seems that using the [Dependency] attribute in Unity only works for public properties. I suppose that makes sense since the internal and private props wouldnt be visible to the Unity assembly, but feels really dirty to have a bunch of public properties that you never want anyone to set or be able to set, other than Unity. Is there a way to let unity set internal or private properties too? Here is the unit test I'd like to see pass. Currently only the public prop test passes: [TestFixture] public class UnityFixture { [Test] public void UnityCanSetPublicDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasPublicDep, HasPublicDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasPublicDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.dep); } [Test] public void UnityCanSetInternalDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasInternalDep, HasInternalDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasInternalDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.dep); } [Test] public void UnityCanSetPrivateDependency() { UnityContainer container = new UnityContainer(); container.RegisterType<HasPrivateDep, HasPrivateDep>(); container.RegisterType<TheDep, TheDep>(); var i = container.Resolve<HasPrivateDep>(); Assert.IsNotNull(i); Assert.IsNotNull(i.depExposed); } } public class HasPublicDep { [Dependency] public TheDep dep { get; set; } } public class HasInternalDep { [Dependency] internal TheDep dep { get; set; } } public class HasPrivateDep { [Dependency] private TheDep dep { get; set; } public TheDep depExposed { get { return this.dep; } } } public class TheDep { } Updated: I noticed the call stack to set the property passed from: UnityCanSetPublicDependency() --> Microsoft.Practices.Unity.dll --> Microsoft.Practices.ObjectBuilder2.dll --> HasPublicDep.TheDep.set() So in an attempt to at least make the internal version work, I added these to my assembly's properties: [assembly: InternalsVisibleTo("Microsoft.Practices.Unity")] [assembly: InternalsVisibleTo("Microsoft.Practices.Unity.Configuration")] [assembly: InternalsVisibleTo("Microsoft.Practices.ObjectBuilder2")] However, no change. Unity/ObjectBuilder still won't set the internal property

    Read the article

  • Is there any way, short of "copy and paste inheritence" to share a .net class with a Silverlight app

    - by Jekke
    I have a project in two parts: a Silverlight front end and a WCF duplex service. Ideally, I would like to pass a message of a custom type (call it TradeOffer) from the WCF service to be consumed by the Silverlight application. When I try to, I get an error that indicates I can't pass an object of an unknown type across the wire like that and that, maybe, I could do so if I used the InternalsVisibleTo attribute on the server component. I'm not sure if that would work in this environment and know it would be messy in development. I originally put the message definition in a library to be used by both the service and the client, but couldn't add a reference to the library from the Silverlight client (because it's not a Silverlight assembly.) Is there some way I can access the definition of a message class from both the Silverlight client that consumes it and the service that publishes it without using the InternalsVisibleTo attribute or should I write the application another way?

    Read the article

  • Moq Testing a private method .Many posts but still cannot make one example work

    - by devnet247
    Hi, I have seen many posts and questions about "Mocking a private method" but still cannot make it work and not found a real answer. Lets forget the code smell and you should not do it etc.... From what I understand I have done the following: 1) Created a class Library "MyMoqSamples" 2) Added a ref to Moq and NUnit 3) Edited the AssemblyInfo file and added [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("MyMoqSamples")] 4) Now need to test a private method.Since it's a private method it's not part of an interface. 5) added the following code [TestFixture] public class Can_test_my_private_method { [Test] public void Should_be_able_to_test_my_private_method() { //TODO how do I test my DoSomthing method } } public class CustomerInfo { public string Name { get; set; } public string Surname { get; set; } } public interface ICustomerService { List<CustomerInfo> GetCustomers(); } public class CustomerService: ICustomerService { public List<CustomerInfo> GetCustomers() { return new List<CustomerInfo> {new CustomerInfo {Surname = "Bloggs", Name = "Jo"}}; } protected virtual void DoSomething() { } } Could you provide me an example on how you would test my private method? Thanks a lot

    Read the article

  • Unit Testing using InternalsVisibleToAttribute requires compiling with /out:filename.ext?

    - by Will Marcouiller
    In my most recent question: Unit Testing Best Practice? / C# InternalsVisibleTo() attribute for VBNET 2.0 while testing?, I was asking about InternalsVisibleToAttribute. I have read the documentation on how to use it, and everything is fine and understood. However, I can't instantiate my class Groupe from my Testing project. I want to be able to instantiate my internal class in my wrapper assembly, from my testing assembly. Any help is appreciated! EDIT #1 Here's the compile-time error I get when I do try to instantiate my type: Erreur 2 'Carra.Exemples.Blocs.ActiveDirectory.Groupe' n'est pas accessible dans ce contexte, car il est 'Private'. C:\Open\Projects\Exemples\Src\Carra.Exemples.Blocs.ActiveDirectory\Carra.Exemples.Blocs.ActiveDirectory.Tests\GroupeTests.vb 9 18 Carra.Exemples.Blocs.ActiveDirectory.Tests (This says that my type is not accessible in this context, because it is private.) But it's Friend (internal)! EDIT #2 Here's a piece of code as suggested for the Groupe class implementing the Public interface IGroupe: #Region "Importations" Imports System.DirectoryServices Imports System.Runtime.CompilerServices #End Region <Assembly: InternalsVisibleTo("Carra.Exemples.Blocs.ActiveDirectory.Tests")> Friend Class Groupe Implements IGroupe #Region "Membres privés" Private _classe As String = "group" Private _domaine As String Private _membres As CustomSet(Of IUtilisateur) Private _groupeNatif As DirectoryEntry #End Region #Region "Constructeurs" Friend Sub New() _membres = New CustomSet(Of IUtilisateur)() _groupeNatif = New DirectoryEntry() End Sub Friend Sub New(ByVal domaine As String) If (String.IsNullOrEmpty(domaine)) Then Throw New ArgumentNullException() _domaine = domaine _membres = New CustomSet(Of IUtilisateur)() _groupeNatif = New DirectoryEntry(domaine) End Sub Friend Sub New(ByVal groupeNatif As DirectoryEntry) _groupeNatif = groupeNatif _domaine = _groupeNatif.Path _membres = New CustomSet(Of IUtilisateur)() End Sub #End Region And the code trying to use it: #Region "Importations" Imports NUnit.Framework Imports Carra.Exemples.Blocs.ActiveDirectory.Tests #End Region <TestFixture()> _ Public Class GroupeTests <Test()> _ Public Sub CreerDefaut() Dim g As Groupe = New Groupe() Assert.IsNotNull(g) Assert.IsInstanceOf(Groupe, g) End Sub End Class EDIT #3 Damn! I have just noticed that I wasn't importing the assembly in my importation region. Nope, didn't solve anything =( Thanks!

    Read the article

  • How to unit test private methods in BDD / TDD?

    - by robert_d
    I am trying to program according to Behavior Driven Development, which states that no line of code should be written without writing failing unit test first. My question is, how to use BDD with private methods? How can I unit test private methods? Is there better solution than: - making private methods public first and then making them private when I write public method that uses those private methods; or - in C# making all private methods internal and using InternalsVisibleTo attribute. Robert

    Read the article

  • Is it possible to compile IronRuby code to a .NET assembly (EXE or DLL)

    - by Chris Ammerman
    My scenario consists of the following points. I have a packaged software product I am developing in C# Since it is a packaged product, the public interfaces of the assemblies need to be tightly controlled... All assemblies are strong-named Any classes that don't absolutely have to be "public" are "internal" I want to write unit tests for those "internal" classes, since they are the bulk of the code And finally.... I want to try writing the unit tests in Ruby. Since the unit tests would be external to the assembly containing the code under test, the assemblies under test would each need to have an "InternalsVisibleTo" attribute specifying the name of the unit test assembly. Which of course would mean that the Ruby unit tests would have to compile down to a .NET assembly so they can be given access in this way. Can this be done? If so, how? All I can find on the web about "compiling IronRuby" is about building the actual IronRuby runtime from source.

    Read the article

  • Any homologue of InternalsVisibleToAttribute, but for internal classes?

    - by Will Marcouiller
    In my most recent question: Unit Testing Best Practice? / C# InternalsVisibleTo() attribute for VBNET 2.0 while testing?, I was asking about InternalsVisibleToAttribute. I have read the documentation on how to use it, and everything is fine and understood. However, I can't instantiate my class Groupe from my Testing project. I want to be able to instantiate my internal class in my wrapper assembly, from my testing assembly. Any help is appreciated! EDIT Here's the compile-time error I get when I do try to instantiate my type: Erreur 2 'Carra.Exemples.Blocs.ActiveDirectory.Groupe' n'est pas accessible dans ce contexte, car il est 'Private'. C:\Open\Projects\Exemples\Src\Carra.Exemples.Blocs.ActiveDirectory\Carra.Exemples.Blocs.ActiveDirectory.Tests\GroupeTests.vb 9 18 Carra.Exemples.Blocs.ActiveDirectory.Tests (This says that my type is not accessible in this context, because it is private.) But it's Friend (internal)!

    Read the article

  • Hiding an internal interface in a "friend" assembly

    - by dmo
    I have two assemblies: A and B. A has InternalsVisibleTo set for B. I would like to make calls from A to get information that can only be known by a type defined in B in a way that keeps things internal. I can do this using an internal interface defined in A and implemented explicitly in B. Assembly A internal interface IHasData { Data GetData(); } class ClassA { DoSomething(IHasData); } Assembly B public abstract class ClassB : IHasData { Data IHasData.GetData() { /** do something internal **/ } } The trouble comes when someone references assembly B and derives from ClassB - they get the error: "The type 'AssemblyA.IHasData' is defined in an assembly that is not referenced" even though that type should be invisible to them. If I look at the public type definition I see what I expect - ClassB with no interfaces implemented. Why do I get this error? All of the implementation is in assembly B. I could use IHasData internally in ClassB and that wouldn't require assembly A to be referenced. Can someone help me understand what is going on?

    Read the article

  • Secure C# Assemblies from unauthorized Callers

    - by Creepy Gnome
    Is there any way to secure your assembly down to the class/property & class/method level to prevent the using/calling of them from another assembly that isn't signed by our company? I would like to do this without any requirements on strong naming (like using StrongNameIdentityPermission) and stick with how an assembly is signed. I really do not want to resort to using the InternalsVisibleTo attribute as that is not maintainable in a ever changing software ecosystem. For example: Scenario One Foo.dll is signed by my company and Bar.dll is not signed at all. Foo has Class A Bar has Class B Class A has public method GetSomething() Class B tries to call Foo.A.GetSomething() and is rejected Rejected can be an exception or being ignored in someway Scenario Two Foo.dll is signed by my company and Moo.dll is also signed by my company. Foo has Class A Moo has Class C Class A has public method GetSomething() Class C tries to call Foo.A.GetSomething() and is not rejected

    Read the article

  • NuGet JustMock

    - by mehfuzh
    As most of us already know JustMock got  a free edition. The free edition is not a stripped down of the features of the full edition but I would rather say its a strip down of the type you can mock. Technically, free version runs on  proxy as full version runs on proxy + profiler. In full version, It switches to profiler when you are mocking final methods or sealed class or anything else that can not be done using inheritance. Like in full version you can mock non public methods , in free version you can still do it but it has to be virtual for protected or must be done through InternalsVisibleTo attribute for internal virtual methods (If you have access to the source and can apply the attribute). Now, you can get a copy of free edition from the product page. Install it and off you go. But it is also exposed to NuGet. Those of you are not familiar with NuGet (that will be odd). But still NuGet is the centralized package manager from Microsoft that cuts the workflow of manual inclusion of  libraries in your project. I think NuGet in future will limit the scope of  “.vsi” packages and installers because of its ease (except in some cases). Its similar to ruby gems. In ruby, virtually you can install any library in this way “gems  install <target_library>” and you are off to go. It will check the dependencies, install them or less prompt with the steps you need to do.   Now sticking to the post, to get started you first need to install NuGet package manager. Once you have completed the step pressing “Ctrl + W, Ctrl + Z” it will bring up an console like one below:   Once you are here, you just have to type “install-package justmock” Next, it will should print the confirmation when the installation is complete: Moving to visual studio solution explorer, you will now see:   Finally, NuGet is still in its early ages and steps that are shown here may not remain the same in coming releases, but feel free to enjoy what is out there right now. Regarding JustMock free edition, there is a nice post by Phil Japikse at Introducing JustMock Free Edition. I think its worth checking if not already.   Have fun and happy holidays!

    Read the article

  • Why is Microsoft under-supporting or under-developping VBNET?

    - by Will Marcouiller
    I ran into a situation where the lack of some features has become somewhat frustrating while developping in VB.NET 2.0. Since my first day of programming, I've always been a C programmer, and still am. Naturally, I chose C# as my favorite .NET language. Recently, a customer of mine has obliged that all of his development projects which disregard SharePoint development have to be written in VB.NET 2.0, that is to avoid conflictual systems to come into some problems. That is a legitimate choice of his which I approve somehow, since he's running some old central systems and is slowly migrating toward latest technologies. As for me, I would have prefered to go with C#, but then, never having done much VB in my life, I see it as an opportunity to learn somethings new, how to handle this and that in VBNET, etc. Except that the syntax is really too verbose for me, which is a pain! I got used to it and that is fine. However, I recently wanted to use the InternalsVisibleToAttribute which I discovered lastly here on SO. But then, in addition to not being able to have lambda expression that returns no value, which I discovered months ago, today I learn that I can't use the attribute in VBNET! Here is what I have read in an article: [...] Sorry VB.Net developers, Microsoft is again shunning you guys and this attribute is NOT available to you.... :( And here is the link: InternalsVisibleTo: Testing internal methods in .Net 2.0 I have heard from Anders Hejlsberg mouth while watching a Webcast from his presentation of .NET 4.0 Framework that the VBNET team was working or has worked in collaboration with the C# team (Eric Lippert and others) in order to bring VBNET to offer the same features as C# offers. But then, I say to myself that the VBNET team has a huge step forward to make, if already in .NET 2.0, some of the most important features lacked! So my question is this: Why is Microsoft under-supporting or under-developping VBNET? Will VBNET ever be lacking the C# features?

    Read the article

  • Unit test complex classes with many private methods

    - by Simon G
    Hi, I've got a class with one public method and many private methods which are run depending on what parameter are passed to the public method so my code looks something like: public class SomeComplexClass { IRepository _repository; public SomeComplexClass() this(new Repository()) { } public SomeComplexClass(IRepository repository) { _repository = repository; } public List<int> SomeComplexCalcualation(int option) { var list = new List<int>(); if (option == 1) list = CalculateOptionOne(); else if (option == 2) list = CalculateOptionTwo(); else if (option == 3) list = CalculateOptionThree(); else if (option == 4) list = CalculateOptionFour(); else if (option == 5) list = CalculateOptionFive(); return list; } private List<int> CalculateOptionOne() { // Some calculation } private List<int> CalculateOptionTwo() { // Some calculation } private List<int> CalculateOptionThree() { // Some calculation } private List<int> CalculateOptionFour() { // Some calculation } private List<int> CalculateOptionFive() { // Some calculation } } I've thought of a few ways to test this class but all of them seem overly complex or expose the methods more than I would like. The options so far are: Set all the private methods to internal and use [assembly: InternalsVisibleTo()] Separate out all the private methods into a separate class and create an interface. Make all the methods virtual and in my tests create a new class that inherits from this class and override the methods. Are there any other options for testing the above class that would be better that what I've listed? If you would pick one of the ones I've listed can you explain why? Thanks

    Read the article

  • When mocking a class with Moq, how can I CallBase for just specific methods?

    - by Daryn
    I really appreciate Moq's Loose mocking behaviour that returns default values when no expectations are set. It's convenient and saves me code, and it also acts as a safety measure: dependencies won't get unintentionally called during the unit test (as long as they are virtual). However, I'm confused about how to keep these benefits when the method under test happens to be virtual. In this case I do want to call the real code for that one method, while still having the rest of the class loosely mocked. All I have found in my searching is that I could set mock.CallBase = true to ensure that the method gets called. However, that affects the whole class. I don't want to do that because it puts me in a dilemma about all the other properties and methods in the class that hide call dependencies: if CallBase is true then I have to either Setup stubs for all of the properties and methods that hide dependencies -- Even though my test doesn't think it needs to care about those dependencies, or Hope that I don't forget to Setup any stubs (and that no new dependencies get added to the code in the future) -- Risk unit tests hitting a real dependency. Q: With Moq, is there any way to test a virtual method, when I mocked the class to stub just a few dependencies? I.e. Without resorting to CallBase=true and having to stub all of the dependencies? Example code to illustrate (uses MSTest, InternalsVisibleTo DynamicProxyGenAssembly2) In the following example, TestNonVirtualMethod passes, but TestVirtualMethod fails - returns null. public class Foo { public string NonVirtualMethod() { return GetDependencyA(); } public virtual string VirtualMethod() { return GetDependencyA();} internal virtual string GetDependencyA() { return "! Hit REAL Dependency A !"; } // [... Possibly many other dependencies ...] internal virtual string GetDependencyN() { return "! Hit REAL Dependency N !"; } } [TestClass] public class UnitTest1 { [TestMethod] public void TestNonVirtualMethod() { var mockFoo = new Mock<Foo>(); mockFoo.Setup(m => m.GetDependencyA()).Returns(expectedResultString); string result = mockFoo.Object.NonVirtualMethod(); Assert.AreEqual(expectedResultString, result); } [TestMethod] public void TestVirtualMethod() // Fails { var mockFoo = new Mock<Foo>(); mockFoo.Setup(m => m.GetDependencyA()).Returns(expectedResultString); // (I don't want to setup GetDependencyB ... GetDependencyN here) string result = mockFoo.Object.VirtualMethod(); Assert.AreEqual(expectedResultString, result); } string expectedResultString = "Hit mock dependency A - OK"; }

    Read the article

1