Inheritance: CommandBase
コード例 #1
0
        public async Task SaveAsync_ShouldDetermineContentTypeFromExtensionIfNotProvided()
        {
            var _mimeMapping = new Mock <IMimeMapping>();

            _mimeMapping.Setup(x => x.GetMimeType(It.IsAny <string>())).Returns("text/plain");

            GlobalConfiguration.Instance.SetMimeMapping(_mimeMapping.Object);

            var            stream  = new MemoryStream();
            var            result  = "Test/test.txt";
            StorageCommand command = new StorageCommand()
            {
                FileName = "test.txt",
                Folder   = "Test"
            };

            command.SetStreamSource(stream, "txt");
            _remoteStorage.Setup(x => x.SaveAsync(It.IsAny <Stream>(), result, "text/plain"))
            .Returns(Task <string> .FromResult <string>(result))
            .Verifiable();

            var res = await _fixture.SaveAsync(command);

            _remoteStorage.Verify();
            Assert.Equal(result, res);
        }
コード例 #2
0
        private void CreateStorageCommand(Opcode cmdType, bool noreply)
        {
            int  offset = 0;
            uint flags  = 0;
            long exp    = 0;

            switch (cmdType)
            {
            case Opcode.Append:
            case Opcode.Prepend:
            case Opcode.AppendQ:
            case Opcode.PrependQ:
                break;

            default:
                flags   = MemcachedEncoding.BinaryConverter.ToUInt32(_rawData, offset);
                exp     = (long)MemcachedEncoding.BinaryConverter.ToInt32(_rawData, offset + 4);;
                offset += 8;
                break;
            }
            string key = MemcachedEncoding.BinaryConverter.GetString(_rawData, offset, _requestHeader.KeyLength);

            byte[] value = new byte[_requestHeader.ValueLength];
            Buffer.BlockCopy(_rawData, _requestHeader.KeyLength + offset, value, 0, _requestHeader.ValueLength);
            StorageCommand cmd = new StorageCommand(cmdType, key, flags, exp, _requestHeader.CAS, _requestHeader.ValueLength);

            cmd.DataBlock = value;
            cmd.NoReply   = noreply;
            cmd.Opaque    = _requestHeader.Opaque;
            _command      = cmd;
        }
コード例 #3
0
ファイル: LogTruncationTest.cs プロジェクト: Neo4Net/Neo4Net
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertHandlesLogTruncation(org.neo4j.kernel.impl.transaction.command.Command cmd) throws java.io.IOException
        private void AssertHandlesLogTruncation(Command cmd)
        {
            _inMemoryChannel.reset();
            _writer.serialize(new PhysicalTransactionRepresentation(singletonList(cmd)));
            int bytesSuccessfullyWritten = _inMemoryChannel.writerPosition();

            try
            {
                LogEntry       logEntry = _logEntryReader.readLogEntry(_inMemoryChannel);
                StorageCommand command  = (( LogEntryCommand )logEntry).Command;
                assertEquals(cmd, command);
            }
            catch (Exception e)
            {
                throw new AssertionError("Failed to deserialize " + cmd.ToString() + ", because: ", e);
            }
            bytesSuccessfullyWritten--;
            while (bytesSuccessfullyWritten-- > 0)
            {
                _inMemoryChannel.reset();
                _writer.serialize(new PhysicalTransactionRepresentation(singletonList(cmd)));
                _inMemoryChannel.truncateTo(bytesSuccessfullyWritten);
                LogEntry deserialized = _logEntryReader.readLogEntry(_inMemoryChannel);
                assertNull("Deserialization did not detect log truncation!" + "Record: " + cmd + ", deserialized: " + deserialized, deserialized);
            }
        }
コード例 #4
0
        static async Task Main(string[] args)
        {
            var logger               = _container.GetService <ILogger <Program> >();
            var consolePrinter       = _container.GetService <IConsolePrinter>();
            var controller           = _container.GetService <IController>();
            var mediator             = _container.GetService <IMediator>();
            var consoleFlagParser    = new ConsoleFlagParser();
            var consoleCommandParser = new ConsoleCommandParser(consoleFlagParser);

            try
            {
                await mediator.Send(new InitializeStorageCommand());

                var argsFlags   = consoleFlagParser.Parse(args);
                var credentials = GetCredentials(argsFlags);
                var isAuthQuery = new IsAuthenticatedQuery(credentials.Login, credentials.Password);

                if (!(await mediator.Send(isAuthQuery)))
                {
                    throw new ArgumentException("Incorrect login or password");
                }
                consolePrinter.PrintAuthenticationSuccessful();

                var command = new StorageCommand();
                while (command.CommandType != StorageCommands.Exit)
                {
                    try
                    {
                        command = GetCommand(consoleCommandParser, consolePrinter);
                        await controller.ExecuteConsoleCommand(command);
                    }
                    catch (AggregateException agEx)
                    {
                        foreach (var innerEx in agEx.InnerExceptions)
                        {
                            string logMessage = ConvertingHelper.GetLogMessage(innerEx.Message, innerEx.StackTrace);
                            logger.LogError(logMessage);
                            consolePrinter.PrintErrorMessage(innerEx.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        string logMessage = ConvertingHelper.GetLogMessage(ex.Message, ex.StackTrace);
                        logger.LogError(logMessage);
                        consolePrinter.PrintErrorMessage(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                string logMessage = ConvertingHelper.GetLogMessage(ex.Message, ex.StackTrace);
                logger.LogError(logMessage);
                consolePrinter.PrintErrorMessage(ex.Message);
                Environment.Exit(-1);
            }
        }
コード例 #5
0
        private void CreateStorageCommand(string arguments, Opcode cmdType)
        {
            if (arguments == null)
            {
                CreateInvalidCommand();
                return;
            }

            string[] argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (argumentsArray.Length < 4 || argumentsArray.Length > 6)
            {
                CreateInvalidCommand("CLIENT_ERROR bad command line format");
                return;
            }
            else
            {
                try
                {
                    string key     = argumentsArray[0];
                    uint   flags   = UInt32.Parse(argumentsArray[1]);
                    long   expTime = long.Parse(argumentsArray[2]);
                    int    bytes   = int.Parse(argumentsArray[3]);

                    if (cmdType == Opcode.CAS)
                    {
                        ulong casUnique = ulong.Parse(argumentsArray[4]);
                        _command = new StorageCommand(cmdType, key, flags, expTime, casUnique, bytes);
                        if (argumentsArray.Length > 5 && argumentsArray[5] == "noreply")
                        {
                            _command.NoReply = true;
                        }
                    }
                    else
                    {
                        _command = new StorageCommand(cmdType, key, flags, expTime, bytes);
                        if (argumentsArray.Length > 4 && argumentsArray[4] == "noreply")
                        {
                            _command.NoReply = true;
                        }
                    }

                    this.State = ParserState.WaitingForData;
                }
                catch (Exception e)
                {
                    CreateInvalidCommand("CLIENT_ERROR bad command line format");
                    return;
                }
            }
        }
コード例 #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: void write(org.neo4j.storageengine.api.WritableChannel channel) throws java.io.IOException
            internal virtual void Write(WritableChannel channel)
            {
                NextJob.accept(channel);
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                if (Commands.hasNext())
                {
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                    StorageCommand storageCommand = Commands.next();
                    NextJob = c => (new StorageCommandSerializer(c)).visit(storageCommand);
                }
                else
                {
                    NextJob = null;
                }
            }
コード例 #7
0
        public void Build(byte[] data)
        {
            StorageCommand command = (StorageCommand)_command;

            if ((char)data[command.DataSize] != '\r' || (char)data[command.DataSize + 1] != '\n')
            {
                command.ErrorMessage = "CLIENT_ERROR bad data chunk";
            }
            else
            {
                byte[] dataToStore = new byte[command.DataSize];
                Buffer.BlockCopy(data, 0, dataToStore, 0, command.DataSize);
                command.DataBlock = (object)dataToStore;
            }
            this.State = ParserState.ReadyToDispatch;
        }
コード例 #8
0
        public static async Task TestSendBehavior <T>(string expectedVerb, StorageCommand <T> command)
        {
            var mockSocket = new MockSocket();
            await command.SendRequest(mockSocket);

            using (var stream = mockSocket.GetSentData())
            {
                // validate the command line
                var commandLine = stream.ReadLine();
                Assert.IsNotNull(commandLine);
                var parts = commandLine.Split(' ');
                Assert.AreEqual(5, parts.Length);
                Assert.AreEqual(command.Verb, parts[0]);
                Assert.AreEqual(command.Key, parts[1]);
                if (command.Options == null)
                {
                    Assert.AreEqual("0", parts[2]);
                    Assert.AreEqual("0", parts[3]);
                }
                else
                {
                    Assert.AreEqual(command.Options.Flags.ToString(), parts[2]);
                    var expectedExpires = command.Options.ExpirationTime.HasValue
                        ? ((uint)(command.Options.ExpirationTime.Value.TotalSeconds)).ToString()
                        : "0";
                    Assert.AreEqual(expectedExpires, parts[3]);
                }
                Assert.AreEqual(command.Data.Count.ToString(), parts[4]);

                // validate the data block
                var block = new byte[command.Data.Count];
                var read  = stream.Read(block, 0, block.Length);
                Assert.AreEqual(block.Length, read);
                var expected = new byte[command.Data.Count];
                Buffer.BlockCopy(command.Data.Array, command.Data.Offset, expected, 0, command.Data.Count);
                CollectionAssert.AreEqual(expected, block);

                // read the last endline
                Assert.AreEqual('\r', stream.ReadByte());
                Assert.AreEqual('\n', stream.ReadByte());
                Assert.AreEqual(-1, stream.ReadByte());
            }
        }
コード例 #9
0
        public async Task SaveAsync_ShouldSaveFile()
        {
            var            stream  = new MemoryStream();
            var            result  = "test.txt";
            StorageCommand command = new StorageCommand()
            {
                ContentType = "text/plain",
                FileName    = "test.txt"
            };

            command.SetStreamSource(stream, "txt");
            _remoteStorage.Setup(x => x.SaveAsync(It.IsAny <Stream>(), command.FileName, command.ContentType))
            .Returns(Task <string> .FromResult <string>(result))
            .Verifiable();

            var res = await _fixture.SaveAsync(command);

            _remoteStorage.Verify();
            Assert.Equal(result, res);
        }
コード例 #10
0
        public static byte[] BuildStorageResponse(StorageCommand command)
        {
            BinaryResponseStatus status = BinaryResponseStatus.no_error;
            ulong cas = 0;

            if (command.ExceptionOccured)
            {
                status = BinaryResponseStatus.item_not_stored;
            }
            else
            {
                switch (command.OperationResult.ReturnResult)
                {
                case Result.SUCCESS:
                    if (command.NoReply == true)
                    {
                        return(null);
                    }
                    cas = (ulong)command.OperationResult.Value;
                    break;

                case Result.ITEM_EXISTS:
                    status = BinaryResponseStatus.key_exists;
                    break;

                case Result.ITEM_NOT_FOUND:
                    status = BinaryResponseStatus.key_not_found;
                    break;

                case Result.ITEM_MODIFIED:
                    status = BinaryResponseStatus.key_exists;
                    break;

                default:
                    status = BinaryResponseStatus.item_not_stored;
                    break;
                }
            }
            return(BuildResposne(command.Opcode, status, command.Opaque, cas, null, null, null));
        }
コード例 #11
0
 internal virtual bool Matches(StorageCommand command)
 {
     if (command is NodeCommand)
     {
         return(Inconsistencies.containsNodeId((( NodeCommand )command).Key));
     }
     if (command is RelationshipCommand)
     {
         return(Inconsistencies.containsRelationshipId((( RelationshipCommand )command).Key));
     }
     if (command is PropertyCommand)
     {
         return(Inconsistencies.containsPropertyId((( PropertyCommand )command).Key));
     }
     if (command is RelationshipGroupCommand)
     {
         return(Inconsistencies.containsRelationshipGroupId((( RelationshipGroupCommand )command).Key));
     }
     if (command is SchemaRuleCommand)
     {
         return(Inconsistencies.containsSchemaIndexId((( SchemaRuleCommand )command).Key));
     }
     return(false);
 }
コード例 #12
0
 public static extern bool DeviceIoControl(
     SafeHandle handle, StorageCommand command,
     ref StoragePropertyQuery query, int querySize,
     IntPtr descriptor, uint descriptorSize,
     out uint bytesReturned, IntPtr overlapped);
コード例 #13
0
 public static extern bool DeviceIoControl(
     SafeHandle handle, StorageCommand command,
     IntPtr inData, int querySize,
     ref STORAGE_DEVICE_NUMBER outData, int outDataSize,
     out uint bytesReturned, IntPtr overlapped);
コード例 #14
0
        public async Task ExecuteConsoleCommand(StorageCommand command)
        {
            switch (command.CommandType)
            {
            case StorageCommands.UserInfo:
            {
                await ExecuteConsoleCommandGetUserInfo(command.Options);

                break;
            }

            case StorageCommands.FileUpload:
            {
                await ExecuteConsoleCommandFileUpload(command.Options);

                break;
            }

            case StorageCommands.FileDownload:
            {
                await ExecuteConsoleCommandFileDownload(command.Options);

                break;
            }

            case StorageCommands.FileMove:
            {
                await ExecuteConsoleCommandFileMove(command.Options);

                break;
            }

            case StorageCommands.FileRemove:
            {
                await ExecuteConsoleCommandFileRemove(command.Options);

                break;
            }

            case StorageCommands.FileInfo:
            {
                await ExecuteConsoleCommandFileInfo(command.Options);

                break;
            }

            case StorageCommands.FileExport:
            {
                await ExecuteConsoleCommandFileExport(command.Options);

                break;
            }

            case StorageCommands.DirectoryCreate:
            {
                await ExecuteConsoleCommandDirectoryCreate(command.Options);

                break;
            }

            case StorageCommands.DirectoryMove:
            {
                await ExecuteConsoleCommandDirectoryMove(command.Options);

                break;
            }

            case StorageCommands.DirectoryRemove:
            {
                await ExecuteConsoleCommandDirectoryRemove(command.Options);

                break;
            }

            case StorageCommands.DirectoryList:
            {
                await ExecuteConsoleCommandDirectoryList(command.Options);

                break;
            }

            case StorageCommands.DirectorySearch:
            {
                await ExecuteConsoleCommandDirectorySearch(command.Options);

                break;
            }

            case StorageCommands.DirectoryInfo:
            {
                await ExecuteConsoleCommandDirectoryInfo(command.Options);

                break;
            }
            }
        }
コード例 #15
0
ファイル: MsSqlDataSaver.cs プロジェクト: tadeuspiat/legacy
        public void Save(EntityBase entity)
        {
            if (entity.State == EntityState.Unchanged || entity.State == EntityState.NewDeleted)
            {
                return;
            }

            ObjectDescription od = ClassFactory.GetObjectDescription(entity.GetType(), _ps);
            EntityBase        ent;

            if (od.IsWrapped)
            {
                ent = ((IWrapObject)entity).WrappedObject;
                _ps.SaveInner(ent);
                return;
            }
            ent = entity;


            bool isNew     = ent.State == EntityState.New;
            bool isDeleted = ent.State == EntityState.Deleted;

            //ent.State = EntityState.Unchanged;

            if (isNew && ent.ID == null)
            {
                throw new Exception("Id is null: entity type " + ent);
            }

            if (isNew && !_ps.Caches[ent.GetType()].Contains(ent.ID))
            {
                _ps.Caches[ent.GetType()].Add(ent);
            }


            foreach (PropertyDescription pd in od.ManyToManyProperties)
            {
                _ps.SourceStorageAccessMediator.AddCommand(new StorageCommand(ent, pd));
            }

            StorageCommand command = new StorageCommand(ent);

            ent.AcceptChanges();

            switch (command.CommandType)
            {
            case StorageCommandType.Insert:
            case StorageCommandType.Update:
                foreach (PropertyDescription pd in od.OneToOneProperties)
                {
                    EntityBase propvalue = pd.GetValue(ent) as EntityBase;
                    if (propvalue != null)
                    {
                        _ps.SaveInner(propvalue);
                    }
                }
                _ps.SourceStorageAccessMediator.AddCommand(command);
                foreach (PropertyDescription pd in od.OneToManyProperties)
                {
                    IList propvalue = pd.GetValue(ent) as IList;
                    if (propvalue != null && propvalue.Count > 0)
                    {
                        foreach (EntityBase e in propvalue)
                        {
                            _ps.SaveInner(e);
                        }
                    }
                }
                break;

            case StorageCommandType.Delete:
                foreach (PropertyDescription pd in od.OneToManyProperties)
                {
                    IList propvalue = pd.GetValue(ent) as IList;
                    if (propvalue != null && propvalue.Count > 0)
                    {
                        foreach (EntityBase e in propvalue)
                        {
                            _ps.SaveInner(e);
                        }
                    }
                }
                _ps.SourceStorageAccessMediator.AddCommand(command);
                foreach (PropertyDescription pd in od.OneToOneProperties)
                {
                    EntityBase propvalue = pd.GetValue(ent) as EntityBase;
                    if (propvalue != null)
                    {
                        _ps.SaveInner(propvalue);
                    }
                }
                break;
            }

            if (isDeleted)
            {
                if (_ps.Caches[ent.GetType()].Contains(ent.ID))
                {
                    _ps.Caches[ent.GetType()].Delete(ent);
                }
            }
            ent.AcceptChanges();
        }
コード例 #16
0
        public StorageCommand Parse(string rawCommand)
        {
            StorageCommand storageCommand = new StorageCommand();

            if (rawCommand.StartsWith(UserInfoCommandName))
            {
                storageCommand.CommandType = StorageCommands.UserInfo;
                storageCommand.Options     = GetOptions(rawCommand, UserInfoCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(ExitCommandName))
            {
                storageCommand.CommandType = StorageCommands.Exit;
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileUploadCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileUpload;
                storageCommand.Options     = GetOptions(rawCommand, FileUploadCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileDownloadCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileDownload;
                storageCommand.Options     = GetOptions(rawCommand, FileDownloadCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileMoveCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileMove;
                storageCommand.Options     = GetOptions(rawCommand, FileMoveCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileRemoveCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileRemove;
                storageCommand.Options     = GetOptions(rawCommand, FileRemoveCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileInfoCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileInfo;
                storageCommand.Options     = GetOptions(rawCommand, FileInfoCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(FileExportCommandName))
            {
                storageCommand.CommandType = StorageCommands.FileExport;
                storageCommand.Options     = GetOptions(rawCommand, FileExportCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectoryCreateCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectoryCreate;
                storageCommand.Options     = GetOptions(rawCommand, DirectoryCreateCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectoryMoveCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectoryMove;
                storageCommand.Options     = GetOptions(rawCommand, DirectoryMoveCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectoryRemoveCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectoryRemove;
                storageCommand.Options     = GetOptions(rawCommand, DirectoryRemoveCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectoryListCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectoryList;
                storageCommand.Options     = GetOptions(rawCommand, DirectoryListCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectorySearchCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectorySearch;
                storageCommand.Options     = GetOptions(rawCommand, DirectorySearchCommandName);
                return(storageCommand);
            }

            if (rawCommand.StartsWith(DirectoryInfoCommandName))
            {
                storageCommand.CommandType = StorageCommands.DirectoryInfo;
                storageCommand.Options     = GetOptions(rawCommand, DirectoryInfoCommandName);
                return(storageCommand);
            }

            throw new ApplicationException($"Wrong command: {rawCommand}.");
        }