public override Task <RobotCommandResponse> RobotCommand(RobotCommandRequest request, ServerCallContext context) { SpotRobot.SpotInstance.Leases.TryGetValue(request.Lease.Resource, out var lease); LeaseUseResult.Types.Status leaseResultStatus = LeaseUseResult.Types.Status.Unknown; if (lease != null) { if (lease.Item1 == request.Header.ClientName) { leaseResultStatus = LeaseUseResult.Types.Status.Ok; } Console.WriteLine($"RobotCommand - {request.Command}"); } else { leaseResultStatus = LeaseUseResult.Types.Status.InvalidLease; } return(Task.FromResult(new RobotCommandResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Status = RobotCommandResponse.Types.Status.Ok, LeaseUseResult = new LeaseUseResult() { Status = leaseResultStatus }, RobotCommandId = (uint)generator.Next(Int32.MaxValue) })); }
public override Task <EstopCheckInResponse> EstopCheckIn(EstopCheckInRequest request, ServerCallContext context) { var endpointIndex = SpotRobot.SpotInstance.RegisteredEndpointsByConfig.FindIndex(status => status.Endpoint.Role == request.Endpoint.Role); EstopCheckInResponse.Types.Status status = EstopCheckInResponse.Types.Status.EndpointUnknown; if (endpointIndex >= 0) { SpotRobot.SpotInstance.RegisteredEndpointsByConfig[endpointIndex].StopLevel = request.StopLevel; SpotRobot.SpotInstance.HandleEstopCheckin(); status = EstopCheckInResponse.Types.Status.Ok; Console.WriteLine( $"EstopCheckIn - checkin endpoint: {request.StopLevel} | {request.Endpoint.Role} - {request.Endpoint.Name} | {SpotRobot.SpotInstance.GetStopLevels().Min()}"); } if (request.Challenge != ~request.Response) { status = EstopCheckInResponse.Types.Status.IncorrectChallengeResponse; } return(Task.FromResult(new EstopCheckInResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Status = status, Request = request, Challenge = request.Challenge })); }
/// <summary> /// Streams a file to the response. /// </summary> /// <param name="response"> /// A <see cref="HeaderBuilder" /> to get the response from. /// </param> /// <param name="file"> /// A <see cref="System.String" /> representing an absolute path pointing to the file to stream. /// </param> /// <param name="mime"> /// A <see cref="System.String" /> denoting the mime type of the streamed string. Defaults to /// "application/octet-stream". /// </param> public static void StreamFile(this HeaderBuilder response, string file, string mime) { using (var fileStream = File.OpenRead(file)) { var responseStream = response .Add("Content-Type", mime) .Add("Content-Lenght", fileStream.Length.ToString()) .Add("Connection", "Close") .Finish(); using (responseStream) { var buffer = new byte[BufferSize]; while (responseStream.CanWrite && fileStream.CanRead) { var bytesRead = fileStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } responseStream.Write(buffer, 0, bytesRead); } responseStream.Flush(); } } }
public async Task DeserializeAsync_WithOneAxisAndSomeValuesAndOneValueDifferent_ReturnsTheValuesAsync() { var deserializer = new ContentDeserializer(); var header = new HeaderBuilder() .WithContentDataType(DataContentType.INTEGER) .WithNumberOfAxis(1) .WithAxisOfSize(dimensionIndex: 1, size: 10) .Build(); var dataStream = new ContentStreamBuilder() .WithDataBeingInitializedWith(123, header) .WithDataAtCoordinates( 10, new Dictionary <uint, ulong> { { 0, 5 } }, header) .Build(); var deserilaizedContent = await deserializer.DeserializeAsync(PipeReader.Create(dataStream), header); deserilaizedContent.Should().NotBeNull(); deserilaizedContent.Value.ToArray().Should().HaveCount(10); deserilaizedContent.Value.Span[4].Should().Equals(10); deserilaizedContent.Value.ToArray().Select((d, i) => (i, d)).Where(d => d.i != 5).All(d => (int)d.d == 123).Should().BeTrue(); }
public override Task <GetImageResponse> GetImage(GetImageRequest request, ServerCallContext context) { return(Task.FromResult(new GetImageResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), ImageResponses = { new ImageResponse { Status = ImageResponse.Types.Status.Ok, Shot = new ImageCapture() { AcquisitionTime = Timestamp.FromDateTime(DateTime.UtcNow), Image = new Image() { Format = Image.Types.Format.Jpeg, Cols = 640, Rows = 480, Data = ByteString.CopyFrom(File.ReadAllBytes(@"assets/camera.jpg")) } }, Source = new ImageSource() { ImageType = ImageSource.Types.ImageType.Visual, Cols = 640, Rows = 480, DepthScale = 1000 } } } })); }
public override Task <RobotIdResponse> GetRobotId(RobotIdRequest request, ServerCallContext context) { return(Task.FromResult( new RobotIdResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), RobotId = new RobotId { Nickname = "monstrey-technologies", Species = "spot", Version = "2.0.2", SerialNumber = "virtual-spot-001", ComputerSerialNumber = "virtual-001", SoftwareRelease = new RobotSoftwareRelease { Changeset = "initial", Name = "name", ApiVersion = "2.0.2", Type = "Some Type", BuildInformation = "Build information", ChangesetDate = Timestamp.FromDateTime(DateTime.Parse("2020-10-05").ToUniversalTime()), InstallDate = Timestamp.FromDateTime(DateTime.Parse("2020-10-05").ToUniversalTime()), Version = new SoftwareVersion { MajorVersion = 0, MinorVersion = 0, PatchLevel = 1 } } } })); }
public override Task <TimeSyncUpdateResponse> TimeSyncUpdate(TimeSyncUpdateRequest request, ServerCallContext context) { return(Task.FromResult(new TimeSyncUpdateResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), State = new TimeSyncState { Status = TimeSyncState.Types.Status.Ok, BestEstimate = new TimeSyncEstimate { ClockSkew = new Duration { Seconds = 0, }, RoundTripTime = new Duration { Seconds = 0 }, }, MeasurementTime = Timestamp.FromDateTime(DateTime.UtcNow) }, ClockIdentifier = request.ClockIdentifier ?? ClockIdentifier, })); }
public void WhenTheUserDeletesAllGitHubRepositories() { List <string> repoNames = new List <string>(); var repos = RESTHelpers.GETList( ConfigurationManager.AppSettings["URL"], ConfigurationManager.AppSettings["UsersResource"] + ConfigurationManager.AppSettings["UserName"] + ConfigurationManager.AppSettings["ReposResource"], HeaderBuilder.BuildHeader(), ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]).Result; foreach (var repo in repos) { HttpResponseMessage result = RESTHelpers.DELETERequestAsync( ConfigurationManager.AppSettings["URL"], repo.name, ConfigurationManager.AppSettings["ReposResource"], HeaderBuilder.BuildHeader(), ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]).Result; Console.WriteLine(result.StatusCode.ToString()); result.StatusCode.Should().Be(HttpStatusCode.NoContent); } }
public void WhenTheUserEditsARepositoryInGithub() { var repository = RepositoryBuilder.BuildRepository(); var patchRepository = RepositoryBuilder.BuildPatchRepository(); var jobj = JsonConvert.SerializeObject(repository); var patchJobj = JsonConvert.SerializeObject(patchRepository); //Create a new repository var result = RESTHelpers.POSTRequestAsync <RepositoryResponseDTO>( ConfigurationManager.AppSettings["URL"], ConfigurationManager.AppSettings["RepositoryResource"], HeaderBuilder.BuildHeader(), ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"], JObject.Parse(jobj)).Result; //PATCH a repository var patchResult = RESTHelpers.PATCHRequestAsync <RepositoryResponseDTO>( ConfigurationManager.AppSettings["URL"], ConfigurationManager.AppSettings["ReposResource"], repository.Name, HeaderBuilder.BuildHeader(), ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"], JObject.Parse(patchJobj)).Result; context.Add("PATCHEDRepo", patchResult); context.Add("ExpectedPATCHREPO", patchRepository); }
/// <summary> /// Writes the request. /// </summary> /// <param name="request">The request object.</param> /// <param name="cancellationToken">Optional cancellation token for this async task.</param> /// <returns></returns> internal async Task WriteRequestAsync(Request request, CancellationToken cancellationToken = default) { var headerBuilder = new HeaderBuilder(); headerBuilder.WriteRequestLine(request.Method, request.RequestUriString, request.HttpVersion); await WriteAsync(request, headerBuilder, cancellationToken); }
/// <summary> /// Writes the response. /// </summary> /// <param name="response">The response object.</param> /// <param name="cancellationToken">Optional cancellation token for this async task.</param> /// <returns>The Task.</returns> internal async Task WriteResponseAsync(Response response, CancellationToken cancellationToken = default) { var headerBuilder = new HeaderBuilder(); headerBuilder.WriteResponseLine(response.HttpVersion, response.StatusCode, response.StatusDescription); await WriteAsync(response, headerBuilder, cancellationToken); }
public override Task <DeregisterEstopEndpointResponse> DeregisterEstopEndpoint( DeregisterEstopEndpointRequest request, ServerCallContext context) { EstopEndpointWithStatus foundEndpoint = null; foreach (var registeredEndpoint in SpotRobot.SpotInstance.RegisteredEndpointsByConfig) { if (registeredEndpoint.Endpoint.UniqueId == request.TargetEndpoint.UniqueId) { foundEndpoint = registeredEndpoint; } } if (foundEndpoint != null) { Console.WriteLine( $"DeregisterEstopEndpointRequest - removing endpoint: {foundEndpoint.Endpoint.UniqueId}"); SpotRobot.SpotInstance.RegisteredEndpointsByConfig.Remove(foundEndpoint); } return(Task.FromResult(new DeregisterEstopEndpointResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Request = request, Status = foundEndpoint != null ? DeregisterEstopEndpointResponse.Types.Status.Success : DeregisterEstopEndpointResponse.Types.Status.EndpointMismatch })); }
public MessageEntryBuilder Header(Action <HeaderBuilder> configureHeader) { var headerBuilder = new HeaderBuilder(); configureHeader(headerBuilder); header = headerBuilder.Build(); return(this); }
public Context Clone(Action <ICloneBuilder> action) { var builder = new HeaderBuilder(this); action(builder); return(builder.Build()); }
public override Task <RobotStateResponse> GetRobotState(RobotStateRequest request, ServerCallContext context) { return(Task.FromResult(new RobotStateResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), RobotState = SpotRobot.SpotInstance.SpotRobotStatus.RobotState })); }
/// <summary> /// Websocket 握手输出 /// </summary> /// <param name="response"></param> public static void WriteWebSocketHandshakeResponse(HandshakeResponse response) { HeaderBuilder builder = HeaderBuilder.NewResonse(101, "Switching Protocols"); builder.Add("Upgrade", "websocket"); builder.Add("Connection", "Upgrade"); builder.Add("Sec-WebSocket-Accept", response.CreateResponseKey()); builder.Add("Server", Utility.PRODUCT_NAME); response.Stream.WriteBytes(builder.ToByteArray()); }
public static c**t Parse(byte[] onlyHeader) { var what = ReplyCode.Parser.Parse(onlyHeader); HeaderBuilder header = new HeaderBuilder(what); header.id = (ushort)((onlyHeader[0] << 8) | onlyHeader[1]); //HeaderBuilder header = new HeaderBuilder() return(new c**t(header)); }
public override Task <PowerCommandFeedbackResponse> PowerCommandFeedback(PowerCommandFeedbackRequest request, ServerCallContext context) { Console.WriteLine($"PowerCommandFeedback - Motor status: {SpotRobot.SpotInstance.PowerCommandStatus}"); return(Task.FromResult(new PowerCommandFeedbackResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Status = SpotRobot.SpotInstance.PowerCommandStatus })); }
static void Main(string[] args) { HeaderBuilder.BuildOwnHeaders(new HeaderModel() { Accept_Charset = "" }); var chromeDriver = ChromeDriverBuilder.CreateChromeDriver(new BuilderModel { Incognito = true }); chromeDriver.Navigate().GoToUrl("https://www.youtube.com/"); }
public void Should_AbleToSetHeaderWithHeaderBuilder() { string headerName = "headerName"; var hBuilder = new HeaderBuilder(); var response = builder.Description(description) .Header(headerName, hBuilder) .Build(); Assert.Equal(1, response.Headers.Count); Assert.Equal(hBuilder.Build().Default, response.Headers[headerName].Default); }
private static void FluentBuilderExercise2() { var header = HeaderBuilder. CreateNewHeader(); header.AddAgent("src", "alt", "name", "email", "phone", "city"); header.AddLogo("src", "alt", "href", "title"); header.Build(); WriteLine(header); ReadLine(); }
public void BuildContentTypeHeaderCreatesDictionaryContainingExpectedAcceptHeader() { // Arrange // Act var headers = new HeaderBuilder().BuildContentType(VersionedAbiquoMediaDataTypes.VND_ABIQUO_ENTERPRISE).GetHeaders(); // Assert Assert.AreEqual(1, headers.Count); Assert.IsTrue(headers.ContainsKey(AbiquoHeaderKeys.CONTENT_TYPE_HEADER_KEY)); Assert.AreEqual(VersionedAbiquoMediaDataTypes.VND_ABIQUO_ENTERPRISE, headers[AbiquoHeaderKeys.CONTENT_TYPE_HEADER_KEY]); }
/// <summary> /// Writes the request/response headers and body. /// </summary> /// <param name="requestResponse"></param> /// <param name="headerBuilder"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected async Task WriteAsync(RequestResponseBase requestResponse, HeaderBuilder headerBuilder, CancellationToken cancellationToken = default) { var body = requestResponse.CompressBodyAndUpdateContentLength(); headerBuilder.WriteHeaders(requestResponse.Headers); await WriteHeadersAsync(headerBuilder, cancellationToken); if (body != null) { await WriteBodyAsync(body, requestResponse.IsChunked, cancellationToken); } }
public void NavigationAddsHomeFirst() { var item = _db.GetItem("/sitecore/content/Home/Child1"); var linkManager = new Mock <BaseLinkManager>(); var headerBuilder = new HeaderBuilder(linkManager.Object, _rootResolver); var header = headerBuilder.GetHeader(item); var expectedItem = _rootResolver.GetNavigationRoot(item); Assert.Equal(expectedItem, header.NavigationItems?.FirstOrDefault()?.Item); }
public override Task <GetAuthTokenResponse> GetAuthToken(GetAuthTokenRequest request, ServerCallContext context) { return(Task.FromResult( new GetAuthTokenResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Status = GetAuthTokenResponse.Types.Status.Ok, Token = new HMACMD5().ComputeHash(System.Text.Encoding.UTF8.GetBytes(request.Username + request.Password)).ToString() })); }
public void SetsNavigationRootAsHomeItem() { var item = _db.GetItem("/sitecore/content/Home/Child1"); var linkManager = new Mock <BaseLinkManager>(); var headerBuilder = new HeaderBuilder(linkManager.Object, _rootResolver); var header = headerBuilder.GetHeader(item); var expectedItem = _rootResolver.GetNavigationRoot(item); Assert.Equal(expectedItem, header.HomeItem); }
/// <summary> /// 转换为二进制数据 /// </summary> /// <returns></returns> public override ArraySegment <byte> ToArraySegment(bool mask) { var builder = HeaderBuilder.NewResonse(101, "Switching Protocols"); builder.Add("Upgrade", "websocket"); builder.Add("Connection", "Upgrade"); builder.Add("Sec-WebSocket-Accept", this.CreateResponseKey()); builder.Add("Server", "NetworkSocket"); var bytes = builder.ToByteArray(); return(new ArraySegment <byte>(bytes)); }
public void NavigationMarksChildItemAsActiveForGrandchild() { var item = _db.GetItem("/sitecore/content/Home/Child2/Grandchild"); var linkManager = new Mock <BaseLinkManager>(); var headerBuilder = new HeaderBuilder(linkManager.Object, _rootResolver); var header = headerBuilder.GetHeader(item); var navItems = header.NavigationItems; Assert.Equal(1, navItems.Count(x => x.IsActive)); Assert.Equal("/sitecore/content/Home/Child2", navItems.Single(x => x.IsActive).Item.Paths.FullPath); }
public void NavigationMarksContextItemAsActive(string path) { var item = _db.GetItem(path); var linkManager = new Mock <BaseLinkManager>(); var headerBuilder = new HeaderBuilder(linkManager.Object, _rootResolver); var header = headerBuilder.GetHeader(item); var navItems = header.NavigationItems; Assert.Equal(1, navItems.Count(x => x.IsActive)); Assert.Equal(path, navItems.Single(x => x.IsActive).Item.Paths.FullPath); }
public override Task <RetainLeaseResponse> RetainLease(RetainLeaseRequest request, ServerCallContext context) { return(Task.FromResult(new RetainLeaseResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), LeaseUseResult = new LeaseUseResult { Status = LeaseUseResult.Types.Status.Ok, } })); }