public IPathValue MoveItem(IProviderContext providerContext, string path, string movePath, IPathValue destinationContainer) { if (providerContext == null) { throw new ArgumentNullException(nameof(providerContext)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (destinationContainer == null) { throw new ArgumentNullException(nameof(destinationContainer)); } var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var moveItem = new CloudPathNode(drive.MoveItem((FileSystemInfoContract)nodeValue.Item, movePath, (DirectoryInfoContract)destinationContainer.Item)); var destinationContainerNode = providerContext.ResolvePath(((DirectoryInfoContract)destinationContainer.Item).Id.Value) as CloudPathNode; destinationContainerNode.children.Add(moveItem); moveItem.SetParent(destinationContainerNode); parent.children.Remove(this); SetParent(null); return(moveItem.nodeValue); } throw new InvalidOperationException(); }
public override IEnumerable<IPathNode> GetNodeChildren(IProviderContext context) { foreach( var dataSource in _drive.DataSources) { yield return new DataSourceNodeFactory( dataSource ); } }
public IEnumerable <IPathNode> ResolvePath(IProviderContext providerContext, string path) { var root = driveRegex.Match(path).Groups["Drive"].Value; var drive = pathResolverCache.Keys.Single(p => p.Root == root); return(pathResolverCache[drive].ResolvePath(providerContext, path)); }
public void RenameItem(IProviderContext providerContext, string path, string newName) { if (providerContext == null) { throw new ArgumentNullException(nameof(providerContext)); } var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var fileSystemInfo = (FileSystemInfoContract)nodeValue.Item; fileSystemInfo = drive.RenameItem(fileSystemInfo, newName); if (itemMode == Mode.Directory) { nodeValue = new ContainerPathValue(fileSystemInfo, fileSystemInfo.Name); return; } else if (itemMode == Mode.File) { nodeValue = new LeafPathValue(fileSystemInfo, fileSystemInfo.Name); return; } } throw new InvalidOperationException(); }
public override IEnumerable <IPathNode> ResolvePath(IProviderContext providerContext, string path) { string adjustedPath; var id = BlobStorageDrive.ExtractDriveIdentifier(path, out adjustedPath); var drive = providerContext.Drive as BlobStorageDrive; if (null == drive) { var drives = providerContext.SessionState.Drive.GetAll().OfType <BlobStorageDrive>(); if (null != id) { var rootId = "[" + id.Replace("\\", "/") + "]"; drive = drives.First(m => m.Root == rootId); } if (null == drive) { drive = drives.First(); } } _client = drive.Client; return(base.ResolvePath(providerContext, adjustedPath)); }
public IPathValue NewItem(IProviderContext providerContext, string path, string itemTypeName, object newItemValue) { var newItem = providerContext.InvokeProvider.Item.New(new[] { OriginalObjectPSPath }, path, itemTypeName, newItemValue, providerContext.Force); return(this.Resolve(providerContext, path).First().GetNodeValue()); }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext providerContext) { if (providerContext == null) { throw new ArgumentNullException(nameof(providerContext)); } if (!nodeValue.IsCollection) { return(null); } if (children == null || providerContext.Force && IsProviderPathNode(providerContext)) { children = (((ICloudDrive)providerContext.Drive).GetChildItem((DirectoryInfoContract)nodeValue.Item).Select(f => new CloudPathNode(f))).ToList(); foreach (var child in children) { child.SetParent(this); } } if (!string.IsNullOrEmpty(providerContext.Filter) && !providerContext.ResolveFinalNodeFilterItems) { var regex = new Regex("^" + providerContext.Filter.Replace("*", ".*").Replace('?', '.') + "$"); return(children.Where(i => regex.IsMatch(i.Name))); } return(children); }
public override async Task <bool> IsSatisfiedAsync(IProviderContext context, ParameterCollection parameters) { try { var currentDocument = context.ActiveDocument.GetCodeAnalysisDocument(); var root = currentDocument != null ? await currentDocument.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false) : null; CurrentNode = root?.FindNode(context.SelectionSpan, true); if (CurrentNode == null) { return(false); } if (IsDocumentation && !InDocumentationElement(CurrentNode) || !IsDocumentation && !InCommentElement(CurrentNode)) { return(false); } return(IsCommentFor(ForElement)); } finally { CurrentNode = null; }; }
private static IEnumerable <IPathNode> ProcessResultsWithCache( ICollection <object> results, IProviderContext context, SHiPSDirectory node, SHiPSDrive drive) { //TODO: async vs cache //we could yield result right away but we need to save the all children in the meantime because //InvokeScript can be costly.So we need to cache the results first by completing the foreach before //returning to a caller. List <IPathNode> retval = new List <IPathNode>(); //clear the child node list, get ready to get the refreshed ones node.Children?.Clear(); foreach (var result in results.WhereNotNull()) { // Making sure to obey the StopProcessing. if (context.Stopping) { return(null); } node.AddAsChildNode(result, drive, retval); } // Mark the node visited once we sucessfully fetched data. node.ItemNavigated = true; return(retval); }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { ITrigger trigger = null; var parameter = context.DynamicParameters as TriggerNewItemParameters; if (null != parameter) { if (parameter.Interval.HasValue) { trigger = new IntervalTrigger { Name = path, Interval = parameter.Interval.Value }; } else if (parameter.Manual) { trigger = new ManualTrigger { Name = path }; } } if (null == trigger) { trigger = new ImmediateTrigger { Name = path }; } _drive.Add(trigger); return(Resolve(context, path).First().GetNodeValue()); }
public override IEnumerable <PathNode> GetChildNodes(IProviderContext providerContext) { return(providerContext .Persistence() .Tags.FindAll() .Select(t => new TagNode(t))); }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext context) { foreach (var trigger in _drive.Triggers) { yield return(new TriggerNodeFactory(_drive, trigger)); } }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext context) { foreach (var dataSource in _drive.DataSources) { yield return(new DataSourceNodeFactory(dataSource)); } }
/// <summary> /// Resolves to corresponding path node object given a string path. /// </summary> /// <param name="context">provider context</param> /// <param name="path">string path given by PowerShell engine</param> /// <param name="force"> /// Whether force to refresh cache. For example, dir myitem -force /// Currently this parameter is used in GetItem. /// </param> /// <returns></returns> internal IEnumerable <IPathNode> ResolvePath(IProviderContext context, string path, bool force) { // We do not call log here. Because PowerShell engine either does not log anything or throw nullref // in System.Management.Automation.MshCommandRuntime.ThrowIfWriteNotPermitted // context.WriteDebug("Resolving path [{0}] drive [{1}]".StringFormat(path, _drive != null ? _drive.Name : string.Empty)); if (_drive == null) { yield break; } // See Issue: https://github.com/PowerShell/SHiPS/issues/10 // While a user is under the drive and run some cmdlets such as Get-Module -listavailable, // the PowerShell engine calls its all registered providers to see whether // any providers can resolve these files defined in .psd1 manifest file. // In this case, our provider does not know these files as its child item, cache misses. So it calls GetChildItem(), // which triggers the engine to call us again. Cycling around, causing potential deadlock or significant delays. // Workaround: filter out all other cmdlets that SHiPS does not handle. if (!context.IsProviderSupportedCommand()) { yield break; } var path1 = path.TrimDrive(_drive); var item = GetNodeObjectFromPath(context, path1, force); if (item != null) { yield return(item); } }
public virtual IEnumerable<IPathNode> ResolvePath(IProviderContext providerContext, string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); Regex re = new Regex(@"^[-_a-z0-9:]+:/?"); path = path.ToLowerInvariant().Replace('\\', '/'); path = re.Replace(path, ""); var factory = Root; var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); IEnumerable<IPathNode> factories = new[] { factory }; foreach (var nodeMoniker in nodeMonikers) { factories = factory.Resolve(providerContext, nodeMoniker); if (null == factories || !factories.Any()) { return null; } factory = factories.First(); } return factories; }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { IScaleDescriptor descriptor = null; if (null == newItemValue) { throw new ArgumentNullException("newItemValue"); } newItemValue = PSObject.AsPSObject(newItemValue).BaseObject; if (newItemValue is string) { descriptor = new ScaleDescriptor(newItemValue as string); } else if (newItemValue is object[]) { descriptor = new ScaleDescriptor(newItemValue as object[]); } else { throw new ArgumentException("the new range value must be specified as a valid range descriptor", "newItemValue"); } _dataSource.Scales.Add(new ScaleDescriptorAssignment { PropertyName = path, Scale = descriptor }); return(Resolve(context, path).First().GetNodeValue()); }
public override IEnumerable<IPathNode> GetNodeChildren(IProviderContext context) { foreach( var trigger in _drive.Triggers ) { yield return new TriggerNodeFactory( _drive, trigger ); } }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { ITrigger trigger = null; var parameter = context.DynamicParameters as TriggerNewItemParameters; if (null != parameter) { if (parameter.Interval.HasValue) { trigger = new IntervalTrigger {Name = path, Interval = parameter.Interval.Value}; } else if (parameter.Manual) { trigger = new ManualTrigger {Name = path}; } } if( null == trigger ) { trigger = new ImmediateTrigger { Name = path }; } _drive.Add(trigger); return Resolve(context, path).First().GetNodeValue(); }
public override IEnumerable <IPathNode> ResolvePath(IProviderContext context, string path) { var match = UriPattern.Match(path); if (!match.Success) { throw new InvalidOperationException("path root value is not valid"); } var uri = match.Groups[1].Value; uri = uri.Decode(); ServerUri = new Uri(uri); var creds = String.IsNullOrEmpty(context.Credential.UserName) ? context.Drive.Credential : context.Credential; if (null != creds) { Credential = creds.GetNetworkCredential(); } path = UriPattern.Replace(path, String.Empty); return(base.ResolvePath(context, path)); }
internal void Set(IProviderContext context) { Force = context.Force; Recurse = context.Recurse; Filter = context.Filter; DynamicParameters = context.DynamicParameters; }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext context) { foreach (var item in Drive.Items) { yield return(new ViewModelNodeFactory <T>(item)); } }
public virtual IEnumerable <IPathNode> ResolvePath(IProviderContext providerContext, string path) { Regex re = new Regex(@"^[-_a-z0-9:]+:/?"); path = path.ToLowerInvariant().Replace('\\', '/'); path = re.Replace(path, ""); var factory = Root; var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); IEnumerable <IPathNode> factories = new[] { factory }; foreach (var nodeMoniker in nodeMonikers) { factories = factory.Resolve(providerContext, nodeMoniker); if (null == factories || !factories.Any()) { return(null); } factory = factories.First(); } return(factories); }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { IScaleDescriptor descriptor = null; if( null == newItemValue ) { throw new ArgumentNullException( "newItemValue"); } newItemValue = PSObject.AsPSObject(newItemValue).BaseObject; if( newItemValue is string ) { descriptor = new ScaleDescriptor(newItemValue as string); } else if ( newItemValue is object[] ) { descriptor = new ScaleDescriptor(newItemValue as object[] ); } else { throw new ArgumentException( "the new range value must be specified as a valid range descriptor", "newItemValue" ); } _dataSource.Scales.Add( new ScaleDescriptorAssignment {PropertyName = path, Scale = descriptor } ); return Resolve(context, path).First().GetNodeValue(); }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext providerContext) { var containers = _client.ListContainers(); var pathNodes = containers.ToList().ConvertAll(a => new BlobContainerPathNode(a)); return(pathNodes); }
/// <summary> /// Constructor for the content stream. /// </summary> /// <param name="context">A provider context.</param> /// <param name="drive">SHiPS based provider drive.</param> /// <param name="node">An object that is corresponding to the current node path.</param> public ContentWriter(IProviderContext context, SHiPSDrive drive, SHiPSBase node) { _drive = drive; _node = node; _context = context; _stream = new MemoryStream(); _writer = new StreamWriter(_stream); }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { var item = context.DynamicParameters as T; item.Name = path; _drive.Add(item); return(Resolve(context, path).First().GetNodeValue()); }
private IEnumerable <IPathNode> GetNodeChildrenInternal(IProviderContext context) { //find the current parent node var item = this.ContainerNode; if (item == null || item.IsLeaf) { // WriteChildItem()/P2F can call us while 'dir -recurse' even if the node is set to leaflet. yield break; } // Set the ProviderContext as the DynamicParameters and Filter objects will be used in the // PowerShell module's GetChildItem(). // If dynamic parameters are used, then SHiPS is not using cache. // ProviderContext has to be set right now because context.NeedRefresh uses it. item.SHiPSProviderContext.Set(context); // The item is the parent node from where we can find its child node list. // We will find child nodes from the cache if GetChildItem() has been called already and NeedRefresh is false. // Otherwise, we will execute the scriptblock and then add the returned nodes to item's child list if (item.UseCache && item.ItemNavigated && !context.NeedRefresh(item, _drive)) { var list = item.Children.Values.SelectMany(each => each); foreach (var node in list) { // Making sure to obey the StopProcessing. if (context.Stopping) { yield break; } yield return(node); } } else { var script = Constants.ScriptBlockWithParam1.StringFormat(Constants.GetChildItem); var nodes = PSScriptRunner.InvokeScriptBlockAndBuildTree(context, item, _drive, script, PSScriptRunner.ReportErrors)?.ToList(); // Save the info of the node just visisted SHiPSProvider.LastVisisted.Set(context.Path, this, nodes); if (nodes == null || nodes.Count == 0) { yield break; } foreach (var node in nodes) { // Making sure to obey the StopProcessing. if (context.Stopping) { yield break; } yield return(node); } } }
public PSObject InvokeAdd(IProviderContext context, string itemName, string type, object value) { var r = context.SessionState.InvokeCommand.InvokeScript(false, _addScript, null, new [] { value }).ToList(); r.ForEach(UpdateIdProperty); context.WriteDebug(String.Format("Invocation of [{0}] complete; [{1}] results returned", _getScript, r.Count)); return(r.FirstOrDefault()); }
public IEnumerable <PSObject> Invoke(IProviderContext context) { var r = context.SessionState.InvokeCommand.InvokeScript(false, _getScript, null).ToList(); r.ForEach(UpdateIdProperty); context.WriteDebug(String.Format("Invocation of [{0}] complete; [{1}] results returned", _getScript, r.Count)); return(r); }
override public IEnumerable <PathNode> GetChildNodes(IProviderContext context) { var persistence = context.Persistence(); IEnumerable <PathNode> entities() => SubEntities(persistence).Select(e => new EntityNode(e)); IEnumerable <PathNode> categories() => SubCategories(persistence).Select(c => new CategoryNode(c)); return(categories().Union(entities())); }
/// <summary> /// Usage: dir /// Also gets called by GetChildItem(), GetChildItems, GetItem() /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext context) { if (context.Stopping) { return(null); } return(GetNodeChildrenInternal(context)); }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext providerContext) { var children = new List <IPathNode>(); int i = 0; children.AddRange(_element.Children.ToList().ConvertAll(c => new ProjectElementPathNode(c, i++))); return(children); }
public override IEnumerable<IPathNode> GetNodeChildren(IProviderContext context) { var data = _dataSource.Scales; foreach( var item in data ) { yield return new ScaleAssignmentNodeFactory( item ); } }
public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext context) { if (null != Collection) { foreach (T item in Collection) { yield return(new ViewModelNodeFactory <T>(item)); } } }
public void RemoveItem(IProviderContext context, string path, bool recurse) { var drive = context.Drive as DataSourceDrive; if (null == drive) { throw new InvalidOperationException("the specified drive does not support the remove data source operation"); } drive.Remove(_dataSource); }
private IPathNode GetNodeObjectFromPath(IProviderContext context, string path, bool force) { var parts = path.Split('/', '\\'); if ((parts.Length == 1) && string.IsNullOrWhiteSpace(parts[0])) { // path is the root return(_drive.RootPathNode); } // When resolving a path, we start from the root node where we know the object already. // It can be costly though, for case like "cd" [tab] if there is no cache enabled. var item = _drive.RootPathNode as ContainerNodeService; if (item == null) { return(null); } // We consider the same operation if the path matches var lastVisisted = SHiPSProvider.LastVisisted; if (lastVisisted.NodeObject != null && lastVisisted.Path.EqualsIgnoreCase(context.Path)) { return(lastVisisted.NodeObject); } IPathNode child = null; // Travel through the path to ensure each node from the root to leaf all exists foreach (var part in parts.Where(each => !string.IsNullOrWhiteSpace(each))) { // Making sure to obey the StopProcessing. if (context.Stopping) { return(null); } child = GetNodeObjectFromPath(context, item, part, force); if (child == null) { //the node on the path does not exist break; } // is a shipsdirectory? item = child as ContainerNodeService; } // Save the info for the node just visited lastVisisted.Set(context.Path, child, null); return(child); }
/// <summary> /// processes the invoke-item cmdlet when invoked on a path that /// resolves to a type value. /// /// this implementation attempts to create an instance of the type /// represented by the path. the type must have a default constructor /// for this to work. /// /// once an instance is created, it is stored in the variable indicated /// by the custom parameter /// </summary> /// <param name="providerContext">the cmdlet providerContext, providing powershell and framework services</param> /// <param name="path">the relative path to the item being invoked</param> /// <returns></returns> public IEnumerable<object> InvokeItem(IProviderContext providerContext, string path) { // retrieve our custom parameter object var param = providerContext.DynamicParameters as CustomInvokeItemParameters; // create an instance of the type at this path value var item = Activator.CreateInstance(_type); // set the specified variable value to the created instance providerContext.SessionState.PSVariable.Set(param.VariableName, item); // return the object created return new[] { item }; }
public ProviderContext(IProviderContext providerContext, object dynamicParameters) { ProviderContext c = providerContext as ProviderContext; if (null == c) { throw new ArgumentException("the providerContext provided is of an incompatible type"); } provider = c.provider; drive = c.drive; path = c.path; pathProcessor = c.pathProcessor; DynamicParameters = dynamicParameters; recurse = c.Recurse; PathTopologyVersion = c.PathTopologyVersion; }
/// <summary> /// processes the new-item cmdlet for paths that resolve to the appdomain value factory /// /// adds an assembly to the current appdomain. assemblies can be specified using /// their (partial) names or a file path. /// /// this implementation essentially delegates all work to to the add-type built-in /// powershell cmdlet to load an assembly from a partial name or file path. /// </summary> /// <param name="providerContext">the cmdlet providerContext providing powershell and framework services</param> /// <param name="path">the relative path supplied to the new-item cmdlet, either as the child element of the -path parameter, or the value of the -name parameter</param> /// <param name="itemTypeName">the type of the item to create; unused in this value</param> /// <param name="newItemValue">the value of the new item to create; unused in this value</param> /// <returns></returns> public IPathValue NewItem(IProviderContext providerContext, string path, string itemTypeName, object newItemValue) { IEnumerable<PSObject> results = new PSObject[]{}; // first try to load the new assembly from an assembly name // note that the invoked script will return a single assembly object if successful try { results = providerContext.InvokeCommand.InvokeScript( String.Format("add-type -assemblyname '{0}' -passthru | select -first 1 -exp Assembly", path), null); } catch { } // ... if that fails, try and load the assembly from a file path // note that the invoked script will return a single assembly object if successful if( ! results.Any() ) { try { results = providerContext.InvokeCommand.InvokeScript( String.Format("add-type -path '{0}' -passthru | select -first 1 -exp Assembly", path), null); } catch { } } // raise any errors if( ! results.Any() ) { throw new ArgumentException( "the specified name is not recognized as a valid assembly name or path"); } // return the path value value to write to the pipeline var assembly = results.First().BaseObject as Assembly; // to maintain consistency I find it easier to leverage the value factory classes rather than return // an IPathValue instance directly. var nodeFactory = new AssemblyPathNode(assembly); return nodeFactory.GetNodeValue(); }
public void RemoveItem(IProviderContext context, string path, bool recurse) { _owner.Ranges.Remove(_range); }
public virtual IEnumerable<IPathNode> ResolvePath( IProviderContext providerContext, string path) { return _basePathResolver.ResolvePath( providerContext, path); }
public IPathValue NewItem(IProviderContext context, string path, string itemTypeName, object newItemValue) { var parameters = context.DynamicParameters as DataSourceNewItemParameters; var name = path; var script = ConvertToScript(newItemValue); if( null == script ) { throw new ArgumentException( "new item value must be a script block or string", "newItemValue"); } var dataSource = new PowerShellDataSource {Name = name, ScriptBlock = script, UseDispatcher = true}; if (null != parameters ) { if (parameters.MaxItemCount.HasValue) { dataSource.DataCollectionMaxSize = parameters.MaxItemCount.Value; } if( parameters.NoDispatcher.IsPresent) { dataSource.UseDispatcher = false; } if( null != parameters.Args ) { string propertyName = null; var specs = parameters.Args.ToHashtable(); foreach (object key in specs.Keys) { var value = specs[key]; IScaleDescriptor descriptor = value as IScaleDescriptor; if (null == descriptor) { if (value is Array) { descriptor = new ScaleDescriptor((object[])value); } else { descriptor = new ScaleDescriptor(value.ToString()); } } dataSource.Scales.Add( new ScaleDescriptorAssignment { Scale = descriptor, PropertyName = key.ToString() } ); } } } ITrigger trigger = Singleton<ImmediateTrigger>.Instance; if( null != parameters && null != parameters.Trigger ) { trigger = parameters.Trigger; } dataSource.Trigger = trigger; _drive.Add( dataSource ); return new PathValue( dataSource, name, true ); }
public void RenameItem(IProviderContext providerContext, string path, string newName) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var fileSystemInfo = (FileSystemInfoContract)nodeValue.Item; fileSystemInfo = drive.RenameItem(fileSystemInfo, newName); if (itemMode == Mode.Directory) { nodeValue = new ContainerPathValue(fileSystemInfo, fileSystemInfo.Name); return; } else if (itemMode == Mode.File) { nodeValue = new LeafPathValue(fileSystemInfo, fileSystemInfo.Name); return; } } throw new InvalidOperationException(); }
public override IEnumerable<IPathNode> Resolve(IProviderContext context, string nodeName) { var trigger = (from t in _drive.Triggers where StringComparer.InvariantCultureIgnoreCase.Equals(nodeName, t.Name) select t).FirstOrDefault(); if( null == trigger) { return null; } return new [] { new TriggerNodeFactory( _drive, trigger ) }; }
public IPathValue NewItem(IProviderContext providerContext, string path, string itemTypeName, object newItemValue) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); if (path == null) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.ItemAlreadyPresent, providerContext.Path)); if (itemMode != Mode.Directory) throw new NotSupportedException($"{nameof(ItemMode)} = {ItemMode}"); Mode mode; if (!Enum.TryParse(itemTypeName, out mode)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.UnknownItemType, itemTypeName), nameof(providerContext)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var baseDirectory = (DirectoryInfoContract)nodeValue.Item; CloudPathNode newItem = null; switch (mode) { case Mode.Directory: newItem = new CloudPathNode(drive.NewDirectoryItem(baseDirectory, path)); newItem.children = new List<CloudPathNode>(); break; case Mode.File: Stream stream = null; if ((stream = newItemValue as Stream) != null) { // nothing else to to } else { var newItemByteArray = newItemValue as byte[]; if (newItemByteArray != null) { stream = new MemoryStream(newItemByteArray); } else { var newItemString = newItemValue as string; if (newItemString != null) { stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(newItemString)); } else if (newItemValue != null) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.UnsupportedContentType, newItemValue.GetType().Name)); } } } newItem = new CloudPathNode(drive.NewFileItem(baseDirectory, path, stream, new ProgressProxy(providerContext, "New-Item", path))); break; } children.Add(newItem); newItem.SetParent(this); return newItem.nodeValue; } throw new InvalidOperationException(); }
public IContentReader GetContentReader(IProviderContext providerContext) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); if (itemMode != Mode.File) throw new NotSupportedException($"{nameof(ItemMode)} = {ItemMode}"); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var fileInfo = (FileInfoContract)nodeValue.Item; return new CloudContentReaderWriter(drive.GetContent(fileInfo, new ProgressProxy(providerContext, "Get-Content", fileInfo.Name)), providerContext.DynamicParameters as CloudContentReaderWriterParameters); } throw new InvalidOperationException(); }
public static string GetRelativePath(IProviderContext providerContext, string path) { string root = providerContext.Drive.Root; return path.StartsWith(root, StringComparison.Ordinal) ? path.Remove(0, root.Length) : path; }
public object GetContentWriterDynamicParameters(IProviderContext providerContext) => new CloudContentReaderWriterParameters();
public override IEnumerable<IPathNode> GetNodeChildren(IProviderContext providerContext) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); if (!nodeValue.IsCollection) return null; if (children == null || providerContext.Force && IsProviderPathNode(providerContext)) { children = (((ICloudDrive)providerContext.Drive).GetChildItem((DirectoryInfoContract)nodeValue.Item).Select(f => new CloudPathNode(f))).ToList(); foreach (var child in children) child.SetParent(this); } if (!string.IsNullOrEmpty(providerContext.Filter) && !providerContext.ResolveFinalNodeFilterItems) { var regex = new Regex("^" + providerContext.Filter.Replace("*", ".*").Replace('?', '.') + "$"); return children.Where(i => regex.IsMatch(i.Name)); } return children; }
public IPathValue MoveItem(IProviderContext providerContext, string path, string movePath, IPathValue destinationContainer) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (destinationContainer == null) throw new ArgumentNullException(nameof(destinationContainer)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var moveItem = new CloudPathNode(drive.MoveItem((FileSystemInfoContract)nodeValue.Item, movePath, (DirectoryInfoContract)destinationContainer.Item)); var destinationContainerNode = providerContext.ResolvePath(((DirectoryInfoContract)destinationContainer.Item).Id.Value) as CloudPathNode; destinationContainerNode.children.Add(moveItem); moveItem.SetParent(destinationContainerNode); parent.children.Remove(this); SetParent(null); return moveItem.nodeValue; } throw new InvalidOperationException(); }
public void RemoveItem(IProviderContext context, string path, bool recurse) { _drive.Remove( _trigger ); }
public virtual IEnumerable<IPathNode> GetNodeChildren(IProviderContext providerContext) { return null; }
public object ClearContentDynamicParameters(IProviderContext providerContext) => null;
private bool IsProviderPathNode(IProviderContext providerContext) { var path = Name; for (var parentNode = parent; parentNode != null; parentNode = parentNode.parent) path = path.Insert(0, parentNode.parent != null ? parentNode.Name + Path.DirectorySeparatorChar : Path.DirectorySeparatorChar.ToString()); if (path == "-") path = Path.DirectorySeparatorChar.ToString(); return CloudPathResolver.GetRelativePath(providerContext, providerContext.Path) == path; }
public virtual IEnumerable<IPathNode> Resolve(IProviderContext providerContext, string name) { var children = GetNodeChildren(providerContext); foreach (var child in children) { if (null == name || StringComparer.InvariantCultureIgnoreCase.Equals(name, child.Name)) { yield return child; } } }
public void ClearContent(IProviderContext providerContext) { if (itemMode != Mode.File) throw new NotSupportedException($"{nameof(ItemMode)} = {ItemMode}"); if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { drive.ClearContent((FileInfoContract)nodeValue.Item); return; } throw new InvalidOperationException(); }
public void RemoveItem(IProviderContext context, string path, bool recurse) { var drive = context.Drive as DataSourceDrive; if( null == drive ) { throw new InvalidOperationException( "the specified drive does not support the remove data source operation" ); } drive.Remove( _dataSource ); }
public IEnumerable<IPathNode> ResolvePath(IProviderContext providerContext, string path) { var root = driveRegex.Match(path).Groups["Drive"].Value; var drive = pathResolverCache.Keys.Single(p => p.Root == root); return pathResolverCache[drive].ResolvePath(providerContext, path); }
public IContentWriter GetContentWriter(IProviderContext providerContext) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); if (itemMode != Mode.File) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "ItemMode = {0}", ItemMode)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { var fileInfo = (FileInfoContract)nodeValue.Item; return new CloudContentReaderWriter(s => drive.SetContent(fileInfo, s, new ProgressProxy(providerContext, "Set-Content", fileInfo.Name)), providerContext.DynamicParameters as CloudContentReaderWriterParameters); } throw new InvalidOperationException(); }
public void RemoveItem(IProviderContext providerContext, string path, bool recurse) { if (providerContext == null) throw new ArgumentNullException(nameof(providerContext)); var drive = providerContext.Drive as ICloudDrive; if (drive != null) { parent.children.Remove(this); drive.RemoveItem((FileSystemInfoContract)nodeValue.Item, recurse); SetParent(null); return; } throw new InvalidOperationException(); }