public ActionResult Upload(HttpPostedFileBase file)
        {
            if (!Services.Authorizer.Authorize(Permissions.InstallTemplate, T("Not allowed to install template")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (file != null)
            {
                try
                {
                    string path = Path.Combine("Sites", _shellSettings.Name, ModuleGeneratorService.ModuleTemplatesPathName);
                    if (!_appDataFolder.DirectoryExists(path))
                    {
                        _appDataFolder.CreateDirectory(path);
                    }
                    string fileName = Path.GetFileName(file.FileName);
                    if (!string.IsNullOrWhiteSpace(fileName))
                    {
                        string fullPath = _appDataFolder.MapPath(Path.Combine(path, fileName));
                        file.SaveAs(fullPath);
                        if (_zipFileService.IsZipFile(fullPath))
                        {
                            _zipFileService.ExtractToDirectory(fullPath, _appDataFolder.MapPath(Path.Combine(path, Path.GetFileNameWithoutExtension(fileName))));
                            return(SuccessResult());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Upload file failed.");
                }
            }
            return(new EmptyResult());
        }
Пример #2
0
        private void EnsureDirectoryExists()
        {
            var directory = new DirectoryInfo(_appDataFolder.MapPath(_basePath));

            if (!directory.Exists)
            {
                directory.Create();
            }
        }
Пример #3
0
        public PipelineFilePart Upload(HttpPostedFileBase input, string role, string tag)
        {
            var part        = _orchardServices.ContentManager.New <PipelineFilePart>(Common.PipelineFileName);
            var permissions = part.As <ContentPermissionsPart>();

            permissions.Enabled = true;

            permissions.ViewContent   = "Administrator";
            permissions.EditContent   = "Administrator";
            permissions.DeleteContent = "Administrator";

            permissions.ViewOwnContent   = "Authenticated";
            permissions.EditOwnContent   = "Authenticated";
            permissions.DeleteOwnContent = "Authenticated";

            if (role != "Private")
            {
                permissions.ViewContent += "," + role;
            }

            part.As <TitlePart>().Title = input.FileName;

            if (tag != string.Empty)
            {
                var tags = tag.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(t => !t.Equals(Common.AllTag, StringComparison.OrdinalIgnoreCase)).ToArray();
                if (tags.Any())
                {
                    _tagService.UpdateTagsForContentItem(part.ContentItem, tags);
                }
            }

            var exportFile = string.Format("{0}-{1}-{2}",
                                           _orchardServices.WorkContext.CurrentUser.UserName,
                                           _clock.UtcNow.ToString(FileTimestamp),
                                           Path.GetFileName(input.FileName)
                                           );

            if (!_appDataFolder.DirectoryExists(Common.FileFolder))
            {
                _appDataFolder.CreateDirectory(Common.FileFolder);
            }

            part.FullPath  = _appDataFolder.MapPath(_appDataFolder.Combine(Common.FileFolder, exportFile));
            part.Direction = "In";
            input.SaveAs(part.FullPath);
            _orchardServices.ContentManager.Create(part);

            _orchardServices.Notifier.Information(T("{0} uploaded successfully.", Path.GetFileName(input.FileName)));

            return(part);
        }
Пример #4
0
        public PipelineFilePart Upload(HttpPostedFileBase input, string role, string tag, int number)
        {
            var part        = _orchardServices.ContentManager.New <PipelineFilePart>(Common.PipelineFileName);
            var permissions = part.As <ContentPermissionsPart>();

            permissions.Enabled = true;

            permissions.ViewContent   = "Administrator";
            permissions.EditContent   = "Administrator";
            permissions.DeleteContent = "Administrator";

            permissions.ViewOwnContent   = "Authenticated";
            permissions.EditOwnContent   = "Authenticated";
            permissions.DeleteOwnContent = "Authenticated";

            if (role != "Private")
            {
                permissions.ViewContent += "," + role;
            }

            part.OriginalName           = input.FileName;
            part.As <TitlePart>().Title = input.FileName;

            if (tag != string.Empty)
            {
                var tags = tag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(t => !t.Equals(Common.AllTag, StringComparison.OrdinalIgnoreCase)).ToArray();
                if (tags.Any())
                {
                    _tagService.UpdateTagsForContentItem(part.ContentItem, tags);
                }
            }

            var exportFile = Common.GetSafeFileName(_orchardServices.WorkContext.CurrentUser.UserName, Path.GetFileName(input.FileName), number);

            var path = Common.GetAppFolder();

            if (!_appDataFolder.DirectoryExists(path))
            {
                _appDataFolder.CreateDirectory(path);
            }

            part.FullPath  = _appDataFolder.MapPath(_appDataFolder.Combine(path, exportFile));
            part.Direction = "In";
            input.SaveAs(part.FullPath);
            _orchardServices.ContentManager.Create(part);

            return(part);
        }
Пример #5
0
        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            Argument.ThrowIfNull(shellSettings, nameof(shellSettings));
            Argument.ThrowIfNullOrWhiteSpace(shellSettings.Name,
                                             nameof(shellSettings.Name),
                                             "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.");

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }
            var tenantPath = _appDataFolder.MapPath(
                _appDataFolder.Combine(
                    _optionsAccessor.Value.Location,
                    shellSettings.Name,
                    string.Format(SettingsFileNameFormat, "txt")));

            var configurationProvider =
                new YamlConfigurationProvider(tenantPath, false);

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
Пример #6
0
        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            if (shellSettings == null)
            {
                throw new ArgumentNullException(nameof(shellSettings));
            }
            if (string.IsNullOrWhiteSpace(shellSettings.Name))
            {
                throw new ArgumentException(
                          "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.",
                          nameof(shellSettings.Name));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }
            var tenantPath = _appDataFolder.MapPath(_appDataFolder.Combine("Sites", shellSettings.Name));

            var configurationProvider = new YamlConfigurationProvider(
                _appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "txt")), false);

            foreach (var key in shellSettings.RootConfiguration.GetChildren())
            {
                configurationProvider.Set(key.Key, key.Value);
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
Пример #7
0
        IEnumerable <ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var tenantPaths = _appDataFolder
                              .ListDirectories("Sites")
                              .Select(path => _appDataFolder.MapPath(path));

            var shellSettings = new List <ShellSettings>();

            foreach (var tenantPath in tenantPaths)
            {
                _logger.LogInformation("ShellSettings found in '{0}', attempting to load.", tenantPath);

                var configurationContainer =
                    new ConfigurationBuilder()
                    .AddJsonFile(_appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "json")),
                                 true)
                    .AddXmlFile(_appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "xml")),
                                true)
                    .Add(
                        new DefaultFileConfigurationSource(
                            _appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "txt")), false));

                var config = configurationContainer.Build();

                var shellSetting = new ShellSettings {
                    Name = config["Name"],
                    DataConnectionString = config["DataConnectionString"],
                    DataProvider         = config["DataProvider"],
                    DataTablePrefix      = config["DataTablePrefix"],
                    RequestUrlHost       = config["RequestUrlHost"],
                    RequestUrlPrefix     = config["RequestUrlPrefix"]
                };

                TenantState state;
                shellSetting.State = Enum.TryParse(config["State"], true, out state)
                    ? state
                    : TenantState.Uninitialized;

                shellSettings.Add(shellSetting);

                _logger.LogInformation("Loaded ShellSettings for tenant '{0}'", shellSetting.Name);
            }

            return(shellSettings);
        }
        IEnumerable <ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var tenantPaths = _appDataFolder
                              .ListDirectories("Sites")
                              .Select(path => _appDataFolder.MapPath(path));

            var shellSettings = new List <ShellSettings>();

            foreach (var tenantPath in tenantPaths)
            {
                Logger.Information("ShellSettings found in '{0}', attempting to load.", tenantPath);

                IConfigurationSourceRoot configurationContainer =
                    new Microsoft.Framework.ConfigurationModel.Configuration()
                    .AddJsonFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "json")),
                                 true)
                    .AddXmlFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "xml")),
                                true)
                    .AddIniFile(_appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "ini")),
                                true)
                    .Add(
                        new DefaultFileConfigurationSource(
                            _appDataFolder.Combine(tenantPath, string.Format(_settingsFileNameFormat, "txt")), false));

                var shellSetting = new ShellSettings {
                    Name = configurationContainer.Get <string>("Name"),
                    DataConnectionString = configurationContainer.Get <string>("DataConnectionString"),
                    DataProvider         = configurationContainer.Get <string>("DataProvider"),
                    DataTablePrefix      = configurationContainer.Get <string>("DataTablePrefix"),
                    RequestUrlHost       = configurationContainer.Get <string>("RequestUrlHost"),
                    RequestUrlPrefix     = configurationContainer.Get <string>("RequestUrlPrefix")
                };

                TenantState state;
                shellSetting.State = Enum.TryParse(configurationContainer.Get <string>("State"), true, out state)
                    ? state
                    : TenantState.Uninitialized;

                shellSettings.Add(shellSetting);

                Logger.Information("Loaded ShellSettings for tenant '{0}'", shellSetting.Name);
            }

            return(shellSettings);
        }
Пример #9
0
        private void ConvertToExport(string user, Process process, PipelineConfigurationPart part, string exportType, IDictionary <string, string> parameters)
        {
            var o = process.Output();

            switch (exportType)
            {
            case "xlsx":
                var folder = Common.GetAppFolder();
                if (!_appDataFolder.DirectoryExists(folder))
                {
                    _appDataFolder.CreateDirectory(folder);
                }

                var fileName = Common.GetSafeFileName(user, _slugService.Slugify(part.Title()), "xlsx");

                o.Provider = "excel";
                o.File     = _appDataFolder.MapPath(_appDataFolder.Combine(folder, fileName));
                break;

            case "geojson":
                o.Stream   = true;
                o.Provider = "geojson";
                o.File     = _slugService.Slugify(part.Title()) + ".geojson";
                break;

            case "kml":
                o.Stream   = true;
                o.Provider = "kml";
                o.File     = _slugService.Slugify(part.Title()) + ".kml";
                break;

            default:     //csv
                o.Stream    = true;
                o.Provider  = "file";
                o.Delimiter = ",";
                o.File      = _slugService.Slugify(part.Title()) + ".csv";
                break;
            }

            parameters["page"] = "0";

            foreach (var entity in process.Entities)
            {
                entity.Page = 0;
                entity.Fields.RemoveAll(f => f.System);

                foreach (var field in entity.GetAllFields())
                {
                    if (field.Alias == Common.BatchValueFieldName)
                    {
                        field.Output = false;
                    }
                    field.T      = string.Empty; // because short-hand has already been expanded
                    field.Output = field.Output && field.Export == "defer" || field.Export == "true";
                }
            }
        }
Пример #10
0
        private Hash ComputeHash()
        {
            var hash = new Hash();

            // Shell settings physical location
            //   The nhibernate configuration stores the physical path to the SqlCe database
            //   so we need to include the physical location as part of the hash key, so that
            //   xcopy migrations work as expected.
            var pathName = GetPathName(_shellSettings.Name);

            hash.AddString(_appDataFolder.MapPath(pathName).ToLowerInvariant());

            // Orchard version, to rebuild the mappings for each new version
            var orchardVersion = new System.Reflection.AssemblyName(typeof(Orchard.ContentManagement.ContentItem).Assembly.FullName).Version.ToString();

            hash.AddString(orchardVersion);

            // Shell settings data
            hash.AddString(_shellSettings.DataProvider);
            hash.AddString(_shellSettings.DataTablePrefix);
            hash.AddString(_shellSettings.DataConnectionString);
            hash.AddString(_shellSettings.Name);

            // Assembly names, record names and property names
            foreach (var tableName in _shellBlueprint.Records.Select(x => x.TableName))
            {
                hash.AddString(tableName);
            }

            foreach (var recordType in _shellBlueprint.Records.Select(x => x.Type))
            {
                hash.AddTypeReference(recordType);

                if (recordType.BaseType != null)
                {
                    hash.AddTypeReference(recordType.BaseType);
                }

                foreach (var property in recordType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
                {
                    hash.AddString(property.Name);
                    hash.AddTypeReference(property.PropertyType);

                    foreach (var attr in property.GetCustomAttributesData())
                    {
                        hash.AddTypeReference(attr.Constructor.DeclaringType);
                    }
                }
            }

            _configurers.Invoke(c => c.ComputingHash(hash), Logger);

            return(hash);
        }
        protected override Directory GetDirectory(string indexName)
        {
            var cacheDirectoryPath = _appDataFolder.Combine("Sites", _shellSettings.Name, "IndexingCache", indexName);
            var cacheDirectoryInfo = new System.IO.DirectoryInfo(_appDataFolder.MapPath(cacheDirectoryPath));

            return(new AzureDirectory(
                       _storageAccount,
                       "lucene",
                       FSDirectory.Open(cacheDirectoryInfo),
                       false,
                       _shellSettings.Name + "/" + indexName));
        }
Пример #12
0
        public FilePart Upload(HttpPostedFileBase input)
        {
            var part       = _orchardServices.ContentManager.New <FilePart>("File");
            var exportFile = string.Format("{0}-{1}-{2}",
                                           _orchardServices.WorkContext.CurrentUser.UserName,
                                           _clock.UtcNow.ToString(FILE_TIMESTAMP),
                                           Path.GetFileName(input.FileName)
                                           );

            if (!_appDataFolder.DirectoryExists(TRANSFORMALIZE_FOLDER))
            {
                _appDataFolder.CreateDirectory(TRANSFORMALIZE_FOLDER);
            }

            part.FullPath  = _appDataFolder.MapPath(_appDataFolder.Combine(TRANSFORMALIZE_FOLDER, exportFile));
            part.Direction = "In";
            input.SaveAs(part.FullPath);
            _orchardServices.ContentManager.Create(part);
            _orchardServices.Notifier.Information(T("{0} uploaded successfully.", Path.GetFileName(input.FileName)));

            return(part);
        }
Пример #13
0
 public ExtensionLibraryService(
     ApplicationPartManager applicationPartManager,
     IOrchardFileSystem fileSystem,
     IAppDataFolder appDataFolder,
     ILogger<ExtensionLibraryService> logger)
 {
     _applicationPartManager = applicationPartManager;
     _fileSystem = fileSystem;
     _appDataFolder = appDataFolder;
     _probingFolderPath = _appDataFolder.MapPath(ProbingDirectoryName);
     _logger = logger;
     T = NullLocalizer.Instance;
 }
Пример #14
0
        public void Configure(DbContextOptionsBuilder optionsBuilders)
        {
            var shellPath = _appDataFolder.Combine("Sites", _shellSettings.Name);

            _appDataFolder.CreateDirectory(shellPath);

            var shellFolder = _appDataFolder.MapPath(shellPath);

            foreach (var provider in _dataServicesProviders)
            {
                provider.ConfigureContextOptions(optionsBuilders, string.Empty);
            }
        }
Пример #15
0
 public ExtensionLibraryService(
     ApplicationPartManager applicationPartManager,
     IOrchardFileSystem fileSystem,
     IAppDataFolder appDataFolder,
     ILogger <ExtensionLibraryService> logger)
 {
     _metadataReferences     = new Lazy <List <MetadataReference> >(GetMetadataReferences);
     _applicationPartManager = applicationPartManager;
     _fileSystem             = fileSystem;
     _probingFolderPath      = appDataFolder.MapPath(ProbingDirectoryName);
     _logger = logger;
     T       = NullLocalizer.Instance;
 }
Пример #16
0
        private void ConvertToExport(string user, Process process, PipelineConfigurationPart part, string exportType, IDictionary <string, string> parameters)
        {
            var o = process.Output();

            switch (exportType)
            {
            case "xlsx":
                if (!_appDataFolder.DirectoryExists(Common.FileFolder))
                {
                    _appDataFolder.CreateDirectory(Common.FileFolder);
                }

                var fileName = $"{user}-{_clock.UtcNow.ToString(FileTimestamp)}-{_slugService.Slugify(part.Title())}.xlsx";

                o.Provider = "excel";
                o.File     = _appDataFolder.MapPath(_appDataFolder.Combine(Common.FileFolder, fileName));
                break;

            case "geojson":
                o.Stream   = true;
                o.Provider = "geojson";
                o.File     = _slugService.Slugify(part.Title()) + ".geojson";
                break;

            case "kml":
                o.Stream   = true;
                o.Provider = "kml";
                o.File     = _slugService.Slugify(part.Title()) + ".kml";
                break;

            default:     //csv
                o.Stream    = true;
                o.Provider  = "file";
                o.Delimiter = ",";
                o.File      = _slugService.Slugify(part.Title()) + ".csv";
                break;
            }

            parameters["page"] = "0";

            foreach (var entity in process.Entities)
            {
                entity.Page = 0;
                entity.Fields.RemoveAll(f => f.System);

                foreach (var field in entity.GetAllFields())
                {
                    field.Output = field.Output && field.Export == "defer" || field.Export == "true";
                }
            }
        }
        public SessionFactoryParameters GetSessionFactoryParameters()
        {
            var shellPath = _appDataFolder.Combine("Sites", _shellSettings.Name);

            _appDataFolder.CreateDirectory(shellPath);

            var shellFolder = _appDataFolder.MapPath(shellPath);

            return(new SessionFactoryParameters {
                Provider = _shellSettings.DataProvider,
                DataFolder = shellFolder,
                ConnectionString = _shellSettings.DataConnectionString,
                RecordDescriptors = _shellBlueprint.Records,
            });
        }
Пример #18
0
        public void Activated()
        {
            var extension = this.extensionManager.GetExtension("OC.GITConnector");
            var path      = Path.Combine(extension.Location, extension.Id, "lib/win32/x86/git2-a5cf255.dll").Replace(Path.DirectorySeparatorChar, '/');

            var destination = Path.Combine("Dependencies", "git2-a5cf255.dll");

            if (!this.appDataFolder.FileExists(destination))
            {
                var stream = new MemoryStream();
                this.webSiteFolder.CopyFileTo(path, stream);
                stream.Seek(0, SeekOrigin.Begin);
                File.WriteAllBytes(appDataFolder.MapPath(destination), stream.ToArray());
            }
        }
        private string WriteExportFile(string exportDocument)
        {
            var exportFile = string.Format("Export-{0}-{1}.xml", _orchardServices.WorkContext.CurrentUser.UserName, DateTime.UtcNow.Ticks);

            if (!_appDataFolder.DirectoryExists(ExportsDirectory))
            {
                _appDataFolder.CreateDirectory(ExportsDirectory);
            }

            var path = _appDataFolder.Combine(ExportsDirectory, exportFile);

            _appDataFolder.CreateFile(path, exportDocument);

            return(_appDataFolder.MapPath(path));
        }
Пример #20
0
        public void Configure(DbContextOptionsBuilder optionsBuilders)
        {
            var shellPath = _appDataFolder.Combine("Sites", _shellSettings.Name);

            _appDataFolder.CreateDirectory(shellPath);

            var shellFolder = _appDataFolder.MapPath(shellPath);

            _dataServicesProviderFactory.CreateProvider(
                new DataServiceParameters {
                Provider         = _shellSettings.DataProvider,
                ConnectionString = _shellSettings.DataConnectionString,
                DataFolder       = shellFolder
            })
            .ConfigureContextOptions(optionsBuilders, _shellSettings.DataConnectionString);
        }
Пример #21
0
        private Hash ComputeHash()
        {
            var hash = new Hash();

            // Shell settings physical location
            //   The nhibernate configuration stores the physical path to the SqlCe database
            //   so we need to include the physical location as part of the hash key, so that
            //   xcopy migrations work as expected.
            var pathName = GetPathName(_shellSettings.Name);

            hash.AddString(_appDataFolder.MapPath(pathName).ToLowerInvariant());

            // Shell settings data
            hash.AddString(_shellSettings.DataProvider);
            hash.AddString(_shellSettings.DataTablePrefix);
            hash.AddString(_shellSettings.DataConnectionString);
            hash.AddString(_shellSettings.Name);

            // Assembly names, record names and property names
            foreach (var tableName in _shellBlueprint.Records.Select(x => x.TableName))
            {
                hash.AddString(tableName);
            }

            foreach (var recordType in _shellBlueprint.Records.Select(x => x.Type))
            {
                hash.AddTypeReference(recordType);

                if (recordType.BaseType != null)
                {
                    hash.AddTypeReference(recordType.BaseType);
                }

                foreach (var property in recordType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public))
                {
                    hash.AddString(property.Name);
                    hash.AddTypeReference(property.PropertyType);

                    foreach (var attr in property.GetCustomAttributesData())
                    {
                        hash.AddTypeReference(attr.Constructor.DeclaringType);
                    }
                }
            }

            return(hash);
        }
Пример #22
0
        public bool SaveSettings(IShellSettings shellSettings)
        {
            if (shellSettings == null)
            {
                throw new ArgumentNullException(nameof(shellSettings));
            }

            if (string.IsNullOrEmpty(shellSettings.Name))
            {
                throw new ArgumentNullException(nameof(shellSettings.Name));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving shell settings for tenant '{0}'", shellSettings.Name);
            }

            var fileName   = string.Format(SettingsFileNameFormat, "txt");
            var tenantPath = _appDataFolder.MapPath(
                _appDataFolder.Combine(
                    _optionsAccessor.Value.Location,
                    shellSettings.Location,
                    fileName));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = tenantPath,
                Optional = false
            });

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved shell settings for tenant '{0}'", shellSettings.Name);
            }

            return(true);
        }
Пример #23
0
        public string WriteExportFile(XDocument recipeDocument)
        {
            var exportFile = String.Format("Export-{0}-{1}.xml", _orchardServices.WorkContext.CurrentUser.UserName, _clock.UtcNow.Ticks);

            if (!_appDataFolder.DirectoryExists(ExportsDirectory))
            {
                _appDataFolder.CreateDirectory(ExportsDirectory);
            }

            var path = _appDataFolder.Combine(ExportsDirectory, exportFile);

            using (var writer = new XmlTextWriter(_appDataFolder.CreateFile(path), Encoding.UTF8)) {
                writer.Formatting = Formatting.Indented;
                recipeDocument.WriteTo(writer);
            }

            return(_appDataFolder.MapPath(path));
        }
        public DbContextOptions BuildConfiguration()
        {
            lock (this)
            {
                if (_dbContextOptions == null)
                {
                    var shellPath = _appDataFolder.Combine("Sites", _shellSettings.Name);
                    _appDataFolder.CreateDirectory(shellPath);

                    var shellFolder = _appDataFolder.MapPath(shellPath);

                    _dbContextOptions = _dataServicesProviderFactory.CreateProvider(
                        new DataServiceParameters
                    {
                        Provider         = _shellSettings.DataProvider,
                        ConnectionString = _shellSettings.DataConnectionString,
                        DataFolder       = shellFolder
                    })
                                        .BuildContextOptions();
                }
            }
            return(_dbContextOptions);
        }
Пример #25
0
 public string MapPath(string path)
 {
     return(_appDataFolder.MapPath(path));
 }
Пример #26
0
        public void PhysicalPathAddsToBasePathAndDoesNotNeedToExist()
        {
            var physicalPath = _appDataFolder.MapPath("delta\\epsilon.txt");

            Assert.Equal(Path.Combine(_tempFolder, "delta\\epsilon.txt"), physicalPath);
        }
Пример #27
0
        public void PhysicalPathAddsToBasePathAndDoesNotNeedToExist()
        {
            var physicalPath = _appDataFolder.MapPath(String.Format("delta{0}epsilon.txt", Path.DirectorySeparatorChar));

            Assert.Equal(Path.Combine(_tempFolder, String.Format("App_Data{0}delta{0}epsilon.txt", Path.DirectorySeparatorChar)), physicalPath);
        }
        protected virtual Directory GetDirectory(string indexName)
        {
            var directoryInfo = new DirectoryInfo(_appDataFolder.MapPath(_appDataFolder.Combine(_basePath, indexName)));

            return(FSDirectory.Open(directoryInfo));
        }
Пример #29
0
        protected override void Load(ContainerBuilder builder)
        {
            if (_process == null)
            {
                return;
            }

            // Connections
            foreach (var connection in _process.Connections.Where(c => c.Provider == "file"))
            {
                // Schema Reader
                builder.Register <ISchemaReader>(ctx => {
                    /* file and excel are different, have to load the content and check it to determine schema */
                    var fileInfo = new FileInfo(Path.IsPathRooted(connection.File) ? connection.File : ctx.Resolve <IAppDataFolder>().Combine(Common.FileFolder, connection.File));
                    var context  = ctx.ResolveNamed <IConnectionContext>(connection.Key);
                    var cfg      = new FileInspection(context, fileInfo, 100).Create();
                    var process  = ctx.Resolve <Process>();
                    process.Load(cfg);

                    foreach (var warning in process.Warnings())
                    {
                        context.Warn(warning);
                    }

                    if (process.Errors().Any())
                    {
                        foreach (var error in process.Errors())
                        {
                            context.Error(error);
                        }
                        return(new NullSchemaReader());
                    }

                    return(new SchemaReader(context, new RunTimeRunner(context, ctx.Resolve <IAppDataFolder>(), ctx.Resolve <ITemplateProcessor>(), ctx.Resolve <INotifier>()), process));
                }).Named <ISchemaReader>(connection.Key);
            }

            // entity input
            foreach (var entity in _process.Entities.Where(e => _process.Connections.First(c => c.Name == e.Connection).Provider == "file"))
            {
                // input version detector
                builder.RegisterType <NullInputProvider>().Named <IInputProvider>(entity.Key);

                // input read
                builder.Register <IRead>(ctx => {
                    var input      = ctx.ResolveNamed <InputContext>(entity.Key);
                    var rowFactory = ctx.ResolveNamed <IRowFactory>(entity.Key, new NamedParameter("capacity", input.RowCapacity));

                    switch (input.Connection.Provider)
                    {
                    case "file":

                        if (input.Connection.Delimiter == string.Empty &&
                            input.Entity.Fields.Count(f => f.Input) == 1)
                        {
                            return(new FileReader(input, rowFactory));
                        }

                        return(new DelimitedFileReader(input, rowFactory));

                    default:
                        return(new NullReader(input, false));
                    }
                }).Named <IRead>(entity.Key);
            }

            // Entity Output
            if (_process.Output().Provider == "file")
            {
                // PROCESS OUTPUT CONTROLLER
                builder.Register <IOutputController>(ctx => new NullOutputController()).As <IOutputController>();

                foreach (var e in _process.Entities)
                {
                    var entity = e;

                    // ENTITY OUTPUT CONTROLLER
                    builder.Register <IOutputController>(ctx => new NullOutputController()).Named <IOutputController>(entity.Key);

                    // ENTITY WRITER
                    builder.Register(ctx => {
                        var output = ctx.ResolveNamed <OutputContext>(entity.Key);

                        switch (output.Connection.Provider)
                        {
                        case "filehelpers":
                        case "file":
                            if (output.Connection.File.StartsWith("~"))
                            {
                                if (output.Connection.File.StartsWith("~/App_Data", System.StringComparison.OrdinalIgnoreCase))
                                {
                                    output.Connection.File = _appDataFolder.MapPath(output.Connection.File);
                                }
                                else
                                {
                                    output.Connection.File = _appDataFolder.MapPath(Path.Combine("~/App_Data/", output.Connection.File.Trim('~', '/')));
                                }
                            }
                            return(output.Connection.Stream ? (IWrite) new DelimitedFileStreamWriter(output, HttpContext.Current.Response.OutputStream) : new DelimitedFileWriter(output));

                        default:
                            return(new NullWriter(output));
                        }
                    }).Named <IWrite>(entity.Key);
                }
            }
        }
        private void ConvertToExport(string user, Process process, PipelineConfigurationPart part, string exportType)
        {
            var o = process.Output();

            switch (exportType)
            {
            case "xlsx":
                var folder = Common.GetAppFolder();
                if (!_appDataFolder.DirectoryExists(folder))
                {
                    _appDataFolder.CreateDirectory(folder);
                }

                var fileName = Common.GetSafeFileName(user, _slugService.Slugify(part.Title()), "xlsx");

                o.Provider = "excel";
                o.File     = _appDataFolder.MapPath(_appDataFolder.Combine(folder, fileName));
                break;

            case "geojson":
                o.Stream   = true;
                o.Provider = "geojson";
                o.File     = _slugService.Slugify(part.Title()) + ".geo.json";

                var suppress = new HashSet <string>()
                {
                    Common.BatchValueFieldName, part.MapColorField, part.MapPopUpField
                };
                var coordinates = new HashSet <string>()
                {
                    part.MapLatitudeField, part.MapLongitudeField
                };
                foreach (var entity in process.Entities)
                {
                    foreach (var field in entity.GetAllFields())
                    {
                        if (suppress.Contains(field.Alias))
                        {
                            field.Output   = false;
                            field.Property = false;
                            field.Alias   += "Suppressed";
                        }
                        else if (coordinates.Contains(field.Alias))
                        {
                            field.Property = field.Export == "true";
                        }
                        else
                        {
                            field.Property = field.Property || field.Output && field.Export == "defer" || field.Export == "true";
                        }
                    }
                }

                break;

            case "map":
                o.Stream   = true;
                o.Provider = "geojson";
                o.File     = _slugService.Slugify(part.Title()) + ".geo.json";

                var mapFields = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { part.MapColorField, "geojson-color" },
                    { part.MapPopUpField, "geojson-description" },
                    { part.MapLatitudeField, "latitude" },
                    { part.MapLongitudeField, "longitude" },
                    { Common.BatchValueFieldName, Common.BatchValueFieldName }
                };

                ConfineData(process, mapFields);
                break;

            case "json":
                o.Stream   = true;
                o.Provider = "json";
                o.File     = _slugService.Slugify(part.Title()) + ".json";
                break;

            case "calendar":
                o.Stream   = true;
                o.Provider = "json";
                o.File     = _slugService.Slugify(part.Title()) + ".json";
                var calendarFields = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { part.CalendarIdField, "id" },
                    { part.CalendarTitleField, "title" },
                    { part.CalendarUrlField, "url" },
                    { part.CalendarClassField, "class" },
                    { part.CalendarStartField, "start" },
                    { part.CalendarEndField, "end" },
                    { Common.BatchValueFieldName, Common.BatchValueFieldName }
                };
                ConfineData(process, calendarFields);
                break;

            case "kml":
                o.Stream   = true;
                o.Provider = "kml";
                o.File     = _slugService.Slugify(part.Title()) + ".kml";
                break;

            default: // csv
                o.Stream        = true;
                o.Provider      = "file";
                o.Delimiter     = ",";
                o.TextQualifier = "\"";
                o.File          = _slugService.Slugify(part.Title()) + ".csv";
                break;
            }

            // common
            foreach (var entity in process.Entities)
            {
                entity.Fields.RemoveAll(f => f.System);

                foreach (var field in entity.GetAllFields())
                {
                    field.T = string.Empty; // because short-hand has already been expanded
                    switch (exportType)
                    {
                    case "map":
                    case "calendar":
                    case "geojson":
                        // already been modified
                        break;

                    default:
                        if (field.Alias == Common.BatchValueFieldName)
                        {
                            field.Output = false;
                        }
                        field.Output = field.Output && field.Export == "defer" || field.Export == "true";
                        break;
                    }
                }
            }
        }
        public bool GenerateModule(string templateName, TemplateModels.Module module)
        {
            if (!string.IsNullOrWhiteSpace(templateName))
            {
                string templatePath           = _appDataFolder.MapPath(Path.Combine("Sites", _shellSettings.Name, ModuleTemplatesPathName, templateName));
                string templateConfigFileName = Path.Combine(templatePath, TEMPLATECONFIG_FILENAME);
                if (File.Exists(templateConfigFileName))
                {
                    string templateConfigContent = File.ReadAllText(templateConfigFileName);
                    if (!string.IsNullOrEmpty(templateConfigContent))
                    {
                        TemplateConfig templateConfig = JsonConvert.DeserializeObject <TemplateConfig>(templateConfigContent);
                        if (templateConfig != null)
                        {
                            string moduleName = module.ModuleName;
                            if (!string.IsNullOrWhiteSpace(moduleName))
                            {
                                if (module.Settings == null)
                                {
                                    module.Settings = new Dictionary <string, string>();
                                }
                                foreach (var templateSetting in templateConfig.Settings)
                                {
                                    if (!module.Settings.ContainsKey(templateSetting.Name))
                                    {
                                        module.Settings.Add(templateSetting.Name, templateSetting.DefaultValue);
                                    }
                                }
                                string modulePath = HostingEnvironment.MapPath("~/Modules/" + moduleName);

                                Directory.CreateDirectory(modulePath);

                                var model = new Model {
                                    Module = module
                                };

                                #region Folders
                                string[] folders = templateConfig.Folders;
                                if (folders != null && folders.Length > 0)
                                {
                                    foreach (var folder in folders)
                                    {
                                        CreateSubDirectory(modulePath, folder);
                                    }
                                }
                                #endregion

                                #region Files
                                string[] files = templateConfig.Files;
                                if (files != null && files.Length > 0)
                                {
                                    foreach (var file in files)
                                    {
                                        CopyFile(templatePath, modulePath, file);
                                    }
                                }
                                #endregion

                                #region Module
                                foreach (var moduleTemplateFile in templateConfig.Module)
                                {
                                    if (!moduleTemplateFile.IsStatic)
                                    {
                                        string moduleTemplateContent = ReadTemplateFile(templatePath, moduleTemplateFile.Template);
                                        string moduleOutputContent   = Razor.Parse(moduleTemplateContent, model);
                                        WriteModuleFile(modulePath, string.Format(moduleTemplateFile.Output, moduleName), moduleOutputContent);
                                    }
                                    else
                                    {
                                        CopyFile(templatePath, moduleTemplateFile.Template, string.Format(moduleTemplateFile.Output, moduleName));
                                    }
                                }
                                #endregion

                                #region Entity
                                var entityTemplates = templateConfig.Entity.Select(templateFile =>
                                {
                                    if (!templateFile.IsStatic)
                                    {
                                        templateFile.Content = ReadTemplateFile(templatePath, templateFile.Template);
                                    }
                                    return(templateFile);
                                }).ToList();
                                foreach (var entity in model.Module.Entities)
                                {
                                    entity.Module        = module;
                                    entity.ParameterName = GetParameterName(entity.TypeName);
                                    entity.IndentityName = GetIndentityName(entity.TypeName);

                                    entityTemplates.ForEach(entityTemplate =>
                                    {
                                        if (!entityTemplate.IsStatic)
                                        {
                                            string entityOutputContent = Razor.Parse(entityTemplate.Content, entity);
                                            WriteModuleFile(modulePath, string.Format(entityTemplate.Output, moduleName, entity.TypeName), entityOutputContent);
                                        }
                                        else
                                        {
                                            CopyFile(templatePath, entityTemplate.Template, modulePath, string.Format(entityTemplate.Output, moduleName, entity.TypeName));
                                        }
                                    });
                                }
                                #endregion

                                return(true);
                            }
                        }
                    }
                }
            }
            return(false);
        }