public void EditRBonusRewards() { IFileContainer fp = ROM.GetFile(GameFile.NestData); var data_table = new GFPack(fp[0]); const string nest = "nest_hole_bonus_rewards.bin"; var nest_bonus = FlatBufferConverter.DeserializeFrom <NestHoleReward8Archive>(data_table.GetDataFileName(nest)); var arr = nest_bonus.Table; var cache = new DataCache <NestHoleReward8Table>(arr); var names = arr.Select(z => $"{z.TableID}").ToArray(); void Randomize() { int[] PossibleHeldItems = Legal.GetRandomItemList(ROM.Info.Game); foreach (var t in arr) { foreach (var i in t.Entries) { i.ItemID = (uint)PossibleHeldItems[Randomization.Util.Random.Next(PossibleHeldItems.Length)]; } } } using var form = new GenericEditor <NestHoleReward8Table>(cache, names, "Raid Bonus Rewards Editor", Randomize); form.ShowDialog(); if (!form.Modified) { return; } var data = FlatBufferConverter.SerializeFrom(nest_bonus); data_table.SetDataFileName(nest, data); fp[0] = data_table.Write(); }
public TextContainer(IFileContainer c, TextConfig t = null, bool remap = false) { Remap = remap; Config = t; Container = c; Cache = new string[Container.Count][]; }
public void SaveAttachedFile(IFileContainer container) { if (container.Files == null) { return; } foreach (var itemFileLink in container.Files) { if (itemFileLink.File == null) { continue; } if (itemFileLink.ParentId <= 0) { itemFileLink.ParentId = container.ItemId; } if (itemFileLink.File.ItemId > 0 && itemFileLink.File.IsDeleted) { _filesSmartCore.DeleteAttachedFile(itemFileLink); } else { _filesSmartCore.SaveAttachedFile(itemFileLink); } } }
/// <summary> /// Returns the corresponding sub process for the given class. Creates it if it isn't running, restarts if the class was modified /// </summary> /// <param name="javascriptContainer"></param> /// <returns></returns> public SubProcess GetOrCreateSubProcess(IFileContainer javascriptContainer) { SubProcess toReturn = null; using (TimedLock.Lock(javascriptContainer)) { using (TimedLock.Lock(SubProcessesByClass)) { if (SubProcessesByClass.TryGetValue(javascriptContainer.FullPath, out toReturn)) { DateTime classLastModified; if (ClassLastModified.TryGetValue(javascriptContainer.FullPath, out classLastModified)) if (javascriptContainer.LastModified == classLastModified) if (toReturn.Alive) return toReturn; } if (null != toReturn) toReturn.Dispose(); ClassLastModified[javascriptContainer.FullPath] = javascriptContainer.LastModified; } toReturn = new SubProcess(javascriptContainer, FileHandlerFactoryLocator); using (TimedLock.Lock(SubProcessesByClass)) SubProcessesByClass[javascriptContainer.FullPath] = toReturn; return toReturn; } }
/// <summary> /// Evaluates given path and creates directory /// </summary> /// <param name="fileContainer">FileContainer to extend</param> /// <param name="path">Directory Path</param> /// <returns>Path segments of created directory</returns> public static string[] CreateDirectoryPath(this IFileContainer fileContainer, string[] path) { #region validation if (path == null) { throw new ArgumentNullException(nameof(path)); } #endregion if (path.Length == 0) { // base path of container should not be created twice return(new string[] { }); } // get directory name from path list (last entry) string directoryName = path.Last(); // determine path to directory string[] pathSegments = path.SkipLast(1).ToArray(); return(fileContainer.CreateDirectory(directoryName, pathSegments)); }
/// <summary> /// Checks existence of a given directory path /// </summary> /// <param name="fileContainer">FileContainer to extend</param> /// <param name="path">Directory path</param> /// <returns>TRUE if directory exists; False if directory does not exist</returns> public static bool DirectoryPathExists(this IFileContainer fileContainer, string[] path) { #region validation if (path == null) { throw new ArgumentNullException(nameof(path)); } #endregion switch (path.Length) { case 0: return(fileContainer.ExistsDirectory(string.Empty)); case 1: { string directoryName = path.First(); return(fileContainer.ExistsDirectory(directoryName)); } default: { string directoryName = path.Last(); string[] pathSegments = path.Take(path.Length - 1).ToArray(); return(fileContainer.ExistsDirectory(directoryName, pathSegments)); } } }
public async Task ExecutePublishDocumentServer_With_SchemaFile_Handler() { // arrange string sessionId = await SessionCreator.CreateSessionAsync(); var handler = new PublishNewSchemaDocumentHandler( Storage, SchemaRepository, PublishSchemaEventSender); using var service = new PublishDocumentService( PublishDocumentMessageReceiver, new IPublishDocumentHandler[] { handler }); var schema = new Schema("abc", "def"); await SchemaRepository.AddSchemaAsync(schema); var environment = new Environment("abc", "def"); await EnvironmentRepository.AddEnvironmentAsync(environment); var message = new PublishDocumentMessage( sessionId, environment.Id, schema.Id, "externalId", Array.Empty <Tag>()); IFileContainer fileContainer = await Storage.CreateContainerAsync(sessionId); byte[] buffer = Encoding.UTF8.GetBytes(@" type Query { foo: String } "); await fileContainer.CreateFileAsync("schema.graphql", buffer, 0, buffer.Length); await PublishDocumentMessageSender.SendAsync(message); // act await service.StartAsync(default);
public FilesystemUpload(string storagePathAndFilename, string fullPath, Stream sourceStream, IFileContainer container) { _storagePathAndFilename = storagePathAndFilename; _destinationFullPath = fullPath; _sourceStream = sourceStream; _container = container; }
/// <summary> /// Evaluates given path and creates directory /// </summary> /// <param name="fileContainer">FileContainer to extend</param> /// <param name="path">Directory Path</param> /// <returns>Path segments of created directory</returns> public static string[] CreateDirectoryPath(this IFileContainer fileContainer, string[] path) { #region validation if (path == null) { throw new ArgumentNullException(nameof(path)); } #endregion switch (path.Length) { case 0: return(new string[] { }); case 1: { string directoryName = path.First(); return(fileContainer.CreateDirectory(directoryName)); } default: { string directoryName = path.Last(); string[] pathSegments = path.SkipLast(1).ToArray(); return(fileContainer.CreateDirectory(directoryName, pathSegments)); } } }
/// <summary> /// Checks existence of a given directory path /// </summary> /// <param name="fileContainer">FileContainer to extend</param> /// <param name="path">Directory path</param> /// <returns>TRUE if directory exists; False if directory does not exist</returns> public static bool DirectoryPathExists(this IFileContainer fileContainer, string[] path) { #region validation if (fileContainer == null) { throw new ArgumentNullException(nameof(fileContainer)); } if (path == null) { throw new ArgumentNullException(nameof(path)); } #endregion if (path.Length == 0) { // base path of container exists return(true); } // get directory name from path list (last entry) string directoryName = path.Last(); // determine path to directory string[] pathSegments = path.SkipLast(1).ToArray(); return(fileContainer.ExistsDirectory(directoryName, pathSegments)); }
private void PopWildEdit(string file) { IFileContainer fp = ROM.GetFile(GameFile.NestData); var data_table = new GFPack(fp[0]); var sdo = data_table.GetDataFileName($"encount_symbol_{file}.bin"); var hdo = data_table.GetDataFileName($"encount_{file}.bin"); var s = FlatBufferConverter.DeserializeFrom <EncounterArchive8>(sdo); var h = FlatBufferConverter.DeserializeFrom <EncounterArchive8>(hdo); while (s.EncounterTables[0].SubTables.Length != 9) { s = FlatBufferConverter.DeserializeFrom <EncounterArchive8>(sdo); h = FlatBufferConverter.DeserializeFrom <EncounterArchive8>(hdo); } using var form = new SSWE(ROM, s, h); form.ShowDialog(); if (!form.Modified) { return; } var sd = FlatBufferConverter.SerializeFrom(s); var hd = FlatBufferConverter.SerializeFrom(h); data_table.SetDataFileName($"encount_symbol_{file}.bin", sd); data_table.SetDataFileName($"encount_{file}.bin", hd); fp[0] = data_table.Write(); }
protected void AddProjectFilesAndFolders(IFileContainer container, string currentPath) { // Create directory if it doesn't exist if (!Directory.Exists(currentPath)) { Directory.CreateDirectory(currentPath); } var containerFiles = container.GetFiles(); if (containerFiles.Count > 0) { // Add files to this directory foreach (ProjectFile file in containerFiles) { string filePath = Path.Combine(currentPath, file.FileName); File.WriteAllText(filePath, file.FileContents); _tempFileRelativePathDictionary.Add(file, filePath.Replace(String.Concat(tempCsProjDirectoryPath, @"\"), String.Empty)); } } else { _emptyFolderRelativePathList.Add(currentPath.Replace(String.Concat(tempCsProjDirectoryPath, @"\"), String.Empty)); } // Go into each folder recursively down the chain creating files and folders foreach (ProjectFolder folder in container.GetFolders()) { AddProjectFilesAndFolders(folder, Path.Combine(currentPath, folder.FolderName)); } }
public async Task <PublishClientPayload> PublishClientAsync( PublishClientInput input, [Service] IMessageSender <PublishDocumentMessage> messageSender, [Service] IFileStorage fileStorage, [Service] ISessionCreator sessionCreator, [DataLoader] SchemaByNameDataLoader schemaDataLoader, [DataLoader] ClientByNameDataLoader clientDataLoader, [DataLoader] EnvironmentByNameDataLoader environmentDataLoader, CancellationToken cancellationToken) { if (input.Files.Count == 0) { throw new GraphQLException("You have to provide at least one query file."); } Schema schema = await schemaDataLoader.LoadAsync( input.SchemaName, cancellationToken) .ConfigureAwait(false); Client client = await clientDataLoader.LoadAsync( input.ClientName, cancellationToken) .ConfigureAwait(false); Environment environment = await environmentDataLoader.LoadAsync( input.EnvironmentName, cancellationToken) .ConfigureAwait(false); string sessionId = await sessionCreator.CreateSessionAsync(cancellationToken) .ConfigureAwait(false); IFileContainer container = await fileStorage.CreateContainerAsync( sessionId, cancellationToken) .ConfigureAwait(false); foreach (QueryFile file in input.Files) { await container.CreateTextFileAsync( file.Name, file.SourceText, cancellationToken) .ConfigureAwait(false); } await messageSender.SendAsync( new PublishDocumentMessage( sessionId, environment.Id, schema.Id, client.Id, input.ExternalId, input.Format == QueryFileFormat.GraphQL ? DocumentType.Query : DocumentType.Schema, input.Tags is null ? Array.Empty <Tag>() : input.Tags.Select(t => new Tag(t.Key, t.Value)).ToArray()), cancellationToken) .ConfigureAwait(false); return(new PublishClientPayload(sessionId, input.ClientMutationId)); }
static IEnumerable <InstallableFileInfo> GetAssembliesForInstallUtils(IFileContainer container, Assembly target) { var attribs = target.GetCustomAttributes(typeof(InstallUtilsAssemblyAttribute), true); var attribs2 = attribs.Cast <InstallUtilsAssemblyAttribute>().ToArray(); var targets = attribs2.Select(x => GetTargetByInstallUtilsAssemblyAttribute(x, container)).ToList(); return(targets); }
static string GetAssemblyFileId(Assembly assembly, IFileContainer container) { if (IsEmbeded(assembly)) { return(container.Single(x => Path.GetFileNameWithoutExtension(x.FileId) == assembly.GetName().Name&& ValidExtension(x.FileId)).FileId); } return(Path.GetFileName(assembly.Location)); }
/// <summary> /// /// </summary> /// <param name="templateParsingState"></param> /// <param name="fileContainer"></param> /// <param name="namedPermission"></param> /// <returns></returns> protected override bool DetermineCondition(ITemplateParsingState templateParsingState, IFileContainer fileContainer, string namedPermission) { foreach (Dictionary<string, object> supportedNamedPermission in fileContainer.FileConfigurationManager.ViewComponents) if (supportedNamedPermission["NamedPermission"].ToString() == namedPermission) return true; return false; }
public void Cleanup() { _rootDirectoryInfo.Delete(true); _rootDirectoryInfo = null; _fileContainer = null; }
public static async Task <byte[]> GetAllBytesAsync( this IFileContainer container, string fileId, CancellationToken cancellationToken = default) { using var stream = await container.GetAsync(fileId, cancellationToken); return(await stream.GetAllBytesAsync(cancellationToken)); }
/// <summary> /// Returns the appropriate FileConfigurationManager /// </summary> /// <param name="fileContainer"></param> /// <returns></returns> public FileConfigurationManager GetFileConfigurationManager(IFileContainer fileContainer) { string extension = fileContainer.Extension; if (null == extension) return FileConfigurationManagersByType[fileContainer.TypeId]; else return FileConfigurationManagersByExtension[extension]; }
public static Task CreateTextFileAsync( this IFileContainer container, string fileName, string text, CancellationToken cancellationToken = default) { byte[] buffer = Encoding.UTF8.GetBytes(text); return(container.CreateFileAsync(fileName, buffer, 0, buffer.Length, cancellationToken)); }
public static string GetFullPath(IFileContainer fileContainer) { /*if (null == fileContainer.ParentDirectoryHandler) return ""; else return string.Format("{0}/{1}", GetFullPath(fileContainer.ParentDirectoryHandler), fileContainer.Filename);*/ throw new NotImplementedException(); }
/// <inheritdoc /> public bool MoveChildToNewParent(IFile child, IFileContainer newParent, int locationInNewParent, bool updateFileSystemTables) { #if REPORT_PERFORMANCE var stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // REPORT_PERFORMANCE bool moved = false; if (child == null) { throw new ArgumentNullException("child"); } if (newParent == null) { throw new ArgumentNullException("newParent"); } if (IsParentOfChild(child)) { var file = (FileNode)child; if (newParent == this) { if (locationInNewParent < 0) { locationInNewParent = Files.Count - 1; } var currentIndex = Files.IndexOf(file); Files.Move(currentIndex, locationInNewParent); UpdateCrc(); moved = true; } else { var newFolder = (Folder)newParent; if (locationInNewParent < 0) { newFolder.Files.Add(file); } else { newFolder.Files.Insert(locationInNewParent, file); } moved = Files.Remove(file); // Remove nulls out the parent, so restore it. file.Parent = newFolder; UpdateCrc(); newFolder.UpdateCrc(); } } else { throw new InvalidOperationException(Resources.Strings.Folder_NotParentError); } #if REPORT_PERFORMANCE stopwatch.Stop(); var prefix = "*"; System.Diagnostics.Debug.WriteLine(prefix + "Folder.MoveToNewParent() for '" + LongName + "' took " + stopwatch.Elapsed.ToString()); #endif // REPORT_PERFORMANCE return(moved); }
private async Task HandleInternalAsync( PublishDocumentMessage message, CancellationToken cancellationToken) { var issueLogger = new IssueLogger(message.SessionId, _eventSender); try { IFileContainer fileContainer = await _fileStorage.GetContainerAsync(message.SessionId).ConfigureAwait(false); IEnumerable <IFile> files = await fileContainer.GetFilesAsync(cancellationToken).ConfigureAwait(false); IFile schemaFile = files.Single(); DocumentNode?schemaDocument = await TryParseSchemaAsync( schemaFile, issueLogger, cancellationToken) .ConfigureAwait(false); string formattedSourceText = schemaDocument is { } ? PrintSchema(schemaDocument) : await ReadSchemaSourceTextAsync( schemaFile, cancellationToken) .ConfigureAwait(false); DocumentHash documentHash = DocumentHash.FromSourceText(formattedSourceText); SchemaVersion?schemaVersion = await _schemaRepository.GetSchemaVersionByHashAsync( documentHash.Hash, cancellationToken) .ConfigureAwait(false); if (schemaVersion is null) { await PublishNewSchemaVersionAsync( message, schemaDocument, formattedSourceText, issueLogger, cancellationToken) .ConfigureAwait(false); } else { await PublishExistingSchemaVersionAsync( message, schemaDocument, schemaVersion, issueLogger, cancellationToken) .ConfigureAwait(false); } await fileContainer.DeleteAsync(cancellationToken).ConfigureAwait(false); }
/// <summary> /// If the corresponding sub process is based on an outdated version of the class, disposes it /// </summary> /// <param name="javascriptContainer"></param> public void DisposeSubProcessIfOutdated(IFileContainer javascriptContainer) { using (TimedLock.Lock(SubProcessesByClass)) if (javascriptContainer.LastModified != ClassLastModified[javascriptContainer.FullPath]) { SubProcessesByClass[javascriptContainer.FullPath].Dispose(); SubProcessesByClass.Remove(javascriptContainer.FullPath); ClassLastModified.Remove(javascriptContainer.FullPath); } }
public static Task CreateTextFileAsync( this IFileContainer container, Guid fileName, string text, CancellationToken cancellationToken = default) => CreateTextFileAsync( container, fileName.ToString("N", CultureInfo.InvariantCulture), text, cancellationToken);
/// <summary> /// /// </summary> /// <param name="templateParsingState"></param> /// <param name="fileContainer"></param> /// <param name="namedPermission"></param> /// <returns></returns> protected override bool DetermineCondition(ITemplateParsingState templateParsingState, IFileContainer fileContainer, string namedPermission) { // Always return true for administrators if (templateParsingState.WebConnection.WebServer.FileHandlerFactoryLocator.UserManagerHandler.IsUserInGroup( templateParsingState.WebConnection.Session.User.Id, templateParsingState.WebConnection.WebServer.FileHandlerFactoryLocator.UserFactory.Administrators.Id)) return true; return fileContainer.HasNamedPermissions(templateParsingState.WebConnection.Session.User.Id, namedPermission); }
public async Task Container_Create_File() { // arrange var fileStorage = new FileStorage(_path); IFileContainer container = await fileStorage.CreateContainerAsync("abc"); // act await container.CreateFileAsync("def", new byte[] { 0 }, 0, 1); // assert Assert.True(IOFile.Exists(Path.Combine(_path, "abc", "def"))); }
private AddRomsToMenuData(MenuLayoutViewModel menuLayout, IFileContainer destination, int insertLocation, IEnumerable <ProgramDescription> itemsToAdd, IEnumerable <string> destinationDirectories) : base(null) { MenuLayout = menuLayout; Destination = destination; ItemsToAdd = new List <ProgramDescription>(itemsToAdd); InsertLocation = insertLocation; DestinationDirectories = destinationDirectories; FailedToAdd = new Dictionary <string, IDictionary <string, IList <System.Tuple <string, string> > > >(); AddedItems = new List <FileNode>(); UIDispatcher = OSDispatcher.Current; }
public async Task Storage_Create_Container() { // arrange var fileStorage = new FileStorage(_path); // act IFileContainer container = await fileStorage.CreateContainerAsync("abc"); // assert Assert.Equal("abc", container.Name); Assert.True(Directory.Exists(Path.Combine(_path, "abc"))); }
public async Task Container_Delete_Container() { // arrange var fileStorage = new FileStorage(_path); IFileContainer container = await fileStorage.CreateContainerAsync("abc"); // act await container.DeleteAsync(); // assert Assert.False(Directory.Exists(Path.Combine(_path, "abc"))); }
public async Task <PublishSchemaPayload> PublishSchemaAsync( PublishSchemaInput input, [Service] IMessageSender <PublishDocumentMessage> messageSender, [Service] IFileStorage fileStorage, [Service] ISessionCreator sessionCreator, [DataLoader] SchemaByNameDataLoader schemaDataLoader, [DataLoader] EnvironmentByNameDataLoader environmentDataLoader, CancellationToken cancellationToken) { Schema schema = await schemaDataLoader.LoadAsync( input.SchemaName, cancellationToken) .ConfigureAwait(false); Environment environment = await environmentDataLoader.LoadAsync( input.EnvironmentName, cancellationToken) .ConfigureAwait(false); if (string.IsNullOrEmpty(input.SourceText)) { throw new GraphQLException( Resources.SchemaMutations_HashAndSourceTextAreNull); } string sessionId = await sessionCreator.CreateSessionAsync(cancellationToken) .ConfigureAwait(false); IFileContainer container = await fileStorage.CreateContainerAsync( sessionId, cancellationToken) .ConfigureAwait(false); using (Stream stream = await container.CreateFileAsync( "schema.graphql", cancellationToken) .ConfigureAwait(false)) { byte[] buffer = Encoding.UTF8.GetBytes(input.SourceText); await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); } await messageSender.SendAsync( new PublishDocumentMessage( sessionId, environment.Id, schema.Id, input.ExternalId, input.Tags is null ? Array.Empty <Tag>() : input.Tags.Select(t => new Tag(t.Key, t.Value)).ToArray()), cancellationToken) .ConfigureAwait(false); return(new PublishSchemaPayload(sessionId, input.ClientMutationId)); }
public async Task Storage_Get_Container() { // arrange var fileStorage = new FileStorage(_path); Directory.CreateDirectory(Path.Combine(_path, "abc")); // act IFileContainer container = await fileStorage.GetContainerAsync("abc"); // assert Assert.Equal("abc", container.Name); }
public static async Task <string> ReadAllTextAsync( this IFileContainer container, Guid fileName, CancellationToken cancellationToken = default) { IFile file = await container.GetFileAsync( fileName.ToString("N", CultureInfo.InvariantCulture), cancellationToken) .ConfigureAwait(false); return(await file.ReadAllTextAsync(cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Creates a Javascript execution environment /// </summary> /// <param name="fileContainer">The object that will be accessed through Javascript</param> /// <param name="javascriptContainer">The text file that contains the javascript</param> public ExecutionEnvironment( FileHandlerFactoryLocator fileHandlerFactoryLocator, IFileContainer javascriptContainer, IFileContainer fileContainer, SubProcess subProcess, ParentScope parentScope) { _FileHandlerFactoryLocator = fileHandlerFactoryLocator; _JavascriptContainer = javascriptContainer; _JavascriptLastModified = javascriptContainer.LastModified; parentScope.WebHandlersWithThisAsParent.Enqueue(fileContainer.WebHandler); object toDiscard; ISession ownerSession = FileHandlerFactoryLocator.SessionManagerHandler.CreateSession(); try { if (null != fileContainer.Owner) ownerSession.Login(fileContainer.Owner); IWebConnection ownerWebConnection = new BlockingShellWebConnection( FileHandlerFactoryLocator.WebServer, ownerSession, fileContainer.FullPath, null, null, new CookiesFromBrowser(), CallingFrom.Web, WebMethod.GET); ScopeWrapper = new ScopeWrapper( fileHandlerFactoryLocator, subProcess, fileContainer, parentScope, ownerWebConnection, out toDiscard); } catch (Exception e) { // If the Javascript has an error in it, it must be ignored. If an error were returned, then malformed Javascript could hose the system! this._ExecutionEnvironmentErrors = e.ToString(); log.Error("Error creating scope", e); } finally { FileHandlerFactoryLocator.SessionManagerHandler.EndSession(ownerSession.SessionId); } }
private bool AcceptDragData(System.Windows.IDataObject data) { IFileContainer dropTarget = Model as IFileContainer; if (dropTarget == null) { dropTarget = Parent; } var draggedItem = data.GetData(MenuLayoutViewModel.DragDataFormat) as IFile; bool accept = draggedItem != null; if (accept) { accept = ShouldAcceptDraggedItem(draggedItem); /* * var draggedItemParent = draggedItem.Parent; * accept = (draggedItem != this.Model); * if (accept && (dropTarget != null)) * { * var draggedContainer = draggedItem as IFileContainer; * if (draggedContainer != null) * { * accept = !draggedContainer.ContainsChild(dropTarget) && (draggedContainer != dropTarget); * } * if (accept) * { * accept = (dropTarget.Size < FileSystemConstants.MaxItemCount) || (dropTarget == draggedItemParent); * } * if (accept) * { * int currentDepth = DepthFromRoot; * int draggedItemDepth = draggedItem.Depth; * if (draggedContainer != null) * { ++draggedItemDepth; // count folders as one extra layer of depth, since they are pointless w/o containing any items * } * accept = currentDepth + draggedItemDepth <= FileSystemConstants.MaximumDepth; * } * } */ } else { IEnumerable <ProgramDescription> draggedPrograms = data.GetData(ProgramDescriptionViewModel.DragDataFormat) as IEnumerable <ProgramDescription>; accept = (draggedPrograms != null) && (draggedPrograms.Any() && ((draggedPrograms.Count() + dropTarget.Size) <= FileSystemConstants.MaxItemCount)); } return(accept); }
/// <summary> /// Determines if the item should accept a collection of dragged items. /// </summary> /// <param name="programDescriptions">The programs being dragged.</param> /// <returns><c>true</c> if the items should be accepted.</returns> internal bool ShouldAcceptDraggedItems(IEnumerable <ProgramDescription> programDescriptions) { IFileContainer dropTarget = null; if ((programDescriptions != null) && programDescriptions.Any()) { dropTarget = Model as IFileContainer; if (dropTarget == null) { dropTarget = Parent; } } return((dropTarget != null) && ((programDescriptions.Count() + dropTarget.Size) <= FileSystemConstants.MaxItemCount)); }
private async Task HandleInternalAsync( PublishDocumentMessage message, CancellationToken cancellationToken) { var logger = new IssueLogger(message.SessionId, _eventSender); try { var documents = new List <QueryDocumentInfo>(); IReadOnlyList <Guid> queryIds = Array.Empty <Guid>(); ISchema?schema = await SchemaHelper.TryLoadSchemaAsync( SchemaRepository, FileStorage, message.SchemaId, message.EnvironmentId, logger, cancellationToken) .ConfigureAwait(false); IFileContainer fileContainer = await FileStorage.GetContainerAsync( message.SessionId, cancellationToken) .ConfigureAwait(false); if (schema is { }) { queryIds = await ProcessDocumentsAsync( message.SchemaId, schema, fileContainer, message.Documents, documents, logger, cancellationToken) .ConfigureAwait(false); } Guid clientVersionId = await AddClientVersionAsync( message, queryIds, cancellationToken) .ConfigureAwait(false); await AddEnvironmentPublishReport( clientVersionId, message.EnvironmentId, logger, cancellationToken) .ConfigureAwait(false); await fileContainer.DeleteAsync( cancellationToken) .ConfigureAwait(false); }
/// <summary> /// Creates a scope wrapper /// </summary> /// <param name="fileHandlerFactoryLocator"></param> /// <param name="webConnection"></param> /// <param name="javascript"></param> /// <param name="fileContainer"></param> /// <param name="constructScopeResults"></param> public ScopeWrapper( FileHandlerFactoryLocator fileHandlerFactoryLocator, SubProcess subProcess, IFileContainer fileContainer, ParentScope parentScope, IWebConnection constructWebConnection, out object constructScopeResults) { _FileContainer = fileContainer; _SubProcess = subProcess; _ParentScope = parentScope; _ScopeId = GetScopeID(); _FileHandlerFactoryLocator = fileHandlerFactoryLocator; constructScopeResults = ConstructScope(constructWebConnection); }
/// <summary> /// Sends a notification /// </summary> /// <param name="recipientIdentities"></param> /// <param name="fileContainer"></param> /// <param name="summaryViewParent">The summary view will be all child nodes</param> /// <param name="documentType"></param> /// <param name="messageSummary"></param> public LinkNotificationInformation SendLinkNotificationFrom( IUser sender, IFileContainer linkedFileContainer) { // TODO: Need a better approach to handle when the linked file doesn't have an owner // For now, just sending as root IUser owner; if (null != linkedFileContainer.Owner) owner = linkedFileContainer.Owner; else owner = FileHandlerFactoryLocator.UserFactory.RootUser; string linkSummaryView = linkedFileContainer.GenerateSummaryView(); string linkID = Interlocked.Increment(ref NextLinkID).ToString(); Dictionary<string, object> changeData = new Dictionary<string,object>(); changeData["linkUrl"] = linkedFileContainer.ObjectUrl; changeData["linkSummaryView"] = linkSummaryView; changeData["linkDocumentType"] = linkedFileContainer.DocumentType; changeData["ownerIdentity"] = owner.Identity; changeData["linkID"] = linkID; SendNotification(sender, "link", changeData); LinkNotificationInformation toReturn = new LinkNotificationInformation(); toReturn.linkID = linkID; toReturn.linkSummaryView = linkSummaryView; return toReturn; }
void AssignNewContainer(string folderpath) { _currentContainer = new Folder(folderpath); _currentContainer.FileLicensed += FileLicensedEventHandler; _currentContainer.FileLicensingStarted += FileLicensingStartedEventHandler; }
/// <summary> /// Generates runtime metadata for the server-side javascript /// </summary> /// <param name="webConnection"></param> /// <param name="context"></param> internal static Dictionary<string, object> CreateMetadata(FileHandlerFactoryLocator fileHandlerFactoryLocator, IFileContainer fileContainer) { Dictionary<string, object> toReturn = new Dictionary<string, object>(); //Ability to know the following from within Javascript: File name, file path, owner name, owner ID, connected user name, connected user id Dictionary<string, object> fileMetadata = new Dictionary<string, object>(); fileMetadata["filename"] = fileContainer.Filename; fileMetadata["fullpath"] = fileContainer.FullPath; fileMetadata["url"] = fileContainer.ObjectUrl; if (null != fileContainer.Owner) fileMetadata["owner"] = fileContainer.Owner.Name; else fileMetadata["owner"] = null; if (null != fileContainer.OwnerId) { fileMetadata["ownerId"] = fileContainer.OwnerId.Value; IUserOrGroup owner = fileHandlerFactoryLocator.UserManagerHandler.GetUserOrGroupNoException(fileContainer.OwnerId.Value); if (null != owner) { fileMetadata["owner"] = owner.Name; if (owner is IUser) fileMetadata["ownerIdentity"] = ((IUser)owner).Identity; } } toReturn["fileMetadata"] = fileMetadata; Dictionary<string, object> hostMetadata = new Dictionary<string, object>(); hostMetadata["host"] = fileHandlerFactoryLocator.HostnameAndPort; hostMetadata["justHost"] = fileHandlerFactoryLocator.Hostname; hostMetadata["port"] = fileHandlerFactoryLocator.WebServer.Port; toReturn["hostMetadata"] = hostMetadata; return toReturn; }
/// <summary> /// Returns the ID for the javascript container's parent scope, creates the parent scope and disposes an old one, if needed /// </summary> /// <param name="javascriptContainer"></param> /// <returns></returns> public ParentScope GetParentScope(IFileContainer javascriptContainer) { ParentScope parentScope = null; LoadedParentScopesLock.EnterReadLock(); // First try getting the parent scope ID in a read-only lock try { LoadedParentScopes.TryGetValue(javascriptContainer, out parentScope); } finally { LoadedParentScopesLock.ExitReadLock(); } if (null != parentScope) if (parentScope.StillValid) { bool stillValid = true; foreach (KeyValuePair<IFileContainer, DateTime> loadedScriptModifiedTime in parentScope.LoadedScriptsModifiedTimes) stillValid = stillValid & (loadedScriptModifiedTime.Key.LastModified == loadedScriptModifiedTime.Value); if (stillValid) return parentScope; } // Either there's no parent scope or it's invalid using (TimedLock.Lock(javascriptContainer, TimeSpan.FromSeconds(15))) { ParentScope parentScopeFromOtherThread = null; LoadedParentScopesLock.EnterReadLock(); // First try getting the parent scope ID in a read-only lock try { LoadedParentScopes.TryGetValue(javascriptContainer, out parentScopeFromOtherThread); } finally { LoadedParentScopesLock.ExitReadLock(); } // If another thread loaded the parent scope, then restart the process of getting it if (parentScope != parentScopeFromOtherThread) return GetParentScope(javascriptContainer); // If there's an old parent scope, delete all references to it and dispose it if (null != parentScope) { // If code changed within the scope, then abort IWebHandler webHandler; while (parentScope.WebHandlersWithThisAsParent.Dequeue(out webHandler)) webHandler.ResetExecutionEnvironment(); // If the parent scope isn't valid, make sure its disposed ThreadPool.QueueUserWorkItem(delegate(object state) { try { _SubProcess.DisposeParentScope((int)state, Thread.CurrentThread.ManagedThreadId); } catch (Exception e) { log.Error("Exception when cleaning up a dead parent scope", e); } }, parentScope.ParentScopeId); } parentScope = CreateParentScope(javascriptContainer); // If the parent scope ID wasn't found, then get a write lock LoadedParentScopesLock.EnterWriteLock(); try { LoadedParentScopes[javascriptContainer] = parentScope; } finally { LoadedParentScopesLock.ExitWriteLock(); } return parentScope; } }
/// <summary> /// Returns the file with all header/footers resolved as XML for further processing /// </summary> /// <param name="arguments"></param> /// <param name="templateFileContainer"></param> /// <param name="webConnection"></param> /// <param name="templateParsingState"></param> /// <returns></returns> private void ResolveHeaderFooter( IWebConnection webConnection, IDictionary<string, object> arguments, IFileContainer templateFileContainer, TemplateParsingState templateParsingState) { HashSet<string> checkedHeaderFooters = new HashSet<string>(); XmlDocument templateDocument = templateParsingState.LoadXmlDocumentAndReplaceGetParameters(arguments, templateFileContainer, XmlParseMode.Xml); // I think this is to work around an issue when directly viewing a template with an empty <oc:component /> tag templateParsingState.TemplateDocument = templateDocument; // While the first node isn't HTML, keep loading header/footers while ("html" != templateDocument.FirstChild.LocalName) { XmlNode firstChild = templateDocument.FirstChild; string headerFooter = "/DefaultTemplate/headerfooter.ochf"; XmlNodeList nodesToInsert; if (("componentdef" == firstChild.LocalName) && (templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace == firstChild.NamespaceURI)) { XmlAttribute headerFooterAttribue = firstChild.Attributes["headerfooter"]; if (null != headerFooterAttribue) headerFooter = FileHandlerFactoryLocator.FileSystemResolver.GetAbsolutePath( templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath, headerFooterAttribue.Value); nodesToInsert = firstChild.ChildNodes; } else nodesToInsert = templateDocument.ChildNodes; string headerFooterOverride; if (webConnection.GetParameters.TryGetValue("HeaderFooterOverride", out headerFooterOverride)) headerFooter = headerFooterOverride; if (checkedHeaderFooters.Contains(headerFooter)) throw new TemplateException("Looping within templates: " + headerFooter + " eventually points to itself as a headerfooter!!!"); else checkedHeaderFooters.Add(headerFooter); templateParsingState.SetCWD(nodesToInsert, templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath); try { templateFileContainer = FileHandlerFactoryLocator.FileSystemResolver.ResolveFile(headerFooter); } catch (FileDoesNotExist fdne) { log.Error(headerFooter + " does not exist", fdne); throw new WebResultsOverrideException(WebResults.From(Status._500_Internal_Server_Error, headerFooter + " does not exist")); } templateDocument = templateParsingState.LoadXmlDocumentAndReplaceGetParameters( arguments, templateFileContainer, XmlParseMode.Xml); templateParsingState.TemplateDocument = templateDocument; // find <oc:component /> tag int numOcComponentTags = 0; XmlNodeList componentTags = templateDocument.GetElementsByTagName("component", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace); foreach (XmlNode componentNode in Enumerable<XmlNode>.FastCopy(Enumerable<XmlNode>.Cast(componentTags))) if ((null == componentNode.Attributes.GetNamedItem("url", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace)) && (null == componentNode.Attributes.GetNamedItem("src", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace))) { numOcComponentTags++; if (1 == numOcComponentTags) templateParsingState.ReplaceNodes(componentNode, nodesToInsert); else templateParsingState.ReplaceNodes( componentNode, templateParsingState.GenerateWarningNode("Warning: Duplicate <oc:component /> tag, count " + numOcComponentTags.ToString())); } // Attempt to recover from a missing <oc:component /> tag if (0 == numOcComponentTags) { XmlNodeList bodyTags = templateDocument.GetElementsByTagName( "body", templateParsingState.TemplateHandlerLocator.TemplatingConstants.HtmlNamespace); XmlElement bodyTag = null; if (null != bodyTags) if (bodyTags.Count > 0) bodyTag = (XmlElement)bodyTags[0]; if (null == bodyTag) { bodyTag = (XmlElement)templateDocument.FirstChild; } bodyTag.AppendChild( templateParsingState.GenerateWarningNode( @"WARNING!!! -------------- " + headerFooter + @" is missing a needed <oc:component /> tag!!! The tag must be empty with no attributes. This is where the content for each page is displayed")); XmlElement componentNode = templateDocument.CreateElement( "component", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace); bodyTag.AppendChild(componentNode); templateParsingState.ReplaceNodes(componentNode, nodesToInsert); } } templateParsingState.SetCWD(templateDocument.ChildNodes, templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath); }
public OpenFailedException(IFileContainer file, string message, Exception innerException) : base(message, innerException) { m_path = file.FilePath; }
/// <summary> /// Loads an XmlDocument from the filecontainer, replacing GET parameters and verifying permissions /// </summary> /// <param name="arguments"></param> /// <param name="fileContainer"></param> /// <param name="xmlParseMode">The kind of text that's being parsed</param> /// <returns></returns> public XmlDocument LoadXmlDocumentAndReplaceGetParameters( IDictionary<string, object> arguments, IFileContainer fileContainer, XmlParseMode xmlParseMode) { XmlDocument xmlDocument = LoadXmlDocument(fileContainer, xmlParseMode); // Do the replacements HandleArguments(arguments, xmlDocument); if (WebConnection.CookiesFromBrowser.ContainsKey(TemplateHandlerLocator.TemplatingConstants.XMLDebugModeCookie)) { StringBuilder commentBuilder = new StringBuilder("\n\nDEBUG INFO\n"); SortedDictionary<string, object> sortedArguments = new SortedDictionary<string, object>(arguments); foreach (KeyValuePair<string, object> getArgument in sortedArguments) if (null != getArgument.Value) commentBuilder.AppendFormat("\t{0}: {1}\n", getArgument.Key, getArgument.Value.ToString()); else commentBuilder.AppendFormat("\t{0}: null\n", getArgument.Key); commentBuilder.Append("\n\n"); XmlComment comment = xmlDocument.CreateComment(commentBuilder.ToString()); XmlNode firstChild = xmlDocument.FirstChild; if ((firstChild.LocalName == "componentdef") && (firstChild.NamespaceURI == TemplateHandlerLocator.TemplatingConstants.TemplateNamespace)) firstChild.InsertBefore(comment, firstChild.FirstChild); else if ("html" != xmlDocument.FirstChild.LocalName) xmlDocument.InsertBefore(comment, firstChild); else firstChild.InsertBefore(comment, firstChild.FirstChild); } return xmlDocument; }
/// <summary> /// Loads an XmlDocument from the filecontainer, replacing GET parameters and verifying permissions /// </summary> /// <param name="fileContainer"></param> /// <param name="xmlParseMode">The kind of text that's being parsed</param> /// <returns></returns> public XmlDocument LoadXmlDocument(IFileContainer fileContainer, XmlParseMode xmlParseMode) { WebConnection.TouchedFiles.Add(fileContainer); // Verify permission if (null == fileContainer.LoadPermission(WebConnection.Session.User.Id)) throw new WebResultsOverrideException(WebResults.From(Status._401_Unauthorized, "You do not have permission to read " + fileContainer.FullPath)); if (!(fileContainer.FileHandler is ITextHandler)) throw new WebResultsOverrideException(WebResults.From(Status._400_Bad_Request, fileContainer.FullPath + " must be a text file")); return LoadXmlDocument( fileContainer.CastFileHandler<ITextHandler>().ReadAll(), xmlParseMode, fileContainer.FullPath); }
private ParentScope CreateParentScope(IFileContainer javascriptContainer) { List<string> scriptsToEval = new List<string>(); List<string> requestedScripts = new List<string>(new string[] { "/API/AJAX_serverside.js", "/API/json2.js" }); string fileType = null; StringBuilder javascriptBuilder = new StringBuilder(); foreach (string line in javascriptContainer.CastFileHandler<ITextHandler>().ReadLines()) { // find file type if (line.Trim().StartsWith("// FileType:")) fileType = line.Substring(12).Trim(); // Find dependant scripts else if (line.Trim().StartsWith("// Scripts:")) foreach (string script in line.Substring(11).Split(',')) requestedScripts.Add(script.Trim()); else javascriptBuilder.AppendFormat("{0}\n", line); } string javascript = javascriptBuilder.ToString(); Dictionary<string, MethodInfo> functionsInScope = new Dictionary<string, MethodInfo>(); List<KeyValuePair<IFileContainer, DateTime>> loadedScriptsModifiedTimes = new List<KeyValuePair<IFileContainer, DateTime>>(); ISession ownerSession = FileHandlerFactoryLocator.SessionManagerHandler.CreateSession(); try { ownerSession.Login(javascriptContainer.Owner); IWebConnection ownerWebConnection = new BlockingShellWebConnection( FileHandlerFactoryLocator.WebServer, ownerSession, javascriptContainer.FullPath, null, null, new CookiesFromBrowser(), CallingFrom.Web, WebMethod.GET); IEnumerable<ScriptAndMD5> dependantScriptsAndMD5s = FileHandlerFactoryLocator.WebServer.WebComponentResolver.DetermineDependantScripts( requestedScripts, ownerWebConnection); // Load static methods that are passed into the Javascript environment as-is foreach (Type javascriptFunctionsType in GetTypesThatHaveJavascriptFunctions(fileType)) foreach (MethodInfo method in javascriptFunctionsType.GetMethods(BindingFlags.Static | BindingFlags.Public)) functionsInScope[method.Name] = method; // Load all dependant scripts foreach (ScriptAndMD5 dependantScript in dependantScriptsAndMD5s) { string scriptName = dependantScript.ScriptName; if (scriptName.Contains("?")) scriptsToEval.Add(ownerWebConnection.ShellTo(scriptName).ResultsAsString); else { IFileContainer scriptFileContainer = FileHandlerFactoryLocator.FileSystemResolver.ResolveFile(scriptName); if (scriptFileContainer.FileHandler is ITextHandler) { loadedScriptsModifiedTimes.Add(new KeyValuePair<IFileContainer, DateTime>(scriptFileContainer, scriptFileContainer.LastModified)); scriptsToEval.Add(scriptFileContainer.CastFileHandler<ITextHandler>().ReadAll()); } else scriptsToEval.Add(ownerWebConnection.ShellTo(scriptName).ResultsAsString); } } loadedScriptsModifiedTimes.Add(new KeyValuePair<IFileContainer, DateTime>(javascriptContainer, javascriptContainer.LastModified)); // Construct Javascript to shell to the "base" webHandler HashSet<Type> webHandlerTypes = new HashSet<Type>(FileHandlerFactoryLocator.WebHandlerPlugins); if (null != fileType) webHandlerTypes.Add(FileHandlerFactoryLocator.WebHandlerClasses[fileType]); string baseWrapper = GetJavascriptWrapperForBase("base", webHandlerTypes); scriptsToEval.Add(baseWrapper); scriptsToEval.Add(javascript); scriptsToEval.Add("if (this.options) options; else null;"); ParentScope parentScope = new ParentScope(loadedScriptsModifiedTimes, functionsInScope); Dictionary<string, object> data = new Dictionary<string, object>(); data["Scripts"] = scriptsToEval; data["Functions"] = functionsInScope.Keys; _SubProcess.CreateParentScope(parentScope.ParentScopeId, Thread.CurrentThread.ManagedThreadId, data); return parentScope; } finally { FileHandlerFactoryLocator.SessionManagerHandler.EndSession(ownerSession.SessionId); } }
/// <summary> /// /// </summary> /// <param name="templateParsingState"></param> /// <param name="fileContainer"></param> /// <param name="namedPermission"></param> /// <returns></returns> protected abstract bool DetermineCondition(ITemplateParsingState templateParsingState, IFileContainer fileContainer, string namedPermission);
public void License(IFileContainer container) { container.CreateFile("LICENSE", GenerateLicenseFile()); }
public DelegateWrapper(WebCallableMethod webCallableMethod, IWebHandlerPlugin webHandlerPlugin) { WebCallableMethod = webCallableMethod; FileContainer = webHandlerPlugin.FileContainer; WebHandlerPlugin = webHandlerPlugin; }
/// <summary> /// Creates a new MethodNameAndContainer for a specfic plugin /// </summary> /// <param name="methodName"></param> /// <param name="fileContainer"></param> /// <param name="webHandler"></param> /// <returns></returns> public static MethodNameAndFileContainer New(string methodName, IFileContainer fileContainer, IWebHandlerPlugin webHandlerPlugin) { MethodNameAndFileContainer me = new MethodNameAndFileContainer(); me._MethodName = methodName; me._FileContainer = fileContainer; me._WebHandlerPlugin = webHandlerPlugin; return me; }
public virtual void CreateRootDirectoryHandler(IFileContainer rootDirectoryContainer) { // Construct the root directory on disk FileHandlerFactoryLocator.DirectoryFactory.CreateFile(FileHandlerFactoryLocator.FileSystem.RootDirectoryId); IDirectoryHandler rootDirectoryHandler = rootDirectoryContainer.CastFileHandler<IDirectoryHandler>(); // Create users folder IDirectoryHandler usersDirectory = (IDirectoryHandler)rootDirectoryHandler.CreateFile("Users", "directory", null); IUserManagerHandler userManager = usersDirectory.CreateSystemFile<IUserManagerHandler>("UserDB", "usermanager", null); userManager.Dispose(); userManager = FileHandlerFactoryLocator.UserManagerHandler; IUserFactory userFactory = FileHandlerFactoryLocator.UserFactory; IUser anonymousUser = userManager.CreateUser( "anonymous", "", "anonymous", userFactory.AnonymousUser.Id, true); usersDirectory.DeleteFile(null, "anonymous"); usersDirectory.RestoreFile("anonymous avatar.jpg", "image", "anonymous avatar.jpg", userFactory.RootUser.Id); usersDirectory.SetPermission(null, "anonymous avatar.jpg", new ID<IUserOrGroup, Guid>[] {userFactory.Everybody.Id}, FilePermissionEnum.Read, false, false); anonymousUser.UserHandler.Set(null, "Avatar", "/Users/anonymous avatar.jpg"); IUser rootUser = userManager.CreateUser( "root", DefaultRootPassword, "root", userFactory.RootUser.Id, true); rootUser.UserHandler.Set(rootUser, "Avatar", "/DefaultTemplate/root.jpg"); // Let the root user see information about the anonymous user IFileContainer anonymousUserFileContainer = usersDirectory.OpenFile("anonymous.user"); usersDirectory.Chown(null, anonymousUserFileContainer.FileId, rootUser.Id); usersDirectory.RemovePermission("anonymous.user", new ID<IUserOrGroup, Guid>[] { anonymousUser.Id }); // Create groups IGroup everybody = userManager.CreateGroup(userFactory.Everybody.Name, userFactory.Everybody.Name, null, userFactory.Everybody.Id, true, true, GroupType.Private); userManager.CreateGroup(userFactory.AuthenticatedUsers.Name, userFactory.AuthenticatedUsers.Name, null, userFactory.AuthenticatedUsers.Id, true, true, GroupType.Private); userManager.CreateGroup(userFactory.LocalUsers.Name, userFactory.LocalUsers.Name, null, userFactory.LocalUsers.Id, true, true, GroupType.Private); IGroup administrators = userManager.CreateGroup(userFactory.Administrators.Name, userFactory.Administrators.Name, rootUser.Id, userFactory.Administrators.Id, true, false, GroupType.Private); // Add root user to administrators userManager.AddUserToGroup(rootUser.Id, administrators.Id); // Allow people who aren't logged in to read the user database usersDirectory.SetPermission( null, "UserDB", new ID<IUserOrGroup, Guid>[] {everybody.Id}, ObjectCloud.Interfaces.Security.FilePermissionEnum.Read, false, false); // Allow administrators to administer the user database usersDirectory.SetPermission( null, "UserDB", new ID<IUserOrGroup, Guid>[] { administrators.Id }, ObjectCloud.Interfaces.Security.FilePermissionEnum.Administer, false, false); // Create shell directory rootDirectoryHandler.RestoreFile( "Shell", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Shell", rootUser.Id); // Create shell directory rootDirectoryHandler.RestoreFile( "Config", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Config", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Config", new ID<IUserOrGroup, Guid>[] { everybody.Id }, ObjectCloud.Interfaces.Security.FilePermissionEnum.Read, false, false); rootDirectoryHandler.SetPermission( null, "Config", new ID<IUserOrGroup, Guid>[] { administrators.Id }, ObjectCloud.Interfaces.Security.FilePermissionEnum.Administer, false, false); rootDirectoryHandler.SetPermission( null, "Shell", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create API directory rootDirectoryHandler.RestoreFile( "API", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "API", rootUser.Id); rootDirectoryHandler.SetPermission( null, "API", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create Templates directory rootDirectoryHandler.RestoreFile( "Templates", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Templates", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Templates", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create Tests directory rootDirectoryHandler.RestoreFile( "Tests", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Tests", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Tests", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create Pages directory rootDirectoryHandler.RestoreFile( "Pages", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Pages", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Pages", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create Pages directory rootDirectoryHandler.RestoreFile( "Docs", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Docs", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Docs", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create Classes directory rootDirectoryHandler.RestoreFile( "Classes", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "Classes", rootUser.Id); rootDirectoryHandler.SetPermission( null, "Classes", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create DefaultTemplate directory rootDirectoryHandler.RestoreFile( "DefaultTemplate", "directory", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "DefaultTemplate", rootUser.Id); rootDirectoryHandler.SetPermission( null, "DefaultTemplate", new ID<IUserOrGroup, Guid>[] {everybody.Id}, FilePermissionEnum.Read, true, false); // Create index.oc rootDirectoryHandler.RestoreFile( "index.oc", "text", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "index.oc", rootUser.Id); rootDirectoryHandler.SetPermission( null, "index.oc", new ID<IUserOrGroup, Guid>[] { everybody.Id }, FilePermissionEnum.Read, true, false); // Create favicon.ico rootDirectoryHandler.RestoreFile( "favicon.ico", "binary", "." + Path.DirectorySeparatorChar + "DefaultFiles" + Path.DirectorySeparatorChar + "favicon.ico", rootUser.Id); rootDirectoryHandler.SetPermission( null, "favicon.ico", new ID<IUserOrGroup, Guid>[] { everybody.Id }, FilePermissionEnum.Read, true, false); rootDirectoryHandler.IndexFile = "index.oc"; // "/System/SessionManager" IDirectoryHandler SystemDirectory = (IDirectoryHandler)rootDirectoryHandler.CreateFile( "System", "directory", rootUser.Id); SystemDirectory.CreateFile( "SessionManager", "sessionmanager", rootUser.Id); // Allow logged in users to manage their sessions SystemDirectory.SetPermission( null, "SessionManager", new ID<IUserOrGroup, Guid>[] { FileHandlerFactoryLocator.UserFactory.AuthenticatedUsers.Id }, FilePermissionEnum.Read, false, false); // Create the proxy SystemDirectory.CreateFile( "Proxy", "proxy", rootUser.Id); SystemDirectory.SetPermission( null, "Proxy", new ID<IUserOrGroup, Guid>[] { FileHandlerFactoryLocator.UserFactory.Everybody.Id }, FilePermissionEnum.Read, false, false); // Create the log SystemDirectory.CreateFile( "Log", "log", rootUser.Id); SystemDirectory.SetPermission( null, "Log", new ID<IUserOrGroup, Guid>[] { FileHandlerFactoryLocator.UserFactory.Administrators.Id }, FilePermissionEnum.Administer, true, false); DoUpgrades(rootDirectoryHandler); }
/// <summary> /// Creates a new MethodNameAndContainer for the default web handler /// </summary> /// <param name="methodName"></param> /// <param name="fileContainer"></param> /// <returns></returns> public static MethodNameAndFileContainer New(string methodName, IFileContainer fileContainer) { return New(methodName, fileContainer, fileContainer.WebHandler); }