コード例 #1
0
ファイル: RemoteFileSystem.cs プロジェクト: 5l1v3r1/Maze-1
        public async Task Remove(FileExplorerEntry entry)
        {
            if (entry.Type == FileExplorerEntryType.File)
            {
                await FileSystemResource.DeleteFile(entry.Path, _restClient);
            }
            else
            {
                await FileSystemResource.DeleteDirectory(entry.Path, _restClient);
            }

            EntryRemoved?.Invoke(this, entry);

            var parentFolder = Path.GetDirectoryName(entry.Path);

            if (parentFolder != null && TryGetCachedDirectory(parentFolder, out var cachedDirectory))
            {
                lock (cachedDirectory.EntriesLock)
                {
                    cachedDirectory.Entries = cachedDirectory.Entries.Remove(entry);
                }
            }

            if (entry.Type != FileExplorerEntryType.File)
            {
                var normalizedPath = NormalizePath(entry.Path);
                foreach (var keyValuePair in _localCache.Where(x =>
                                                               x.Key.StartsWith(normalizedPath, PathStringComparison)))
                {
                    _localCache.TryRemove(keyValuePair.Key, out _);
                }
            }
        }
コード例 #2
0
        public void Write()
        {
            IResource      input   = new FileSystemResource("Objects.xml");
            IObjectFactory factory = new XmlObjectFactory(input);
            //是否包含以某个名称命名的对象
            var isContainsObject = factory.ContainsObject("aaaa");
            //返回以指定名称命名的对象
            var objectA = factory.GetObject <IDao>("dao");
            var objectB = factory.GetObject("dao", typeof(IDao));
            //索引器返回以指定名称命名的对象
            var objectC = factory["dao"] as IDao;
            //是否为单例模式
            var isSingleton = factory.IsSingleton("dao");
            //获取别名
            IList <string> aliases = factory.GetAliases("dao");

            factory.ConfigureObject(new TestInject(), "dao");



            Console.WriteLine("isContainsObject值为{0}", isContainsObject);
            Console.WriteLine("objectA值为{0}", objectA);
            Console.WriteLine("objectB值为{0}", objectB);
            Console.WriteLine("objectC值为{0}", objectC);
            Console.WriteLine("isSingleton值为{0}", isSingleton);
            Console.WriteLine("aliases值为{0}", string.Join(",", aliases));
        }
コード例 #3
0
    public IController CreateController(RequestContext context, Type controllerType)
    {
        IResource      input   = new FileSystemResource(context.HttpContext.Request.MapPath("Resource\\objects.xml"));
        IObjectFactory factory = new XmlObjectFactory(input);

        return((IController)factory.GetObject(controllerType.Name));
    }
コード例 #4
0
        public void EbcdicFileTestTest2()
        {
            // local resources
            IResource fileResource     = new FileSystemResource(new FileInfo("C:/temp/outputs/CustomerWritten.txt"));
            var       executionContext = new ExecutionContext();
            FileInfo  fileInfo         = new FileInfo("Ebcdic/Resources/copybooks/Customer.fileformat");

            IResource copybookResource = new FileSystemResource(fileInfo);

            //1. WRITE
            EbcdicWriterMapper writerMapper = new EbcdicWriterMapper();

            writerMapper.AfterPropertiesSet();

            var writer = new EbcdicFileWriter <Customer>
            {
                AppendAllowed      = false,
                WriteRdw           = false,
                Name               = "CustomerWriter",
                Resource           = fileResource,
                EbcdicWriterMapper = writerMapper,
                DefaultValue       = EbcdicEncoder.DefaultValue.LowValue,
                Copybooks          = new List <IResource> {
                    new FileSystemResource(fileInfo)
                }
            };


            writer.AfterPropertiesSet();
            writer.Open(executionContext);
            writer.Write(GetCustomers());
            writer.Close();

            //2.READ WHAT WAS WRITTEN
            var reader = new EbcdicFileReader <Customer>
            {
                EbcdicReaderMapper = new CustomerEbcdicMapper(),
                Rdw       = false,
                Resource  = fileResource,
                Name      = "CustomerReader",
                SaveState = false,
                Copybook  = copybookResource
            };

            reader.AfterPropertiesSet();

            var customers = new List <Customer>();

            reader.Open(executionContext);
            Customer customer;

            while ((customer = reader.Read()) != null)
            {
                customers.Add(customer);
            }
            reader.Close();

            Assert.AreEqual(CountObject, customers.Count);
        }
コード例 #5
0
        public void TestGetFileInfo2()
        {
            var resource = new FileSystemResource(TestDataDirectory);
            var fileInfo = resource.GetFileInfo();

            Assert.IsNotNull(fileInfo);
            Assert.AreEqual("TestData", fileInfo.Name);
        }
コード例 #6
0
        private void ConfigureIoC()
        {
            IResource      input   = new FileSystemResource(Server.MapPath("objects.xml"));
            IObjectFactory factory = new XmlObjectFactory(input);

            MvcContrib.Services.DependencyResolver.InitializeWith(new SpringDependencyResolver(factory));

            ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));
        }
コード例 #7
0
ファイル: RtmpServer.cs プロジェクト: jfarre20/Ubiquitous
        public RtmpServer(RtmpEndpoint endpoint)
        {
            _connections     = new Hashtable();
            _socketListeners = new ArrayList();
            _endpoint        = endpoint;
            _rtmpHandler     = new RtmpHandler(endpoint);

            try
            {
                if (endpoint.ChannelDefinition.Properties.KeystoreFile != null)
                {
                    FileSystemResource fsr = new FileSystemResource(endpoint.ChannelDefinition.Properties.KeystoreFile);
                    if (fsr.Exists)
                    {
                        if (endpoint.ChannelDefinition.Properties.KeystorePassword != null)
                        {
                            _serverCertificate = new X509Certificate2(fsr.File.FullName, endpoint.ChannelDefinition.Properties.KeystorePassword);
                        }
                        else
                        {
                            _serverCertificate = X509Certificate.CreateFromCertFile(fsr.File.FullName);
                        }
                        log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
                    }
                    else
                    {
                        log.Error("Certificate file not found");
                    }
                }
                else
                {
                    if (endpoint.ChannelDefinition.Properties.ServerCertificate != null)
                    {
                        StoreName     storeName     = (StoreName)Enum.Parse(typeof(StoreName), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreName, false);
                        StoreLocation storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreLocation, false);
                        X509FindType  x509FindType  = (X509FindType)Enum.Parse(typeof(X509FindType), endpoint.ChannelDefinition.Properties.ServerCertificate.X509FindType, false);
                        X509Store     store         = new X509Store(storeName, storeLocation);
                        store.Open(OpenFlags.ReadOnly);
                        X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, endpoint.ChannelDefinition.Properties.ServerCertificate.FindValue, false);
                        X509Certificate2Enumerator enumerator            = certificateCollection.GetEnumerator();
                        if (enumerator.MoveNext())
                        {
                            _serverCertificate = enumerator.Current;
                            log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
                        }
                        else
                        {
                            log.Error("Certificate not found");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Error loading certificate.", ex);
            }
        }
コード例 #8
0
        public void Test_ResolveVariable_Should_Correctly_Resolve_Parent_Property()
        {
            /* Given: the valid json file */
            IResource json = new FileSystemResource("..\\..\\Sample\\Valid\\Config\\sample.json");

            /* When: variable should be resolved */
            string applicationName = new Spring.Objects.Factory.Config.JsonVariableSource(json).ResolveVariable("applicationName");

            /* Then: applicationName should be resolved correctly */
            applicationName.Should().Be("Sample Application");
        }
コード例 #9
0
        public void Test_ResolveVariable_Should_Throw_Exception_When_JSon_Is_Invalid()
        {
            /* Given: the invalid json file */
            IResource json = new FileSystemResource("..\\..\\Sample\\Invalid\\Config\\sample.json");

            /* When: variable should be resolved */
            Action action = () => new Spring.Objects.Factory.Config.JsonVariableSource(json).ResolveVariable("applicationName");

            /* Then: an exception should be thrown */
            action.ShouldThrow <FormatException>();
        }
コード例 #10
0
        public void Test_ResolveVariable_Should_Correctly_Resolve_Child_Property()
        {
            /* Given: the valid json file */
            IResource json = new FileSystemResource("..\\..\\Sample\\Valid\\Config\\sample.json");

            /* When: child variable should be resolved */
            string login = new Spring.Objects.Factory.Config.JsonVariableSource(json).ResolveVariable("credentials.login");

            /* Then: login-name of credentials should be resolved correctly */
            login.Should().Be("username");
        }
コード例 #11
0
        private async void OpenFileProperties(FileViewModel file, FileExplorerViewModel context)
        {
            var properties = await FileSystemResource.GetFileProperties(file.Source.Path, context.RestClient)
                             .DisplayOnStatusBarCatchErrors(context.StatusBar, Tx.T("FileExplorer:StatusBar.LoadProperties"));

            if (!properties.Failed)
            {
                context.Window.Show <PropertiesViewModel>(null, window =>
                {
                    window.Title       = Tx.T("FileExplorer:Properties.Title", "name", file.Name);
                    window.TaskBarIcon = file.Icon;
                }, viewModel => viewModel.Initialize(file, properties.Result, context.RestClient), out var _);
            }
        }
コード例 #12
0
ファイル: RemoteFileSystem.cs プロジェクト: 5l1v3r1/Maze-1
        public async Task CreateDirectory(string path)
        {
            await FileSystemResource.CreateDirectory(path, _restClient);

            var entry = new DirectoryEntry
            {
                CreationTime = DateTimeOffset.Now,
                HasSubFolder = false,
                Name         = Path.GetFileName(path),
                Path         = path
            };

            UploadCompleted(entry);
        }
コード例 #13
0
        /// <summary>
        /// Registers the artifacts required to execute the steps (tasklets, readers, writers, etc.)
        /// </summary>
        /// <param name="container">the unity container to use for registrations</param>
        public override void LoadArtifacts(IUnityContainer container)
        {
            //Connection string using relative path
            string path   = Directory.GetCurrentDirectory();
            var    config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var    connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

            connectionStringsSection.ConnectionStrings["Default"].ConnectionString = connectionStringsSection.ConnectionStrings["Default"].ConnectionString.Replace("%DataDirectory%", path);
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
            var writerConnectionstring = ConfigurationManager.ConnectionStrings["Default"];

            //input file
            var inputFileResource = new FileSystemResource("data/input/FlatFile.txt");

            // Reader - FlatFileReader/FlatFileReader
            container.StepScopeRegistration <IItemReader <FlatFileRecord>, FlatFileItemReader <FlatFileRecord> >("FlatFileReader/FlatFileReader")
            .Property("Resource").Value(inputFileResource)
            .Property("Encoding").Value(Encoding.GetEncoding("UTF-8"))
            .Property("LineMapper")
            .Reference <ILineMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/LineMapper")
            .Register();

            // Line mapper
            container.StepScopeRegistration <ILineMapper <FlatFileRecord>, DefaultLineMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/LineMapper")
            .Property("Tokenizer")
            .Reference <ILineTokenizer>("FlatFileReader/FlatFileReader/Tokenizer")
            .Property("FieldSetMapper")
            .Reference <IFieldSetMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/FieldSetMapper")
            .Register();

            // Tokenizer
            container.StepScopeRegistration <ILineTokenizer, DelimitedLineTokenizer>("FlatFileReader/FlatFileReader/Tokenizer")
            .Property("Delimiter").Value(";")
            .Register();

            // Field set mapper
            container.RegisterStepScope <IFieldSetMapper <FlatFileRecord>, FlatFileRecordMapper>("FlatFileReader/FlatFileReader/FieldSetMapper");

            // Processor - FlatFileReader/Processor
            container.RegisterStepScope <IItemProcessor <FlatFileRecord, FlatFileRecord>, FlatFileRecordProcessor>("FlatFileReader/Processor");

            // Writer - FlatFileReader/DatabaseWriter
            container.StepScopeRegistration <IItemWriter <FlatFileRecord>, DatabaseBatchItemWriter <FlatFileRecord> >("FlatFileReader/DatabaseWriter")
            .Property("ConnectionString").Instance(writerConnectionstring)
            .Property("Query").Value("INSERT INTO BA_FLATFILE_READER_TABLE (CODE,NAME,DESCRIPTION,DATE)" + " VALUES (:code,:name,:description,:date)")
            .Property("DbParameterSourceProvider").Reference <PropertyParameterSourceProvider <FlatFileRecord> >()
            .Register();
        }
コード例 #14
0
ファイル: RemoteFileSystem.cs プロジェクト: 5l1v3r1/Maze-1
        public async Task <IEnumerable <DirectoryEntry> > FetchSubDirectories(DirectoryEntry directoryEntry, bool ignoreCache)
        {
            if (!ignoreCache && TryGetCachedDirectory(directoryEntry.Path, out var cachedDirectory))
            {
                return(cachedDirectory.Entries.OfType <DirectoryEntry>());
            }

            var directories = await FileSystemResource.QueryDirectories(directoryEntry.Path, _restClient);

            foreach (var subDirectory in directories)
            {
                subDirectory.Migrate(directoryEntry);
            }

            AddToCache(directoryEntry, directories, true);
            return(directories);
        }
コード例 #15
0
        /// <summary>
        ///     Ctor.
        /// </summary>
        /// <param name="location">location of the json-file.</param>
        public JsonVariableSource(IResource location)
        {
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }

            Location   = location;
            _variables = LoadJson(Location);

            if (CanResolveVariable("$schema"))
            {
                string    schemaLocation = ResolveVariable("$schema");
                IResource schemaResource = new FileSystemResource(Location.File.Directory.FullName + "\\" + schemaLocation);
                ValidateResource(_variables, schemaResource);
            }
        }
コード例 #16
0
        public void FlatFileTestRestart()
        {
            System.IO.File.Copy("TestData/FlatFile/output/Test.txt", _testpath3, true);
            IResource fileResource = new FileSystemResource(new FileInfo(_testpath3));

            Assert.IsTrue(fileResource.Exists());

            var writer = new FlatFileItemWriter <Person>
            {
                Resource       = new FileSystemResource(_testpath3),
                LineAggregator = new LineAggregator(),
                HeaderWriter   = new HeaderWriter()
            };
            var reader = new FlatFileItemReader <Person>
            {
                Resource    = new FileSystemResource(_testpath3),
                LinesToSkip = 2,
                LineMapper  = new LineMapper()
            };

            var executionContext = new ExecutionContext();

            executionContext.PutLong("FlatFileItemWriter.current.count", 133L); // Last position in Test.txt
            executionContext.PutLong("FlatFileItemWriter.written", 10L);        // Record already written in Test.txt

            writer.Open(executionContext);
            writer.Write(GetPersons());
            writer.Close();

            Assert.IsTrue(System.IO.File.Exists(_testpath3));
            Assert.IsTrue(new FileInfo(_testpath3).Length > 0);

            var persons = new List <Person>();

            reader.Open(executionContext);
            Person person;

            while ((person = reader.Read()) != null)
            {
                persons.Add(person);
            }
            reader.Close();

            Assert.AreEqual(CountObjects + 10, persons.Count); // The final record number must be 20+10.
        }
コード例 #17
0
ファイル: RemoteFileSystem.cs プロジェクト: 5l1v3r1/Maze-1
        public async Task Move(FileExplorerEntry entry, string path)
        {
            path = NormalizePath(path);

            if (entry.Type == FileExplorerEntryType.File)
            {
                await FileSystemResource.MoveFile(entry.Path, path, _restClient);
            }
            else
            {
                await FileSystemResource.MoveDirectory(entry.Path, path, _restClient);
            }

            var oldPath = NormalizePath(entry.Path);

            entry.Path = path;
            entry.Name = Path.GetFileName(path);

            EntryUpdated?.Invoke(this, new EntryUpdatedEventArgs(entry, oldPath));

            if (entry.Type != FileExplorerEntryType.File)
            {
                foreach (var cachedEntry in _localCache.Where(x => x.Key.StartsWith(oldPath, PathStringComparison)))
                {
                    _localCache.TryRemove(cachedEntry.Key, out _);
                    var newPath = path + cachedEntry.Key.Substring(oldPath.Length);
                    cachedEntry.Value.Directory.Path = newPath;

                    lock (cachedEntry.Value.EntriesLock)
                    {
                        foreach (var fileExplorerEntry in cachedEntry.Value.Entries)
                        {
                            fileExplorerEntry.Path = path + fileExplorerEntry.Path.Substring(oldPath.Length);
                        }
                    }

                    _localCache[newPath] = cachedEntry.Value;
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Registers the artifacts required to execute the steps (tasklets, readers, writers, etc.)
        /// </summary>
        /// <param name="container">the unity container to use for registrations</param>
        public override void LoadArtifacts(IUnityContainer container)
        {
            //Connection string
            var writerConnectionstring = ConfigurationManager.ConnectionStrings["Default"];

            //input file
            var inputFileResource = new FileSystemResource("data/input/LargeFlatFile.txt");

            // Reader - FlatFileReader/FlatFileReader
            container.StepScopeRegistration <IItemReader <FlatFileRecord>, FlatFileItemReader <FlatFileRecord> >("FlatFileReader/FlatFileReader")
            .Property("Resource").Value(inputFileResource)
            .Property("Encoding").Value(Encoding.GetEncoding("UTF-8"))
            .Property("LineMapper").Reference <ILineMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/LineMapper")
            .Register();

            // Line mapper
            container.StepScopeRegistration <ILineMapper <FlatFileRecord>, DefaultLineMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/LineMapper")
            .Property("Tokenizer").Reference <ILineTokenizer>("FlatFileReader/FlatFileReader/Tokenizer")
            .Property("FieldSetMapper").Reference <IFieldSetMapper <FlatFileRecord> >("FlatFileReader/FlatFileReader/FieldSetMapper")
            .Register();

            // Tokenizer
            container.StepScopeRegistration <ILineTokenizer, DelimitedLineTokenizer>("FlatFileReader/FlatFileReader/Tokenizer")
            .Property("Delimiter").Value(";")
            .Register();

            // Field set mapper
            container.RegisterStepScope <IFieldSetMapper <FlatFileRecord>, FlatFileRecordMapper>("FlatFileReader/FlatFileReader/FieldSetMapper");

            // Processor - FlatFileReader/Processor
            container.RegisterStepScope <IItemProcessor <FlatFileRecord, FlatFileRecord>, FlatFileRecordProcessor>("FlatFileReader/Processor");

            // Writer - FlatFileReader/DatabaseWriter
            container.StepScopeRegistration <IItemWriter <FlatFileRecord>, DatabaseBatchItemWriter <FlatFileRecord> >("FlatFileReader/DatabaseWriter")
            .Property("ConnectionString").Instance(writerConnectionstring)
            .Property("Query").Value("INSERT INTO BA_FLATFILE_READER_TABLE (CODE,NAME,DESCRIPTION,DATE) VALUES (:code,:name,:description,:date)")
            .Property("DbParameterSourceProvider").Reference <PropertyParameterSourceProvider <FlatFileRecord> >()
            .Register();
        }
コード例 #19
0
        /// <summary>
        /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="configFolderPaths">Possible configuration file locations.</param>
        /// <param name="serviceBrowserAvailable">Indicates whether the service browser is avaliable.</param>
        public void Init(string[] configFolderPaths, bool serviceBrowserAvailable)
        {
            _messageBroker = new MessageBroker(this);

            string servicesConfigFile = null;

            for (int i = 0; i < configFolderPaths.Length; i++)
            {
                servicesConfigFile = Path.Combine(configFolderPaths[i], "services-config.xml");
                if (log.IsDebugEnabled)
                {
                    log.Debug(__Res.GetString(__Res.MessageServer_TryingServiceConfig, servicesConfigFile));
                }
                if (File.Exists(servicesConfigFile))
                {
                    break;
                }
            }
            if (servicesConfigFile != null && File.Exists(servicesConfigFile))
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug(__Res.GetString(__Res.MessageServer_LoadingServiceConfig, servicesConfigFile));
                }
                _servicesConfiguration = ServicesConfiguration.Load(servicesConfigFile);
            }
            else
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug(__Res.GetString(__Res.MessageServer_LoadingConfigDefault));
                }
                _servicesConfiguration = ServicesConfiguration.CreateDefault();
            }

            foreach (ChannelDefinition channelDefinition in _servicesConfiguration.Channels)
            {
                Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(channelDefinition.Endpoint.Class));
                if (type != null)
                {
                    IEndpoint endpoint = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, channelDefinition }) as IEndpoint;
                    if (endpoint != null)
                    {
                        _messageBroker.AddEndpoint(endpoint);
                    }
                }
                else
                {
                    log.Error(__Res.GetString(__Res.Type_InitError, channelDefinition.Class));
                }
            }
            ChannelDefinition rtmptChannelDefinition = new ChannelDefinition();

            rtmptChannelDefinition.Id = RtmptEndpoint.FluorineRtmptEndpointId;
            IEndpoint rtmptEndpoint = new RtmptEndpoint(_messageBroker, rtmptChannelDefinition);

            _messageBroker.AddEndpoint(rtmptEndpoint);

            if (_servicesConfiguration.Factories != null)
            {
                foreach (Factory factory in _servicesConfiguration.Factories)
                {
                    Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(factory.Class));
                    if (type != null)
                    {
                        IFlexFactory flexFactory = ObjectFactory.CreateInstance(type, new object[0]) as IFlexFactory;
                        if (flexFactory != null)
                        {
                            _messageBroker.AddFactory(factory.Id, flexFactory);
                        }
                    }
                    else
                    {
                        log.Error(__Res.GetString(__Res.Type_InitError, factory.Class));
                    }
                }
            }
            //Add the dotnet Factory
            _messageBroker.AddFactory(DotNetFactory.Id, new DotNetFactory());

            if (serviceBrowserAvailable)
            {
                ServiceDefinition serviceConfiguration = _servicesConfiguration.GetServiceByClass("flex.messaging.services.RemotingService");
                if (serviceConfiguration != null)
                {
                    AdapterDefinition adapter = serviceConfiguration.GetAdapterByClass(typeof(Remoting.RemotingAdapter).FullName);
                    if (adapter != null)
                    {
                        InstallServiceBrowserDestinations(serviceConfiguration, adapter);
                    }
                    else
                    {
                        adapter = serviceConfiguration.GetDefaultAdapter();
                        if (adapter != null)
                        {
                            InstallServiceBrowserDestinations(serviceConfiguration, adapter);
                        }
                    }
                }
            }
            if (_servicesConfiguration.Services.ServiceDefinitions != null)
            {
                foreach (ServiceDefinition serviceDefinition in _servicesConfiguration.Services.ServiceDefinitions)
                {
                    Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(serviceDefinition.Class));//current assembly only
                    if (type != null)
                    {
                        IService service = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, serviceDefinition }) as IService;
                        if (service != null)
                        {
                            _messageBroker.AddService(service);
                        }
                    }
                    else
                    {
                        log.Error(__Res.GetString(__Res.Type_InitError, serviceDefinition.Class));
                    }
                }
            }
            if (_servicesConfiguration.Services.Includes != null)
            {
                foreach (ServiceInclude include in _servicesConfiguration.Services.Includes)
                {
                    ServiceDefinition serviceDefinition = include.ServiceDefinition;
                    Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(serviceDefinition.Class));//current assembly only
                    if (type != null)
                    {
                        IService service = ObjectFactory.CreateInstance(type, new object[] { _messageBroker, serviceDefinition }) as IService;
                        if (service != null)
                        {
                            _messageBroker.AddService(service);
                        }
                    }
                    else
                    {
                        log.Error(__Res.GetString(__Res.Type_InitError, serviceDefinition.Class));
                    }
                }
            }
            if (_servicesConfiguration.Security != null)
            {
                if (_servicesConfiguration.Security.LoginCommands != null && _servicesConfiguration.Security.LoginCommands.Length > 0)
                {
                    LoginCommand loginCommand = _servicesConfiguration.Security.GetLoginCommand(LoginCommand.FluorineLoginCommand);
                    if (loginCommand != null)
                    {
                        Type type = ObjectFactory.Locate(FluorineConfiguration.Instance.ClassMappings.GetType(loginCommand.Class));
                        if (type != null)
                        {
                            ILoginCommand loginCommandObj = ObjectFactory.CreateInstance(type, new object[] { }) as ILoginCommand;
                            _messageBroker.LoginManager.LoginCommand = loginCommandObj;
                            _messageBroker.LoginManager.IsPerClientAuthentication = loginCommand.IsPerClientAuthentication;
                        }
                        else
                        {
                            log.Error(__Res.GetString(__Res.Type_InitError, loginCommand.Class));
                        }
                    }
                    else
                    {
                        log.Error(__Res.GetString(__Res.Type_InitError, "<<LoginCommand class>>"));
                    }
                }
            }
            InitAuthenticationService();

            try
            {
                if (FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings != null &&
                    FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.Enable)
                {
                    IResource resource;
                    if (FluorineContext.Current != null)
                    {
                        resource = FluorineContext.Current.GetResource(FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile);
                    }
                    else
                    {
                        resource = new FileSystemResource(FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile);
                    }
                    if (resource.Exists)
                    {
                        log.Info(__Res.GetString(__Res.Silverlight_StartPS, resource.File.FullName));
                        _policyServer = new PolicyServer(resource.File.FullName);
                    }
                    else
                    {
                        throw new FileNotFoundException("Policy file not found", FluorineConfiguration.Instance.FluorineSettings.Silverlight.PolicyServerSettings.PolicyFile);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(__Res.GetString(__Res.Silverlight_PSError), ex);
            }
        }
コード例 #20
0
        public void EbcdicFileTestTransactionalWrite()
        {
            // local resources
            IResource fileResource     = new FileSystemResource(new FileInfo("C:/temp/outputs/PersonWritten.txt"));
            var       executionContext = new ExecutionContext();
            FileInfo  fileInfo         = new FileInfo("Ebcdic/Resources/copybooks/Person.fileformat");

            IResource copybookResource = new FileSystemResource(fileInfo);

            //1. WRITE
            EbcdicWriterMapper writerMapper = new EbcdicWriterMapper();

            writerMapper.AfterPropertiesSet();

            var writer = new EbcdicFileWriter <Ebcdic.Test.Person>
            {
                AppendAllowed      = false,
                WriteRdw           = false,
                Name               = "PersonWriter",
                Resource           = fileResource,
                EbcdicWriterMapper = writerMapper,
                DefaultValue       = EbcdicEncoder.DefaultValue.LowValue,
                Copybooks          = new List <IResource> {
                    new FileSystemResource(fileInfo)
                }
            };

            writer.AfterPropertiesSet();
            writer.Open(executionContext);

            try
            {
                for (int i = 0; i < CountTransactions; i++)
                {
                    using (TransactionScope scope = TransactionScopeManager.CreateScope())
                    {
                        writer.Write(GetPersons(i));
                        if (i == CountTransactions - 1) //SIMULATE FAILURE
                        {
                            throw new Exception("Bailing out ... should rollback ...");
                        }
                        scope.Complete();
                    }
                }
            }
            catch (Exception)
            {
                // DISCARDED (JUST TO AVOID UNIT TEST FAILURE ...)
            }
            writer.Close();

            Assert.IsTrue(System.IO.File.Exists("C:/temp/outputs/PersonWritten.txt"));
            Assert.IsTrue(new FileInfo("C:/temp/outputs/PersonWritten.txt").Length > 0);

            //2.READ WHAT WAS WRITTEN
            var reader = new EbcdicFileReader <Ebcdic.Test.Person>
            {
                EbcdicReaderMapper = new PersonMapper(),
                Rdw       = false,
                Resource  = fileResource,
                Name      = "PersonReader",
                SaveState = false,
                Copybook  = copybookResource
            };

            reader.AfterPropertiesSet();

            var persons = new List <Ebcdic.Test.Person>();

            reader.Open(executionContext);
            Ebcdic.Test.Person person;
            while ((person = reader.Read()) != null)
            {
                persons.Add(person);
            }
            reader.Close();

            Assert.AreEqual(CountObject * (CountTransactions - 1), persons.Count);
            foreach (Ebcdic.Test.Person p in persons)
            {
                Assert.AreEqual(p.Id, p.Value);
                Assert.IsTrue(p.Name.StartsWith("Name_" + p.Id));
            }
        }
コード例 #21
0
        public void TestExists2()
        {
            var resource = new FileSystemResource(Path.Combine(TestDataDirectory, "NonExistingFile"));

            Assert.IsFalse(resource.Exists());
        }
コード例 #22
0
        public void EbcdicFileTestRestart()
        {
            // local resources
            System.IO.File.Copy("Ebcdic/Resources/outputs/simple.txt", "C:/temp/outputs/SimpleWritten.txt", true);
            IResource fileResource     = new FileSystemResource(new FileInfo("C:/temp/outputs/SimpleWritten.txt"));
            var       executionContext = new ExecutionContext();

            executionContext.PutLong("EbcdicFileWriter.current.count", 21L);
            executionContext.PutLong("EbcdicFileWriter.written", 1L);
            FileInfo fileInfo = new FileInfo("Ebcdic/Resources/copybooks/simple.fileformat");

            IResource copybookResource = new FileSystemResource(fileInfo);

            //1. WRITE
            EbcdicWriterMapper writerMapper = new EbcdicWriterMapper();

            writerMapper.AfterPropertiesSet();

            var writer = new EbcdicFileWriter <Simple>
            {
                AppendAllowed      = false,
                WriteRdw           = false,
                Resource           = fileResource,
                EbcdicWriterMapper = writerMapper,
                DefaultValue       = EbcdicEncoder.DefaultValue.LowValue,
                DeleteIfExist      = true
            };


            var mySimple = new Simple()
            {
                LongValue = 12, FloatValue = 12.5f, Date = DateTime.Now, BooleanValue = true
            };
            List <Simple> simpleList = new List <Simple> {
                mySimple
            };

            writer.Copybooks = new List <IResource> {
                new FileSystemResource(fileInfo)
            };

            writer.AfterPropertiesSet();
            writer.Open(executionContext);
            writer.Write(simpleList);
            writer.Close();

            //2.READ WHAT WAS WRITTEN
            var reader = new EbcdicFileReader <Simple>
            {
                EbcdicReaderMapper = new SimpleEbcdicMapper(),
                Rdw       = false,
                Resource  = fileResource,
                Name      = "PersonReader",
                SaveState = false,
                Copybook  = copybookResource
            };

            reader.AfterPropertiesSet();

            var simples = new List <Simple>();

            reader.Open(executionContext);
            Simple simple;

            while ((simple = reader.Read()) != null)
            {
                simples.Add(simple);
            }
            reader.Close();

            /*foreach (Ebcdic.Test.Person p in simple)
             * {
             *  Assert.AreEqual(p.Id, p.Value);
             *  Assert.IsTrue(p.Name.StartsWith("Name_" + p.Id));
             * }*/
        }
コード例 #23
0
        public void EbcdicFileTestTest()
        {
            // local resources
            IResource fileResource     = new FileSystemResource(new FileInfo("C:/temp/outputs/PersonWritten.txt"));
            var       executionContext = new ExecutionContext();
            FileInfo  fileInfo         = new FileInfo("Ebcdic/Resources/copybooks/Person.fileformat");

            IResource copybookResource = new FileSystemResource(fileInfo);

            //1. WRITE
            EbcdicWriterMapper writerMapper = new EbcdicWriterMapper();

            writerMapper.AfterPropertiesSet();

            var writer = new EbcdicFileWriter <Ebcdic.Test.Person>
            {
                AppendAllowed      = false,
                WriteRdw           = false,
                Name               = "PersonWriter",
                Resource           = fileResource,
                EbcdicWriterMapper = writerMapper,
                DefaultValue       = EbcdicEncoder.DefaultValue.LowValue,
                Copybooks          = new List <IResource> {
                    new FileSystemResource(fileInfo)
                }
            };


            writer.AfterPropertiesSet();
            writer.Open(executionContext);
            writer.Write(GetPersons());
            writer.Close();

            //2.READ WHAT WAS WRITTEN
            var reader = new EbcdicFileReader <Ebcdic.Test.Person>
            {
                EbcdicReaderMapper = new PersonMapper(),
                Rdw       = false,
                Resource  = fileResource,
                Name      = "PersonReader",
                SaveState = false,
                Copybook  = copybookResource
            };

            reader.AfterPropertiesSet();

            var persons = new List <Ebcdic.Test.Person>();

            reader.Open(executionContext);
            Ebcdic.Test.Person person;
            while ((person = reader.Read()) != null)
            {
                persons.Add(person);
            }
            reader.Close();

            Assert.AreEqual(CountObject, persons.Count);
            foreach (Ebcdic.Test.Person p in persons)
            {
                Assert.AreEqual(p.Id, p.Value);
                Assert.IsTrue(p.Name.StartsWith("Name_" + p.Id));
            }
        }
        private string ResolvePath(FrontendCompiler context, FileSystemResource r)
        {
            if (String.IsNullOrEmpty(r.Path))
            {
                // If there is a parent folder resolve it's path.
                string parentPath = String.Empty;
                if (r.ParentFolder != null)
                {
                    parentPath = ResolvePath(context, r.ParentFolder); // recurse.
                }

                string path = IO.Path.Combine(parentPath, r.ParentRelativePathFromName ?? String.Empty, r.Name ?? String.Empty);
                Debug.Assert((r is Folder && path.EndsWith("\\", StringComparison.Ordinal)) || (r is File && !path.EndsWith("\\", StringComparison.Ordinal)));

                r.SetPath(path);
            }

            // If in the process of calculating this resource's path we reparented the folder (which deletes the
            // resource) then don't check for a conflicting resource because this resource would lose anyway.
            if (!r.Deleted)
            {
                Resource conflictingResource;
                if (this.resolvedPaths.TryGetValue(r.Path, out conflictingResource))
                {
                    if (conflictingResource == r)
                    {
                        // We found ourself so don't do anything.
                    }
                    else if (conflictingResource is Folder && r is Folder) // folders are special because the can be implicitly created.
                    {
                        // If our resource has an id that makes it a better candidate for the path.
                        if (!String.IsNullOrEmpty(r.Id))
                        {
                            // The conflicting resource cannot also have an Id or the backend compiler will be all confusimicated.
                            if (!String.IsNullOrEmpty(conflictingResource.Id))
                            {
                                // TODO: change this to an error message instead of an internal compiler error.
                                CompilerException.ThrowInternalError("Two named folders refer to the same path. That is not supported.");
                            }

                            this.ReparentFolderChildren(context, (Folder)conflictingResource, (Folder)r);

                            this.resolvedPaths[r.Path] = r; // this resource now owns the path.
                        }
                        else // the conflicting resource either has an Id or was here first so it's a better parent.
                        {
                            this.ReparentFolderChildren(context, (Folder)r, (Folder)conflictingResource);
                        }
                    }
                    else
                    {
                        // TODO: change this to an error message instead of an internal compiler error.
                        CompilerException.ThrowInternalError("Two files or a file and a folder ended up with the same path. That is not allowed.");
                    }
                }
                else // no one owns this path yet so take it over.
                {
                    Debug.Assert(r != r.ParentFolder);
                    this.resolvedPaths.Add(r.Path, r);
                }
            }

            return(r.Path);
        }
コード例 #25
0
ファイル: RemoteFileSystem.cs プロジェクト: 5l1v3r1/Maze-1
        public async Task <PathContent> FetchPath(string path, bool ignoreEntriesCache, bool ignorePathCache,
                                                  CancellationToken token)
        {
            if (PathHelper.ContainsEnvironmentVariables(path))
            {
                path = await FileSystemResource.ExpandEnvironmentVariables(path, _restClient);
            }

            path = NormalizePath(path);
            var request = new PathTreeRequestDto {
                Path = path, RequestedDirectories = new List <int>()
            };

            if (ignoreEntriesCache || !TryGetCachedDirectory(path, out var cachedDirectory) ||
                cachedDirectory.DirectoriesOnly)
            {
                request.RequestEntries = true;
            }

            var parts = PathHelper.GetPathDirectories(path).ToList();

            for (var i = 0; i < parts.Count; i++)
            {
                var partPath = parts[i];

                if (ignorePathCache || !TryGetCachedDirectory(partPath, out _))
                {
                    request.RequestedDirectories.Add(i);
                }
            }

            PathTreeResponseDto queryResponse = null;

            if (request.RequestEntries || request.RequestedDirectories.Any())
            {
                queryResponse = await FileExplorerResource.GetPathTree(request,
                                                                       DirectoryHelper.IsComputerDirectory(path), token, _restClient);
            }

            parts.Add(path);

            DirectoryEntry directory       = null;
            var            pathDirectories = new List <DirectoryEntry>();
            IReadOnlyList <FileExplorerEntry> directoryEntries = null;

            for (var i = 0; i < parts.Count; i++)
            {
                var directoryPath = parts[i];

                if (directory == null)
                {
                    if (TryGetCachedDirectory(directoryPath, out cachedDirectory))
                    {
                        directory = cachedDirectory.Directory;
                    }
                    else
                    {
                        directory = _computerDirectory.Entries.OfType <DirectoryEntry>()
                                    .FirstOrDefault(x => string.Equals(x.Path, directoryPath, PathStringComparison));
                    }
                }

                if (directory == null) //Special folders like trash can etc.
                {
                    directory = await FileSystemResource.GetDirectoryEntry(directoryPath, _restClient);

                    directory.Migrate();
                }

                if (request.RequestEntries && i == parts.Count - 1)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    directoryEntries = queryResponse.Entries;
                    foreach (var entry in directoryEntries)
                    {
                        entry.Migrate(directory);
                    }

                    AddToCache(directory, directoryEntries, false);
                }
                else if (queryResponse?.Directories != null && queryResponse.Directories.TryGetValue(i, out var subDirectories))
                {
                    directoryEntries = subDirectories;

                    foreach (var directoryEntry in directoryEntries)
                    {
                        directoryEntry.Migrate(directory);
                    }

                    AddToCache(directory, directoryEntries, true);
                }
                else
                {
                    directoryEntries = _localCache[NormalizePath(directoryPath)].Entries.ToList();
                }

                pathDirectories.Add(directory);

                //if we are not at the very last part (so there is a child directory)
                if (i < parts.Count - 1)
                {
                    var normalizedPath = NormalizePath(parts[i + 1]); //path of the child directory
                    var nextDirectory  = directoryEntries.OfType <DirectoryEntry>().FirstOrDefault(x =>
                                                                                                   string.Equals(normalizedPath, NormalizePath(x.Path), PathStringComparison));

                    if (nextDirectory == null)
                    {
                        nextDirectory = new DirectoryEntry
                        {
                            HasSubFolder = true,
                            Parent       = directory,
                            Name         = GetDirectoryName(normalizedPath)
                        };
                        directoryEntries = directoryEntries.Concat(new[] { nextDirectory }).ToList();

                        //update cache
                        var key      = NormalizePath(directoryPath);
                        var oldCache = _localCache[key];
                        _localCache[key] = new CachedDirectory(oldCache.Directory, oldCache.DirectoriesOnly,
                                                               directoryEntries);
                    }

                    directory = nextDirectory;
                }
            }

            return(new PathContent(directory, directoryEntries, pathDirectories));
        }