I am trying to write an attribute to apply security to a method. Something that would look like this:
[CustomAuthorization(SecurityAction.Demand)]
public void DoSomething()
{
//Do Something
}
so I have my Attribute on another assembly:
public sealed class AuthorizationAttribute : CodeAccessSecurityAttribute
{
public override IPermission CreatePermission()
{
if (!/*authorize here*/)
{
return new CustomPermission(PermissionState.Unrestricted);
}
throw new Exception("IdentificationFailure.");
}
}
public AuthorizationAttribute(SecurityAction securityAction)
: base(securityAction) { }
}
So far it works.
I run my main program and it does its job.
Now I go and to modify the assembly having the attribute, build it. no problem.
I go back in my main program try to build and there it fails. It cannot copy the new built dll because the old one is still in use by a process.
Does anybody have any idea what would be happening here?
If you're using VS2010, there is an issue with vhost.exe not releasing the instance. You can end process on it for now until MS comes out with a fix.
It sounds like you haven't exited your main program before trying to rebuild it. Check your running processes for references to your main program or your security attribute dll. Process Explorer can be a real big help here.
Just been trouble shooting the same issue and it boiled down to the fact that we were using testaccessors to test private methods. When unloading the unittest projects, the assembly is released. Our assembly gets locked when compiling. Haven't found a solution to this yet, but have submitted a bug to ms. Are you using testaccessors?
Also see Assembly is being used by another process and https://stackoverflow.com/questions/6895038/testaccessor-impl-of-codeaccesssecurityattribute-locks-assembly
MS bug:
https://connect.microsoft.com/VisualStudio/feedback/details/682485/use-of-testaccessor-and-impl-of-codeaccesssecurityattribute-locks-assembly#details
Related
I've put together an application that I plan on writing plugins for. In order to keep everything separate and make updating easy, I figured writing individual class libraries would be the best solution. The problem I'm running into is that my dll can't communicate with it's parent. Is this only one-way communication?
I dynamically load the dll at runtime and can tell it to do what I want it to do without any problems. The problem I encounter is after it's finished doing its work, I can't get it to signal the parent that it's finished. I don't want the parent to hang and wait for it, so I open a new thread in the dll to do the "work". I tried something as simple as passing a self reference to the dll when it's opened, but I get an access violation when I try to access something on the parent from the DLL.
All of my searches come up mentioning WCF and named pipes. I feel like it should be a simpler solution than this, like the self reference. Is WCF the way to go for this? Any other/better solutions?
ModuleHandler.cs:
using System;
using System.IO;
using System.Reflection;
namespace Collector
{
class ModuleHandler
{
public ModuleHandler()
{
LoadStaticModules();
}
private void LoadStaticModules()
{
Assembly assembly = Assembly.Load("Module_WaitForIt");
Type[] types = assembly.GetTypes();
dynamic module = Activator.CreateInstance(types[0]);
module.StartSleeping();
}
public void TestMethod()
{
Console.WriteLine("TestMethod()");
}
}
}
Module_WaitForIt:
using System.Threading;
namespace Module_WaitForIt
{
public class WaitModule
{
public void StartSleeping()
{
System.Console.WriteLine("Sleeping");
Thread t = new Thread(() => SleepyThread());
}
public void SleepyThread()
{
Thread.Sleep(10000);
}
}
}
In this example, I want Module_WaitForIt.SleepyThread() to call ModuleHandler.TestMethod() after it sleeps for 10 seconds.
There are a number of ways to do this that don't need WCF, e.g.
Your dynamically-loaded assembly can implement an interface or be derived from a base class that is defined in an assembly that is referenced by both your assembly and your parent assembly. This interface or base class could, for example, include events which you can raise to pass data to your parent assembly.
Your dynamically-loaded assembly can include methods that take parameters whose type is an interface defined in another assembly. When your parent calls your method, it passes you a concrete instance that implements that interface, and you can call it when appropriate.
I was wondering if it was possible to have a start-up script before running any load tests? For example, perhaps to seed some data or clear anything down prior to the tests executing.
In my instance I have a mixed bag of designer and coded tests. Put it simply, I have:
Two coded tests
A designer created web test which points to these coded tests
A load test which runs the designer
I have tried adding a class and decorating with the attributes [TestInitialize()], [ClassInitialize()] but this code doesn't seem to get run.
Some basic code to show this in practice (see below). Is there a way of doing this whereby I can have something run only the once before test run?
[TestClass]
public class Setup : WebTest
{
[TestInitialize()]
public static void Hello()
{
// Run some code
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
return null;
}
}
Probably should also mention that on my coded tests I have added these attributes and they get ignored. I have come across a workaround which is to create a Plugin.
EDIT
Having done a little more browsing around I found this article on SO which shows how to implement a LoadTestPlugin.
Visual Studio provides a way of running a script before and also after a test run. They are intended for use in deploying data for a test and cleaning up after a test. The scripts are specified on the "Setup and cleanup" page in the ".testsettings" file.
A load test plugin can contain code to run before and after any test cases are executed, also at various stages during test execution. The interface is that events are raised at various points during the execution of a load test. User code can be called when these events occur. The LoadTestStarting event is raised before any test cases run. See here for more info.
If you are willing to use NUnit you have SetUp/TearDown for a per test scope and TestFixtureSetUp/TestFixtureTearDown to do something similar for a class (TestFixture)
Maybe a bit of a hack, but you can place your code inside the static constructor of your test class as it will automatically run exactly once before the first instance is created or any static members are referenced:
[TestClass]
public class Setup : WebTest
{
static Setup()
{
// prepare data for test
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
return null;
}
}
I am using Approval Tests. On my dev machine I am happy with DiffReporter that starts TortoiseDiff when my test results differ from approved:
[UseReporter(typeof (DiffReporter))]
public class MyApprovalTests
{ ... }
However when the same tests are running on Teamcity and results are different tests fail with the following error:
System.Exception : Unable to launch: tortoisemerge.exe with arguments ...
Error Message: The system cannot find the file specified
---- System.ComponentModel.Win32Exception : The system cannot find the file
specified
Obviously it cannot find tortoisemerge.exe and that is fine because it is not installed on build agent. But what if it gets installed? Then for each fail another instance of tortoisemerge.exe will start and nobody will close it. Eventually tons of tortoisemerge.exe instances will kill our servers :)
So the question is -- how tests should be decorated to run Tortoise Diff on local machine
and just report errors on build server? I am aware of #IF DEBUG [UseReporter(typeof (DiffReporter))] but would prefer another solution if possible.
There are a couple of solutions to the question of Reporters and CI. I will list them all, then point to a better solution, which is not quite enabled yet.
Use the AppConfigReporter. This allows you to set the reporter in your AppConfig, and you can use the QuietReporter for CI.
There is a video here, along with many other reporters. The AppConfigReporter appears at 6:00.
This has the advantage of separate configs, and you can decorate at the assembly level, but has the disadvantage of if you override at the class/method level, you still have the issue.
Create your own (2) reporters. It is worth noting that if you use a reporter, it will get called, regardless as to if it is working in the environment. IEnvironmentAwareReporter allows for composite reporters, but will not prevent a direct call to the reporter.
Most likely you will need 2 reporters, one which does nothing (like a quiet reporter) but only works on your CI server, or when called by TeamCity. Will call it the TeamCity Reporter. And One, which is a multiReporter which Calls teamCity if it is working, otherwise defers to .
Use a FrontLoadedReporter (not quite ready). This is how ApprovalTests currently uses NCrunch. It does the above method in front of whatever is loaded in your UseReporter attribute. I have been meaning to add an assembly level attribute for configuring this, but haven't yet (sorry) I will try to add this very soon.
Hope this helps.
Llewellyn
I recently came into this problem myself.
Borrowing from xunit and how they deal with TeamCity logging I came up with a TeamCity Reporter based on the NCrunch Reporter.
public class TeamCityReporter : IEnvironmentAwareReporter, IApprovalFailureReporter
{
public static readonly TeamCityReporter INSTANCE = new TeamCityReporter();
public void Report(string approved, string received) { }
public bool IsWorkingInThisEnvironment(string forFile)
{
return Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null;
}
}
And so I could combine it with the NCrunch reporter:
public class TeamCityOrNCrunchReporter : FirstWorkingReporter
{
public static readonly TeamCityOrNCrunchReporter INSTANCE =
new TeamCityOrNCrunchReporter();
public TeamCityOrNCrunchReporter()
: base(NCrunchReporter.INSTANCE,
TeamCityReporter.INSTANCE) { }
}
[assembly: FrontLoadedReporter(typeof(TeamCityOrNCrunchReporter))]
I just came up with one small idea.
You can implement your own reporter, let's call it DebugReporter
public class DebugReporter<T> : IEnvironmentAwareReporter where T : IApprovalFailureReporter, new()
{
private readonly T _reporter;
public static readonly DebugReporter<T> INSTANCE = new DebugReporter<T>();
public DebugReporter()
{
_reporter = new T();
}
public void Report(string approved, string received)
{
if (IsWorkingInThisEnvironment())
{
_reporter.Report(approved, received);
}
}
public bool IsWorkingInThisEnvironment()
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
Example of usage,
[UseReporter(typeof(DebugReporter<FileLauncherReporter>))]
public class SomeTests
{
[Test]
public void test()
{
Approvals.Verify("Hello");
}
}
If test is faling, it still would be red - but reporter would not came up.
The IEnvironmentAwareReporter is specially defined for that, but unfortunatelly whatever I return there, it still calls Report() method. So, I put the IsWorkingInThisEnvironment() call inside, which is a little hackish, but works :)
Hope that Llywelyn can explain why it acts like that. (bug?)
I'm using CC.NET and I do have TortoiseSVN installed on the server.
I reconfigured my build server to allow the CC.NET service to interact with the desktop. When I did that, TortiseMerge launched. So I think what's happening is that Approvals tries to launch the tool, but it cant because CC.NET is running as a service and the operating system prevents that behavior by default. If TeamCity runs as a service, you should be fine, but you might want to test.
I have to restrict my .net 4 WPF application so that it can be run only once per machine. Note that I said per machine, not per session.
I implemented single instance applications using a simple mutex until now, but unfortunately such a mutex is per session.
Is there a way to create a machine wide mutex or is there any other solution to implement a single instance per machine application?
I would do this with a global Mutex object that must be kept for the life of your application.
MutexSecurity oMutexSecurity;
//Set the security object
oMutexSecurity = new MutexSecurity();
oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow));
//Create the global mutex and set its security
moGlobalMutex = new Mutex(True, "Global\\{5076d41c-a40a-4f4d-9eed-bf274a5bedcb}", bFirstInstance);
moGlobalMutex.SetAccessControl(oMutexSecurity);
Where bFirstInstance returns if this is the first instance of your application running globally. If you omited the Global part of the mutex or replaced it with Local then the mutex would only be per session (this is proberbly how your current code is working).
I believe that I got this technique first from Jon Skeet.
The MSDN topic on the Mutex object explains about the two scopes for a Mutex object and highlights why this is important when using terminal services (see second to last note).
I think what you need to do is use a system sempahore to track the instances of your application.
If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name.
Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes.
EDIT: Note that I am not aware if this approach works across multiple windows sessions on a machine. I think it should as its an OS level construct but I cant say for sure as i havent tested it that way.
EDIT 2: I did not know this but after reading Stevo2000's answer, i did some looking up as well and I think that the "Global\" prefixing to make the the object applicable to the global namespace would apply to semaphores as well and semaphore, if created this way, should work.
You could open a file with exclusive rights somewhere in %PROGRAMDATA%
The second instance that starts will try to open the same file and fail if it's already open.
How about using the registry?
You can create a registry entry under HKEY_LOCAL_MACHINE.
Let the value be the flag if the application is started or not.
Encrypt the key using some standard symmetric key encryption method so that no one else can tamper with the value.
On application start-up check for the key and abort\continue accordingly.
Do not forget to obfuscate your assembly, which does this encryption\decryption part, so that no one can hack the key in registry by looking at the code in reflector.
I did something similar once.
When staring up the application list, I checked all running processes for a process with identical name, and if it existed I would not allow to start the program.
This is not bulletproof of course, since if another application have the exact same process name, your application will never start, but if you use a non-generic name it will probably be more than good enough.
For the sake of completeness, I'd like to add the following which I just found now:
This web site has an interesting approach in sending Win32 messages to other processes. This would fix the problem of the user renaming the assembly to bypass the test and of other assemblies with the same name.
They're using the message to activate the main window of the other process, but it seems like the message could be a dummy message only used to see whether the other process is responding to it to know whether it is our process or not.
Note that I haven't tested it yet.
See below for full example of how a single instace app is done in WPF 3.5
public class SingleInstanceApplicationWrapper :
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
public SingleInstanceApplicationWrapper()
{
// Enable single-instance mode.
this.IsSingleInstance = true;
}
// Create the WPF application class.
private WpfApp app;
protected override bool OnStartup(
Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
app = new WpfApp();
app.Run();
return false;
}
// Direct multiple instances.
protected override void OnStartupNextInstance(
Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
{
if (e.CommandLine.Count > 0)
{
app.ShowDocument(e.CommandLine[0]);
}
}
}
Second part:
public class WpfApp : System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
WpfApp.current = this;
// Load the main window.
DocumentList list = new DocumentList();
this.MainWindow = list;
list.Show();
// Load the document that was specified as an argument.
if (e.Args.Length > 0) ShowDocument(e.Args[0]);
}
public void ShowDocument(string filename)
{
try
{
Document doc = new Document();
doc.LoadFile(filename);
doc.Owner = this.MainWindow;
doc.Show();
// If the application is already loaded, it may not be visible.
// This attempts to give focus to the new window.
doc.Activate();
}
catch
{
MessageBox.Show("Could not load document.");
}
}
}
Third part:
public class Startup
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceApplicationWrapper wrapper =
new SingleInstanceApplicationWrapper();
wrapper.Run(args);
}
}
You may need to add soem references and add some using statements but it shoudl work.
You can also download a VS example complete solution by downloading the source code of the book from here.
Taken From "Pro WPF in C#3 2008 , Apress , Matthew MacDonald" , buy the book is gold. I did.
I'm trying to write a custom decoupled WMI provider in C#. I've followed the examples and yet whenever I try to access my WMI class from either WMI Studio, through PowerShell, or via wmic, it just hangs there indefinitely until I terminate the provider host app, at which point I get an error ranging from "Invalid Class" to "The remote procedure call failed".
I can see my WMI provider fine if I don't try to actually access an instance of it, so I know it's registering with WMI.
Here's the code I'm running:
[assembly: WmiConfiguration(#"root\CIMV2", HostingModel=ManagementHostingModel.Decoupled)]
[RunInstaller(true)]
public class WmiInstaller : DefaultManagementInstaller { }
[ManagementEntity(Singleton=true)]
[ManagementQualifier("Description", Value="Accesses and manipulates licenses held in the SLN license database.")]
public class SoftwareLicensingNetworkLicenseDatabase {
[ManagementBind]
public SoftwareLicensingNetworkLicenseDatabase() { Test = "OMG!"; }
[ManagementProbe]
public string Test;
}
And then in my main function:
[STAThread]
static void Main() {
InstrumentationManager.RegisterType(typeof(SoftwareLicensingNetworkLicenseDatabase));
Console.ReadLine();
InstrumentationManager.UnregisterType(typeof(SoftwareLicensingNetworkLicenseDatabase));
}
I've tried any number of things to diagnose this issue: switch to .Net 3.5 (I'm using .Net 4.0), change namespace names, use a multi-instance class instead of a singleton, etc.
Any help would be sincerely appreciated!
Nevermind, I figured it out:
Your Main function cannot have STAThread as an attribute. I added it when I was debugging something that required it and had not taken it off. It figures it would take me so long to figure out something so simple and obvious once you think about it.