public async Task WhenReadSourceToVhdDestinationThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.vhd";
            var fakeCommandHelper       = new FakeCommandHelper(new [] { sourcePath });
            var cancellationTokenSource = new CancellationTokenSource();

            // assert: destination path vhd doesn't exist
            Assert.False(File.Exists(destinationPath));

            // act: read source img to destination vhd
            var readCommand = new ReadCommand(new NullLogger <ReadCommand>(), fakeCommandHelper, Enumerable.Empty <IPhysicalDrive>(), sourcePath, destinationPath);
            var result      = await readCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);

            // get source bytes
            var sourceBytes = fakeCommandHelper.GetMedia(sourcePath).GetBytes();

            // get destination bytes from vhd
            var destinationBytes = await ReadMediaBytes(fakeCommandHelper, destinationPath, FakeCommandHelper.ImageSize);

            var destinationPathSize = new FileInfo(destinationPath).Length;

            // assert length is not the same (vhd file format different than img) and bytes are the same
            Assert.NotEqual(sourceBytes.Length, destinationPathSize);
            Assert.Equal(sourceBytes, destinationBytes);

            // delete destination path vhd
            File.Delete(destinationPath);
        }
        public async Task WhenReadSourceToImgDestinationThenReadDataIsIdentical()
        {
            // arrange
            var sourcePath              = $"{Guid.NewGuid()}.img";
            var destinationPath         = $"{Guid.NewGuid()}.img";
            var fakeCommandHelper       = new FakeCommandHelper(new [] { sourcePath }, new [] { destinationPath });
            var cancellationTokenSource = new CancellationTokenSource();

            // act - read source img to destination img
            var readCommand = new ReadCommand(new NullLogger <ReadCommand>(), fakeCommandHelper, new List <IPhysicalDrive>(), sourcePath, destinationPath);
            DataProcessedEventArgs dataProcessedEventArgs = null;

            readCommand.DataProcessed += (_, args) =>
            {
                dataProcessedEventArgs = args;
            };
            var result = await readCommand.Execute(cancellationTokenSource.Token);

            Assert.True(result.IsSuccess);

            Assert.NotNull(dataProcessedEventArgs);
            Assert.NotEqual(0, dataProcessedEventArgs.PercentComplete);
            Assert.NotEqual(0, dataProcessedEventArgs.BytesProcessed);
            Assert.Equal(0, dataProcessedEventArgs.BytesRemaining);
            Assert.NotEqual(0, dataProcessedEventArgs.BytesTotal);

            // assert data is identical
            var sourceBytes      = fakeCommandHelper.GetMedia(sourcePath).GetBytes();
            var destinationBytes = fakeCommandHelper.GetMedia(destinationPath).GetBytes();

            Assert.Equal(sourceBytes, destinationBytes);
        }
예제 #3
0
        public void VisitRead(ReadCommand Read)
        {
            System.Console.WriteLine("Sending read: " + Read.Schema);
            ITuple tuple = CliApi.Read(Read.Schema);

            System.Console.WriteLine("Got: " + tuple);
        }
예제 #4
0
        /// <summary>
        /// mark all conversations as read.
        /// </summary>
        /// <returns></returns>
        public Task ReadAllAsync()
        {
            var cids    = ConversationUnreadListener.FindAllConvIds();
            var readCmd = new ReadCommand().ConvIds(cids).PeerId(this.ClientId);

            return(this.RunCommandAsync(readCmd));
        }
예제 #5
0
        private async void OnOpenDrive()
        {
            try
            {
                Reading = true;
                CdItems.Clear();
                CdItemViewModel[] cdTracks = await _cdReaderService.GetTracks(DriveLetter);

                CdItems.AddRange(cdTracks);
                await RaisePropertyChanged(nameof(CdItems));

                Reading = false;
            }
            catch (Exception)
            {
                _dialogService.ShowError(Resources.Error_CdRead);
                Reading = false;
                CdItems.Clear();
            }
            finally
            {
                SelectAllCommand.RaiseCanExecuteChanged();
                DeSelectAllCommand.RaiseCanExecuteChanged();
                ReadCommand.RaiseCanExecuteChanged();
            }
        }
예제 #6
0
        private void DoReadCommand(ReadCommand command, IConnectionManager connection)
        {
            List <Task <DataTable> > tasks = new List <Task <DataTable> >();

            foreach (string podName in workers)
            {
                tasks.Add(RelayReadCommand(podName, command, connection));
            }
            List <DataTable> tables = new List <DataTable>();

            foreach (Task <DataTable> task in tasks)
            {
                task.Wait();
                if (task.Status == TaskStatus.Faulted || task.Exception != null)
                {
                    throw new Exception($"{command} failed", task.Exception);
                }
                if (task.Result != null)
                {
                    tables.Add(task.Result);
                }
            }
            command.Result = DataTableUtilities.Merge(tables);
            foreach (string param in command.Parameters)
            {
                if (command.Result.Columns[param] == null)
                {
                    throw new Exception($"Column {param} does not exist in table {command.TableName} (it appears to have disappeared in the merge)");
                }
            }
        }
예제 #7
0
        public void Initialize()
        {
            fakeStories = new Story[]
            {
                new Story { Message = "First story", PostedOn = new DateTime(2000, 1, 1, 15, 1, 0) },
                new Story { Message = "Second story", PostedOn = new DateTime(2000, 1, 1, 15, 5, 0) }
            };

            //Creates a fake ITimelineReaderService with a liked observer in order to
            //assert that the SUT relies on it
            timelineReaderServiceObserver = new StubObserver();
            timelineReaderService = new Contracts.Interfaces.Fakes.StubITimelineReaderService
            {
                InstanceObserver = timelineReaderServiceObserver,
                GetTimelineString = userName => fakeStories
            };

            storyFormatterObserver = new StubObserver();
            storyFormatter = new Contracts.Interfaces.Fakes.StubIEntityFormatter<Story>
            {
                InstanceObserver = storyFormatterObserver,
                FormatT0 = story => story.Message
            };

            sut = new ReadCommand(timelineReaderService, storyFormatter);
        }
예제 #8
0
        public async ValueTask Handle(IBackgroundTaskContext context)
        {
            if (context.BackgroundTask is not ReadBackgroundTask readBackgroundTask)
            {
                return;
            }

            try
            {
                var physicalDrives = await physicalDriveManager.GetPhysicalDrives();

                var commandHelper = new CommandHelper();
                var readCommand   =
                    new ReadCommand(loggerFactory.CreateLogger <ReadCommand>(), commandHelper, physicalDrives,
                                    readBackgroundTask.SourcePath, readBackgroundTask.DestinationPath);
                readCommand.DataProcessed += async(_, args) =>
                {
                    await progressHubConnection.UpdateProgress(new Progress
                    {
                        Title               = readBackgroundTask.Title,
                        IsComplete          = false,
                        PercentComplete     = args.PercentComplete,
                        BytesProcessed      = args.BytesProcessed,
                        BytesRemaining      = args.BytesRemaining,
                        BytesTotal          = args.BytesTotal,
                        MillisecondsElapsed = args.PercentComplete > 0
                            ? (long)args.TimeElapsed.TotalMilliseconds
                            : new long?(),
                        MillisecondsRemaining = args.PercentComplete > 0
                            ? (long)args.TimeRemaining.TotalMilliseconds
                            : new long?(),
                        MillisecondsTotal = args.PercentComplete > 0
                            ? (long)args.TimeTotal.TotalMilliseconds
                            : new long?()
                    }, context.Token);
                };

                var result = await readCommand.Execute(context.Token);

                await progressHubConnection.UpdateProgress(new Progress
                {
                    Title           = readBackgroundTask.Title,
                    IsComplete      = true,
                    HasError        = result.IsFaulted,
                    ErrorMessage    = result.IsFaulted ? result.Error.Message : null,
                    PercentComplete = 100
                }, context.Token);
            }
            catch (Exception e)
            {
                await progressHubConnection.UpdateProgress(new Progress
                {
                    Title           = readBackgroundTask.Title,
                    IsComplete      = true,
                    HasError        = true,
                    ErrorMessage    = e.Message,
                    PercentComplete = 100
                }, context.Token);
            }
        }
        public void ReturnAllUserPostsInPayloadWhenSuccessfullyExecuted()
        {
            var userRepository = new UserRepository();
            var user           = userRepository.RegisterUser("alice");

            user.Posts.AddRange(
                new List <Post> {
                new Post("test1"), new Post("test2")
            }
                );

            var arguments = new List <string>
            {
                "alice"
            };

            var readCommand = new ReadCommand()
            {
                Arguments      = arguments,
                UserRepository = userRepository
            };
            var commandResult = readCommand.Execute();

            Assert.That(commandResult.Payload.Count, Is.EqualTo(2));
            Assert.That(commandResult.Payload[0], Is.EqualTo("test1 (0 seconds ago)"));
            Assert.That(commandResult.Payload[1], Is.EqualTo("test2 (0 seconds ago)"));
        }
예제 #10
0
        protected override void UpdateModuleCycle()
        {
            this.Port0CycleCount++;
            { //Perform writing
                WriteCommand wCmd = Write_IFace.Get();
                if (wCmd.Enabled)
                {
                    uint loaded;
                    this.RAM.LoadWord((uint)wCmd.Address, out loaded, EnumMemorymAccessType.No);
                    this.RAM.StoreWord((uint)wCmd.Address, ((((uint)wCmd.Value) << 16) & 0xFFFF0000) | (loaded & 0xFFFF), 2, 0);
                    this.Port0WriteCycleCount++;
                }
                PreviousWrite = wCmd;
            }

            { //Count reading
                ReadCommand rCmd = Read_IFace.Get();
                if (rCmd.Enabled && rCmd.Address != PreviousRead.Address)
                {
                    this.Port0ReadCycleCount++;
                    if (rCmd.AccessType != EnumMemorymAccessType.No)
                    {
                        ReadAccessCycleTypes[(int)rCmd.AccessType]++;
                    }
                }
                PreviousRead = rCmd;
            }

            base.UpdateModuleCycle();
        }
예제 #11
0
        public static string BuildQuery(ReadCommand command, List <Column> columns)
        {
            var columnNames  = string.Join(",", columns.Select(x => $"`{x.Name}`"));
            var queryBuilder = new StringBuilder($"select {columnNames} from `{command.TableSchema.Name}`");
            var pkNames      = GetPkNames(command.TableSchema);

            if (pkNames.Count > 0)
            {
                var fromClause = SqlUtil
                                 .MakeLexicalGreaterOrEqualComparision(
                    pkNames,
                    Enumerable.Range(0, pkNames.Count).Select(i => $"from_{i}").ToList()
                    );
                queryBuilder.Append($" where ({fromClause})");

                if (command.ToPrimaryKey != null)
                {
                    var toClause = SqlUtil
                                   .MakeLexicalLessThanComparision(
                        pkNames,
                        Enumerable.Range(0, pkNames.Count).Select(i => $"to_{i}").ToList());
                    queryBuilder
                    .Append($" and ({toClause})");
                }
            }

            return(queryBuilder.ToString());
        }
예제 #12
0
        private Task <DataTable> RelayReadCommand(string podName, ReadCommand command, IConnectionManager connection)
        {
            return(Task.Run <DataTable>(() =>
            {
                V1Pod pod = GetWorkerPod(podName);
                if (string.IsNullOrEmpty(pod.Status.PodIP))
                {
                    throw new NotImplementedException("Pod IP not set.");
                }

                // Create a new socket connection to the pod.
                string ip = pod.Status.PodIP;
                ushort port = GetPortNo(pod);
                WriteToLog($"Attempting connection to pod {podName} on {ip}:{port}");
                using (NetworkSocketClient conn = new NetworkSocketClient(relayOptions.Verbose, ip, port, Protocol.Managed))
                {
                    WriteToLog($"Connection to {podName} established. Sending command...");

                    // Relay the command to the pod.
                    try
                    {
                        return conn.ReadOutput(command);
                    }
                    catch (Exception err)
                    {
                        throw new Exception($"Unable to read output from pod {podName}", err);
                    }
                }
            }));
        }
예제 #13
0
        public ReadHandle ReadAsync()
        {
            if (EndOfStream)
            {
                return(new ReadHandle());              // returns void handle
            }
            // check file termination
            _info.Target->dataLength = Math.Min(_info.Target->blockSize, (int)(_info.Target->fileSize - ((long)_info.Target->blockSize) * _info.Target->blockPos));

            _readCommands[0] = new ReadCommand
            {
                Offset = _info.Target->blockPos * _info.Target->blockSize,
                Size   = _info.Target->dataLength,
                Buffer = _byteBuffer.GetUnsafePtr(),
            };

            ReadHandle read_handle = AsyncReadManager.Read(_path.Target, (ReadCommand *)(_readCommands.GetUnsafePtr()), 1);

            if (!read_handle.IsValid())
            {
                throw new InvalidOperationException("failure to open file.");
            }

            _info.Target->blockPos++;
            return(read_handle);
        }
예제 #14
0
        public ASyncRAMInterfaceRW1High(RAM ram)
        {
            this.RAM = ram;

            Read_IFace  = CreateInputface <ReadCommand>();
            Write_IFace = CreateInputface <WriteCommand>();

            Read_OFace = CreateAsyncOutputface <ushort>();

            PreviousRead = new ReadCommand()
            {
                Enabled = false,
                Address = -1
            };

            Read_OFace.SetFunc(() =>
            {
                ReadCommand rCmd = Read_IFace.Get();
                uint res;
                if (rCmd.Enabled)
                {
                    this.RAM.LoadWord(
                        (uint)rCmd.Address, out res,
                        rCmd.Address != PreviousRead.Address ? rCmd.AccessType : EnumMemorymAccessType.No, 2, 0);
                }
                else
                {
                    res = 0;
                }
                return((ushort)(res >> 16));
            });
        }
예제 #15
0
        // index -1 means 'use current index'
        public static void WriteContainerToDisk(this PersistentSceneSystem persistentSceneSystem, Hash128 containerIdentifier, bool initial = false, int index = -1)
        {
            Debug.Assert(initial == (index != -1), "Don't fill in an index if you want the initial container!");

            // Path
            string path       = CalculateStreamingAssetsPath(containerIdentifier);
            string folderPath = Path.GetDirectoryName(path);

            Debug.Assert(!string.IsNullOrEmpty(folderPath));
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            // Container
            PersistentDataStorage   dataStorage = persistentSceneSystem.PersistentDataStorage;
            PersistentDataContainer container;

            if (index == -1)
            {
                container = dataStorage.GetReadContainerForCurrentIndex(containerIdentifier);
            }
            else if (initial)
            {
                container = dataStorage.GetInitialStateReadContainer(containerIdentifier);
            }
            else
            {
                int oldIndex = dataStorage.NonWrappedIndex;
                dataStorage.ToIndex(index);
                container = dataStorage.GetReadContainerForCurrentIndex(containerIdentifier);
                dataStorage.ToIndex(oldIndex);
            }

            // Workaround for bug where AsyncReadManager.Read keeps a handle to the last 11 reads
            for (int i = 0; i < 12; i++)
            {
                string bugWorkaroundFilePath = Application.streamingAssetsPath + $"/UnityAsyncReadBugWorkaround{i.ToString()}.txt";
                unsafe
                {
                    var readCmd = new ReadCommand
                    {
                        Size = 0, Offset = 0, Buffer = null
                    };
                    var readHandle = AsyncReadManager.Read(bugWorkaroundFilePath, &readCmd, 1);
                    readHandle.JobHandle.Complete();
                    readHandle.Dispose();
                }
            }

            // Write To Disk
            using (var fileStream = new StreamBinaryWriter(path))
            {
                fileStream.Write(container.CalculateEntityCapacity());
                NativeArray <byte> rawData = container.GetRawData();
                fileStream.Write(rawData.Length);
                fileStream.WriteArray(rawData);
            }
        }
예제 #16
0
 private void OnSelectOutDir()
 {
     if (_dialogService.ShowFolderSelect(out string path))
     {
         TargetDirectory = path;
     }
     ReadCommand.RaiseCanExecuteChanged();
 }
예제 #17
0
 /// <summary>
 /// Read job output.
 /// </summary>
 /// <param name="command"></param>
 public DataTable ReadOutput(ReadCommand command)
 {
     if (connectionType != Protocol.Managed)
     {
         throw new NotImplementedException("tbi");
     }
     return(((ManagedCommunicationProtocol)comms).ReadOutput(command));
 }
 protected virtual void RaiseCanExecuteEvents()
 {
     MessageCommand.RaiseCanExecuteChanged();
     DeleteCommand.RaiseCanExecuteChanged();
     ReadCommand.RaiseCanExecuteChanged();
     ChangeCategoryCommand.RaiseCanExecuteChanged();
     FollowUpCommand.RaiseCanExecuteChanged();
 }
예제 #19
0
        public void GivenAReadCommandWhenExecuteMethodIsCalledThenItCallsReadInTheCommandReceiver()
        {
            var command = new ReadCommand(this.receiver, BobUserHandle);

            command.Execute();

            this.receiver.Received().Read(BobUserHandle);
        }
예제 #20
0
 public void VisitRead(ReadCommand Read)
 {
     System.Console.WriteLine("read ");
     foreach (IField field in Read.Schema.Fields)
     {
         System.Console.WriteLine(field.ToString().Trim('"'));
     }
 }
예제 #21
0
        public void GivenAReadCommandWhenCreateFormaterForCommandIsInvokedOnFactoryThenItReturnsAMessageFromater()
        {
            var command = new ReadCommand(this.brokerMock, BobUserHandle);
            var factory = new MessageFormaterFactory();

            var formater = factory.CreateFormaterForCommand(command);

            formater.Should().BeAssignableTo <MessageFormater>();
        }
예제 #22
0
        public List <string> Execute(string qry)
        {
            string        cmdString = "select Status.StatusText from Status";
            IReadCommand  cmd       = new ReadCommand();
            DataTable     dt        = cmd.Execute(cmdString);
            List <string> status    = new List <string>();

            status = (from row in dt.AsEnumerable() select Convert.ToString(row["STATUSTEXT"])).ToList();
            return(status);
        }
 private static void StartReadMagicBytes(string path, JobMetaLoaderInternal *answer)
 {
     answer->ReadCommandReference = new ReadCommand
     {
         Buffer = (void *)answer->MagicBytePtr,
         Offset = 0L,
         Size   = 20L,
     };
     answer->ReadHandleReference = AsyncReadManager.Read(path, (ReadCommand *)answer->ReadCommandPtr, 1);
 }
예제 #24
0
        public List<string> Execute(string qry)
        {
            string cmdString = "select Status.StatusText from Status";
            IReadCommand cmd = new ReadCommand();
            DataTable dt = cmd.Execute(cmdString);
            List<string> status = new List<string>();

            status = (from row in dt.AsEnumerable() select Convert.ToString(row["STATUSTEXT"])).ToList();
            return status;
        }
        [MethodImpl(256)] //256 is the value of MethodImplOptions.AggresiveInlining
        public unsafe static ReadCommand GetCommand(void *buffer, long readSize, long offset)
        {
            var cmd = new ReadCommand();

            cmd.Buffer = buffer;
            cmd.Size   = readSize;
            cmd.Offset = offset;

            return(cmd);
        }
예제 #26
0
        public void GivenAReadCommandWhenExecuteMethodIsCalledThenItStoresTheExecutionResultInResults()
        {
            var command = new ReadCommand(this.receiver, BobUserHandle);

            this.receiver.Read(BobUserHandle).Returns(new[] { new Message(null, PostMessageText) });

            command.Execute();

            ((IQueryCommand)command).Results.Should().Contain(m => m.Body == PostMessageText);
        }
예제 #27
0
        private void PopulateTheComboBoxes()
        {
            IReadCommand cmd        = new ReadCommand();
            string       statusText = "SELECT STATUSTEXT FROM STATUS";

            StatusComBox.DataSource = cmd.Execute(statusText);

            string streamText = "SELECT STREAMTEXT FROM STREAM";

            StreamComBox.DataSource = cmd.Execute(streamText);
        }
예제 #28
0
        public void BuildQuery_OnePK_ShouldReturnValidQuery()
        {
            // Arrange
            var command = new ReadCommand
                          (
                new TableSchema
            {
                Name    = "Orders",
                Columns = new List <Column>
                {
                    new Column
                    {
                        Name = "Id",
                        PkOrdinalPosition = 1
                    },
                    new Column
                    {
                        Name = "Name"
                    }
                }
            },
                new List <object>
            {
                1
            },
                new List <object>
            {
                10
            }
                          );

            var columns = new List <Column>
            {
                new Column
                {
                    Name = "Id",
                    PkOrdinalPosition = 1
                },
                new Column
                {
                    Name = "Name"
                }
            };

            // Act
            var result = SourceDataReader.BuildQuery(command, columns);

            // Assert
            Assert.AreEqual("select `Id`,`Name` from `Orders` where (`Id` >= @from_0) and (`Id` < @to_0)", result);
        }
예제 #29
0
        public unsafe void Start()
        {
            string path = Path.Combine(Application.streamingAssetsPath, relativePathToStreamingData);

            cmd = new NativeArray <ReadCommand>(1, Allocator.Persistent);
            var command = new ReadCommand {
                Offset = 0,
                Size   = 1024,
                Buffer = (byte *)UnsafeUtility.Malloc(1024, 16, Allocator.Persistent)
            };

            cmd[0]     = command;
            readHandle = AsyncReadManager.Read(path, (ReadCommand *)cmd.GetUnsafePtr(), 1);
        }
예제 #30
0
        public void ReadCommand_Ctor_ParamValidation()
        {
            // ARRANGE
            var storage     = new Mock <IStorageProvider>();
            var interaction = new Mock <IInteractionProvider>();
            var time        = new Mock <ITimeProvider>();

            // ACT

            // missing "arg"
            IDictionary <string, string> arguments = new Dictionary <string, string> {
            };

            ArgumentException ex1 = Assert.Throws <ArgumentException>(() =>
            {
                var command = new ReadCommand(storage.Object, interaction.Object, time.Object, arguments);
            });

            // missing "storage"
            ArgumentNullException ex2 = Assert.Throws <ArgumentNullException>(() =>
            {
                var command = new ReadCommand(null, interaction.Object, time.Object, arguments);
            });

            // missing "interaction"
            ArgumentNullException ex3 = Assert.Throws <ArgumentNullException>(() =>
            {
                var command = new ReadCommand(storage.Object, null, time.Object, arguments);
            });

            // missing "time"
            ArgumentNullException ex4 = Assert.Throws <ArgumentNullException>(() =>
            {
                var command = new ReadCommand(storage.Object, interaction.Object, null, arguments);
            });

            // missing "arguments"
            ArgumentNullException ex5 = Assert.Throws <ArgumentNullException>(() =>
            {
                var command = new ReadCommand(storage.Object, interaction.Object, time.Object, null);
            });

            // ASSERT
            Assert.Equal("user", ex1.ParamName);
            Assert.Equal("storage", ex2.ParamName);
            Assert.Equal("interaction", ex3.ParamName);
            Assert.Equal("time", ex4.ParamName);
            Assert.Equal("arguments", ex5.ParamName);
        }
예제 #31
0
        public void OnReadCommand(ReadCommand command)
        {
            if (insideLoop)
            {
                loopCommands.Add(command);
                return;
            }

            string partitionId = command.PartitionId.Replace(LOOPSTRING, currentRep.ToString());
            string objectId    = command.ObjectId.Replace(LOOPSTRING, currentRep.ToString());
            // Check if server id is null
            string serverId = command.ServerId?.Replace(LOOPSTRING, currentRep.ToString());

            bool   success;
            string value;

            // No fallback server
            if (serverId == null || serverId == "-1")
            {
                success = SimpleKVSMessageLayer.Instance.Read(
                    partitionId,
                    objectId,
                    out value);
            }
            else
            {
                success = SimpleKVSMessageLayer.Instance.ReadFallback(
                    partitionId,
                    objectId,
                    serverId,
                    out value);
            }

            if (success)
            {
                Console.WriteLine(
                    "[{0}] Object <{1},{2}> has value '{3}'",
                    DateTime.Now.ToString("HH:mm:ss"),
                    partitionId,
                    objectId,
                    value);
            }
            else
            {
                Console.WriteLine(
                    "[{0}] N/A",
                    DateTime.Now.ToString("HH:mm:ss"));
            }
        }
예제 #32
0
        public void Encode()
        {
            var command = new ReadCommand()
            {
                Address      = 0x12,
                FunctionCode = ModbusFunction.ReadCoils,
                Count        = 2
            };

            var content = command.Encode();

            Assert.Equal(5, content.Length);
            Assert.Equal(command.Address, content[2]);
            Assert.Equal(command.Count, content[4]);
        }
예제 #33
0
        /// <summary>
        /// リードコマンドの応答文字列を作成する
        /// </summary>
        /// <param name="command"></param>
        /// <param name="album"></param>
        /// <returns></returns>
        public static string CreateReadResponse(ReadCommand command, Album[] albums)
        {
            if (albums == null || albums.Length == 0)
            {
                return "401 " + command.Category + " " + command.DiscId + " No such CD entry in database." + Environment.NewLine;
            }

            Album album = albums[0];

            StringBuilder result = new StringBuilder();

            result.AppendLine("210 Misc " + album.GN_ID + " CD database entry follows (until terminating `.')");
            result.AppendLine("DISCID=" + album.GN_ID);
            result.AppendLine("DTITLE=" + album.ARTIST + " / " + album.TITLE);
            result.AppendLine("DYEAR=" + album.DATE);
            result.AppendLine("DGENRE=" + album.GENRE.Value);

            for (int i = 0; i < album.TRACK.Length; i++)
            {
                string title = album.TRACK[i].TITLE;
                if (string.IsNullOrWhiteSpace(album.TRACK[i].ARTIST) == false)
                {
                    title = album.TRACK[i].ARTIST + " / " + title;
                }

                result.AppendLine("TTITLE" + i + "=" + title);
            }

            result.AppendLine("EXTD=");

            for (int i = 0; i < album.TRACK.Length; i++)
            {
                result.AppendLine("EXTT" + i + "=");
            }

            result.AppendLine("PLAYORDER=");
            result.AppendLine(".");

            return result.ToString();
        }
예제 #34
0
        public List<DbJob> Execute(string stream, string status, string location, string company, List<string> skills)
        {
            List<DbJob> finalJobs = new List<DbJob>();
            List<string> sortedJobs = new List<string>();

            // search based on stream, status, skills, company and location

            // get jobs with stream, status, loaction and company match
            string qry = "SELECT JOBPOST.job_id FROM JOBPOST JOIN STREAM ON JOBPOST.stream_id = STREAM.stream_id JOIN STATUS ON JOBPOST.status_id = STATUS.status_id WHERE statusText = '" + status + "' AND streamText = '" + stream + "' AND company = '" + company + "' AND location = '" + location + "'";

            IReadCommand read = new ReadCommand();
            DataTable dt = read.Execute(qry);
            List<string> jobs = (from row in dt.AsEnumerable() select Convert.ToString(row["JOB_ID"])).ToList();

            for (int i = 0; i < jobs.Count(); i++)
            {
                sortedJobs.Add(jobs[i]);
            }

            // match skills

            return finalJobs;
        }