Powershell Provider - GetItem Path Error - Custom File as Drive - c#

I'm trying to emulate my custom project file as new PS Drive. I am trying to create my custom Powershell Provider that is derived from NavigationCmdletProvider. I have overridden PSDriveInfo to read and contain the project from the file and filepath is in the root of PSDriveInfo.
I can't override GetItem properly. What I want to do is use GetNamesFromPath(path, out tableName, out rowNumber) method. Since my custom project is basically dataset, I would like to use tableName to get the DataTable and rowNumber for ID of DataRow.
The problem is that I get the "path doesn't exist" kind of error. It doesn't event get into the overridden method. Am I missing something to override? The filepath doesn't exist really, but I simply need to handle the path and use WriteItemObject with what I want as object(s) returned, without checking is it valid path.
Edit 1:
One thing I noticed is that it never gets into GetItem and therefore into IsValidPath. When I debug and use breakpoints, first I load the drive and then Set-Location to the drive, IsItemContainer is called (it has to be overridden for Set-Location to work).
GetItem and IsValidPath are not called at all, as if it checks for valid path before calling overridden method. Can NavigationCmdletProvider work with non-existing paths (except for the file itself), just work with strings that will manually be handled as paths would?

Make sure you override the IsValidPath and ItemExists methods:
protected override bool IsValidPath(string path)
{
return true;
}
protected override bool ItemExists(string path)
{
return true;
}

If you are extending NavigationCmdletProvider then you should override IsValidPath, ItemExists, GetItem, GetChildItems and possibly other methods depending on what features you want to support for your PS drives.
The best way to find out which methods are missing implementation is to override all the virtual methods and put a breakpoint in each one. Then execute a cmdlet and see in the debugger what gets called and what are the parameter values.
Unfortunately, there isn't a lot of detailed documentation about implementing custom PowerShell providers. However, you can find a quite detailed tutorial on MSDN about this topic with a lot of source code examples. Additionally, you can take a look at the PowerShell VFS project - it's a wrapper around PowerShell provider API to make it easier to build complicated providers.

Related

Activator.CreateInstance returning incorrect type?

I'd be grateful if you could help with this:
I have a base class for a Provider.
This is subclassed to create a
DefaultProvider.
DefaultProvider implements an interface called “IExportProvider”
DefaultProvider is subclassed to create a
DanishProvider.
The base class has various virtual methods that return string values in English.
The DanishProvider overrides these to return strings in Danish.
At runtime, I load either the DefaultProvider or the DanishProvider depending on a config. value. I do this by scanning the current assembly for the type name, which is either “DefaultProvider” or “DanishProvider”, and which implements “IExportProvider”
var importServiceType = assembly.DefinedTypes.FirstOrDefault(type => (type.Name.Equals(providerServiceName, StringComparison.OrdinalIgnoreCase)) && type.ImplementedInterfaces.Any(i => i == typeof(I)));
I then use Activator.CreateInstance to create an instance of the type:
return (IExportProvider)Activator.CreateInstance(importServiceType, …)
Problem
I use the code in a .Net 4.8 Web application, where I load the DanishProvider. This mostly works OK and I can see the Danish strings are returned. However, occasionally (after several days) the application appears to incorrectly load the DefaultProvider, and I see English strings returned.
Once it has switched to English it appears to stay on the DefaultProvider.
Twice I have done an IISRESET which fixes the problem immediately.
The settings
are not being changed.
There is only one type in the assembly called “DanishProvider”
The code is executing on a single UAT server. I have not seen the issue on my local PC.
I do not believe that the issue is related to caching.
Q. Is there a problem with the code approach described above?
Thank you

ASP.Net Idenity - Override FindByName to include extra search criteria

We have a setup where clients run stand-alone version of our system, but they all link to the same Identity Database with Entity Framework.
A user can be registered as a user on many versions of the application, thereby having multiple accounts with the same username, but the applicationId (stored in the web.config) is unique.
What I would like to do is use the UserManager.FindByName function, but have it automatically add the "&& applicationId = X" to the request sent to the context.
Well you can inherit from the UserManager class, but you have to rewrite the original code (.NET now is open source you can find the original code) and add your logic to it. However, this may be a lengthy action.
What i suggest is if you are using Entity Framework search for the user id by name and application id, then pass the id for the FindById method.
If follow down the implementation, you'll eventually find this method:
public virtual Task<TUser> FindByIdAsync(TKey userId)
{
this.ThrowIfDisposed();
return this.GetUserAggregateAsync((Expression<Func<TUser, bool>>) (u => u.Id.Equals(userId)));
}
In order to override this properly, it would have to be inside the UserStore class, since there are loads of internal methods (otherwise you'd have to rewrite every single internal method in the class), and add a new Type Parameter that would accept your ApplicationId, since UserStore is a generic class. Then you would be able to write another FindByIdAsync method, because it's a virtual method and it can't be overridden. You would also have to rewrite the GetUserAggregateAsync internal method, because it isn't prepared to handle your new Type Parameter.
Now, there are probably a few more hiccups that would show up, but you can, ultimately, rewrite this method to suit you, but I would advise against it because it's A LOT of work to achieve something that might be possible in another way.
Docs: http://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNet/Identity/EntityFramework/UserStore-TUser-TRole-TContext-TKey/index.html
Code: https://github.com/aspnet/identity/blob/master/src/Microsoft.AspNet.Identity.EntityFramework/UserStore.cs

Attribute Useage For Checking Method Permissions

I'm trying to implement a security mechanism to automatically test a particular plugins permissions and method security privileges and I've gotten a bit stuck on how to get this working.
I've writing a custom MEF Metadata attribute that takes a constructor property like:
params PluginPermission[] permission
This contains an array of all the permissions that the plugin is granted.
The PluginPermission class looks like:
PluginPermission.cs
public enum PluginPermission
{
CreateUsers,
DeleteUsers,
ReadPassword,
WritePassword,
AddUsersToGroups,
AddGroups,
DeleteGroups
}
I've also written a RequiredPermissionAttribute that targets individual methods and takes one or more PluginPermission objects to tell the system what permissions are required for an individual method to be execute. These are applied to the interface for the plugins like:
ILicensingManagement.cs
[RequiredPermission(PluginPermission.CreateUsers)]
bool AddUser(string userName);
Obviously if the plugin doesn't have the required permissions for a particular method the method is not executed.
What I'm stuck on is how to actually get the test method in the RequiredPermissionAttribute class to run before the method is executed and how to gracefully exit the execution if the permissions requirements for the method are not met by the plugin.
I looked at the xUnit BeforeAfterTestAttribute but the implementation seemed so specific I stuggled to pull the source code apart to arrive at the solution.
I can't comment on MEF specific things but one thing to keep in mind that custom attributes are nothing more than "tags", they do not do anything unless your code specifically checks for them, for example using reflection.
The BeforeAfterTestAttribute of xUnit probably works, because xUnit uses reflection to execute the methods. When it encounters this attribute it changes its behavious accordingly.
Attributes in the .NET framework namespace work because either the CLR checks for them or the compiler does.
I know this doesn't really answer your question completely but it was a bit too long to put into a comment.
Update: you can access the attributes using the Type if it's a class or the MethodInfo if it's a method, e.g.
MethodInfo mi = /* method info */;
Attribute[] attrs = mi.GetCustomAttributes(typeof(RequiredPermissionAttribute), false);
RequiredPermissionAttribute req = attrs.Cast<RequiredPermissionAttribute>().FirstOrDefault();
if ((req != null) && (/* current user does not have the required permission */)) throw new Exception();
But this is not a real security solution, a developer can easily avoid these checks. I've only briefly glanced at it but PostSharp could maybe help you.

Directory tree data type?

What would be the return type of the following method? (T)
public T GetDirectoryContentsRecursively (string path) { ... }
The method will read the contents of a remote directory, and read the contents of each sub-directory and each of that object's sub-directories and so on.
I have thought about using List<object>, where object could be another List<object> etc... but I don't want the caller to have to be casting everything into FileSystemInfos every time they want to use the method.
Every file must be a FileInfo and every directory a DirectoryInfo, both of which inherit the abstract class FileSystemInfo.
I just can't figure out what data type is best used to represent this.
Any ideas? Do I need to make my own DirectoryTree type?
Edit: The data is to be fetched from a server, probably directory by directory, one at a time. What I need to do is take this data and reconstruct it into something that I can pass to the user. This means I can't just pass a DirectoryInfo, then call its GetFileSystemInfos() because the Directory will not exist on the local machine.
I think maybe the approach is wrong, what are you trying to achieve with a tree structure that you can't by using the APIs directory as and when you need to?
If the intention is to just walk the folder/file structure on the remote directory then you don't necessary need to build your own in-memory representation to do this. If you are rendering the structure, just grab the top level, and load other levels on demand.
If you really want to go down this route then you could just return IEnumerable<string> with all the directory and file paths. DirectoryInfo and FileInfo are relatively expensive objects. It all depends on purpose, can you give any more info?
see below information of SortedSet if you are uisng .net 4.0
http://msdn.microsoft.com/en-us/library/dd412070.aspx
and Directory.Enumarate in .net 4.0 is desinged for the task you are doing.
Try something like this:
class MySweetObject{
HashSet fileInfoSet;
HashSet directoryInfoSet;
//Logic needed to manipulate files as you see fit
//Logic needed to access files as you see fit
}
Then write it as:
public MySweetObject GetDirectoryContentsRecursively (string path) { ... }
Create a custom object and pass that around to the caller.

Getting attribute context in C#

Basically I'm trying to implement some sort of poor man's Aspect Oriented Programming in C#. I had thought about using a ContextAttribute but they seem only be be bound at the class level. Is there any way that I can put an attribute in such that it will receive the same parameters as the method which it annotates or some way to access the context in which it fired?
I have this code
public void AddUser(User user)
{
var errors = DataAnnotationsValidationRunner.GetErrors(user);
if (errors.Any())
throw new RulesException(errors);
users.Add(user);
}
from which I would like to extract the first 3 lines so I had something like
[Validated]
public void AddUser(User user)
{
users.Add(user);
}
I think you are missing a third component. Most AOP implementations (e.g. Aspect#) rely on a proxy or interceptor to actually execute the code. In your scenario, you lack whichever component needed to 1) know the attribute exists on the method, and 2) trigger the mechanism (or become it) needed to execute the code within the attribute.
Fortunately, there are already many (fairly) simple solutions available in open source. The simplest option I can think of would be to use a compile-time weaver like PostSharp. Grab a copy of that, and in the samples you'll find several examples of exactly what you are trying to do (you'd be interested in the OnMethodInvocationAspect).
The end result is that your code looks exactly like it does in the sample you provided, yet it's also running the code you wish.
Don't know exactly how your solution should look like, but in C# attributes do not execute code as long as you don't request them (as far as I know). And if you query for the attribute, you also have the context. So there is something wrong with your strategy in my opinion.

Categories