private static string Get(RequestHeader requestHeader) { var name = RequestHeaders[requestHeader]; if (HttpContext.Current == null || !HttpContext.Current.Items.Contains(name)) return null; var value = HttpContext.Current.Items[name]; return value == null ? null : value.ToString(); }
public RequestPackage(RequestHeader header, byte[] data) { if (header == null) throw new ArgumentNullException("header"); if (data == null) throw new ArgumentNullException("data"); if (data.Length == 0) throw new ArgumentOutOfRangeException("data"); this.Header = header; this.Data = data; }
public RequestBody Read(NetworkStream connection, RequestHeader header) { var encoding = Encoding.GetEncoding(header.GetContentEncoding()); var requestReader = new StreamReader(connection, encoding); var body = new char[header.GetContentLength()]; requestReader.Read(body, 0, header.GetContentLength()); return new RequestBody(body); }
public Nsi() { //fixture.Customizations.Add(new TypeRelay(typeof(XmlNode),typeof(Helper))); //fixture.Customizations.Add(new TypeRelay(typeof(XmlResolver),typeof(Resolver))); //fixture.Customize(new AutoConfiguredMoqCustomization()); header = new RequestHeader { MessageGUID = Guid.NewGuid().ToString(), Date = DateTime.Now, SenderID = "fake service" }; }
public ResponseHeader ModifySubscription( RequestHeader requestHeader, uint subscriptionId, double requestedPublishingInterval, uint requestedLifetimeCount, uint requestedMaxKeepAliveCount, uint maxNotificationsPerPublish, byte priority, out double revisedPublishingInterval, out uint revisedLifetimeCount, out uint revisedMaxKeepAliveCount) { return(m_server.ModifySubscription(requestHeader, subscriptionId, requestedPublishingInterval, requestedLifetimeCount, requestedMaxKeepAliveCount, maxNotificationsPerPublish, priority, out revisedPublishingInterval, out revisedLifetimeCount, out revisedMaxKeepAliveCount)); }
/// <summary> /// Helper to get endpoints async. /// </summary> private Task<EndpointDescriptionCollection> GetEndpointsAsync( RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection profileUris) { return Task.Factory.FromAsync( (callback, state) => BeginGetEndpoints(requestHeader, endpointUrl, localeIds, profileUris, callback, state), result => { EndpointDescriptionCollection endpoints; var response = EndGetEndpoints(result, out endpoints); return endpoints; }, TaskCreationOptions.DenyChildAttach); }
/// <summary> /// Async find servers on network service /// </summary> /// <param name="client"></param> /// <param name="requestHeader"></param> /// <param name="startingRecordId"></param> /// <param name="maxRecordsToReturn"></param> /// <param name="serverCapabilityFilter"></param> /// <returns></returns> public static Task <FindServersOnNetworkResponse> FindServersOnNetworkAsync( this DiscoveryClient client, RequestHeader requestHeader, uint startingRecordId, uint maxRecordsToReturn, StringCollection serverCapabilityFilter) { #if !USE_TASK_RUN return(Task.Factory.FromAsync( (callback, state) => client.BeginFindServersOnNetwork(requestHeader, startingRecordId, maxRecordsToReturn, serverCapabilityFilter, callback, state), result => { var response = client.EndFindServersOnNetwork(result, out var lastCounterResetTime, out var servers); return NewFindServersOnNetworkResponse(response, lastCounterResetTime, servers); }, TaskCreationOptions.DenyChildAttach));
public ICompletes <Response> RequestWith(Request request, ICompletes <Response> completes) { _completesEventually = Stage.World.CompletesFor(completes); if (_testId != EmptyTestId) { request.Headers.Add(RequestHeader.Of(Client.ClientIdCustomHeader, _testId)); request.Headers.Add(RequestHeader.Of(RequestHeader.XCorrelationID, _testId)); } _requestSender.SendRequest(request); StowMessages(typeof(IResponseChannelConsumer)); return(completes); }
private string StitchRequestHeader(HttpRequestMessage request, RequestHeader requestHeader) { string value = null; var name = RequestContext.RequestHeaders[requestHeader]; if (request.Headers.Contains(name)) value = request.Headers.GetValues(name).First(); else if (_generateIfMissing) value = Guid.NewGuid().ToString(); else _errors.Add(string.Format("{0} is missing from the request", name)); RequestContext.Set(requestHeader, value); return value; }
public RefundRequestFactory() { refundRequest = new RefundRequest() { MerchantCode = Constants.MERCHANT_CODE, ReferenceNumber = Constants.PRE_REFERENCE_NUMBER + UniqueIdGenerator.KeyGenerator() }; RequestHeader requestHeader = new RequestHeader() { ApplicationName = Constants.APPLICATION_NAME, ApplicationPwd = Constants.APPLICATION_PASSWORD }; refundRequest.RequestHeader = requestHeader; }
public static IRouteHandler ConstructRouteHandler(RequestHeader request) { switch (request.Method) { case RequestMethod.GET: return(new GetRouteHandler()); break; //PA3 TODO: Add case for RequestMethod.POST default: throw new Exception("Request method not supported"); break; } }
public void Add_CanAddRequestHeaderKeyValuePair() { RequestHeader header = new RequestHeader(); header.Add("test", new[] { "test_value" }); header.HeadersInternal.Keys.Should().Contain("test"); header.HeadersInternal.Values.Should().BeEquivalentTo(new[] { new[] { "test_value" } }); }
/// <summary> /// 发现服务(由客户端请求) /// </summary> /// <param name="requestHeader"></param> /// <param name="endpointUrl"></param> /// <param name="localeIds"></param> /// <param name="serverUris"></param> /// <param name="servers"></param> /// <returns></returns> public override ResponseHeader FindServers( RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection serverUris, out ApplicationDescriptionCollection servers) { servers = new ApplicationDescriptionCollection(); ValidateRequest(requestHeader); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":请求查找服务..."); string hostName = Dns.GetHostName(); lock (_serverTable) { foreach (var item in _serverTable) { StringCollection urls = new StringCollection(); foreach (var url in item.DiscoveryUrls) { if (url.Contains("localhost")) { string str = url.Replace("localhost", hostName); urls.Add(str); } else { urls.Add(url); } } servers.Add(new ApplicationDescription() { ApplicationName = item.ServerNames.FirstOrDefault(), ApplicationType = item.ServerType, ApplicationUri = item.ServerUri, DiscoveryProfileUri = item.SemaphoreFilePath, DiscoveryUrls = urls, ProductUri = item.ProductUri, GatewayServerUri = item.GatewayServerUri }); } } return(CreateResponse(requestHeader, StatusCodes.Good)); }
public void TestThatSecureClientReceivesResponse() { var responseConsumer = new TestResponseConsumer(_output); var access = responseConsumer.AfterCompleting(1); var unknown = new UnknownResponseConsumer(access, _output); var config = Client.Configuration.Secure( _world.Stage, Address.From(Host.Of("google.com"), 443, AddressType.None), unknown, false, 10, 65535, 10, 65535); config.TestInfo(true); var client = Client.Using( config, Client.ClientConsumerType.RoundRobin, 5); var request = Request .Has(Method.Get) .And(new Uri("/search?q=vlingo", UriKind.Relative)) .And(RequestHeader.WithHost("google.com")) .And(RequestHeader.WithConnection("close")) .And(RequestHeader.WithContentType("text/html")); var response = client.RequestWith(request); response.AndThenConsume(res => { _responseContent = res.Entity.Content; access.WriteUsing("response", res); }); Assert.Equal(1, access.ReadFrom <int>("responseCount")); var accessResponse = access.ReadFrom <Response>("response"); Assert.Equal(_responseContent, accessResponse.Entity.Content); }
/// <summary> /// Writes the value /// </summary> private Variant WriteValue(Session session, NodeId nodeId) { // cast the value to a string. object value = TypeInfo.Cast(ValueTB.Text, TypeInfo.Scalars.String, m_sourceType.BuiltInType); // build list of attributes to read. WriteValueCollection nodesToWrite = new WriteValueCollection(); WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = nodeId; nodeToWrite.AttributeId = Attributes.Value; // using the WrappedValue instead of the Value property because we know the TypeInfo. // this makes the assignment more efficient by avoiding reflection to determine type. nodeToWrite.Value.WrappedValue = new Variant(value, m_sourceType); nodesToWrite.Add(nodeToWrite); // override the diagnostic masks (other parameters are set to defaults). RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = (uint)DiagnosticsMasks.All; // read the attributes. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = session.Write( requestHeader, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); // check status. if (StatusCode.IsBad(results[0])) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable); } // return valid value. return(nodeToWrite.Value.WrappedValue); }
/// <summary> /// Initializes the service before MakeApiCall. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="parameters">The method parameters.</param> protected override void InitForCall(string methodName, object[] parameters) { DfpAppConfig config = this.User.Config as DfpAppConfig; string oAuthHeader = null; RequestHeader header = GetRequestHeader(); if (header == null) { throw new DfpApiException(null, DfpErrorMessages.FailedToSetAuthorizationHeader); } if (!(this.GetType().Name == "NetworkService" && (methodName == "getAllNetworks" || methodName == "makeTestNetwork"))) { if (string.IsNullOrEmpty(header.networkCode)) { throw new SoapHeaderException("networkCode header is required in all API versions. " + "The only exceptions are NetworkService.getAllNetworks and " + "NetworkService.makeTestNetwork.", XmlQualifiedName.Empty); } } if (string.IsNullOrEmpty(header.applicationName) || header.applicationName.Contains( DfpAppConfig.DEFAULT_APPLICATION_NAME)) { throw new ApplicationException(DfpErrorMessages.RequireValidApplicationName); } if (config.AuthorizationMethod == DfpAuthorizationMethod.OAuth2) { if (this.User.OAuthProvider != null) { oAuthHeader = this.User.OAuthProvider.GetAuthHeader(); } else { throw new DfpApiException(null, DfpErrorMessages.OAuthProviderCannotBeNull); } } else { throw new DfpApiException(null, DfpErrorMessages.UnsupportedAuthorizationMethod); } ContextStore.AddKey("OAuthHeader", oAuthHeader); base.InitForCall(methodName, parameters); }
/// <summary> /// Validates request header and returns a request context. /// </summary> /// <remarks> /// This method verifies that the session id valid and that it uses secure channel id /// associated with with current thread. It also verifies that the timestamp is not too /// and that the sequence number is not out of order (update requests only). /// </remarks> public virtual OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { if (requestHeader == null) { throw new ArgumentNullException("requestHeader"); } Session session = null; try { lock (m_lock) { // check for create session request. if (requestType == RequestType.CreateSession || requestType == RequestType.ActivateSession) { return(new OperationContext(requestHeader, requestType)); } // find session. if (!m_sessions.TryGetValue(requestHeader.AuthenticationToken, out session)) { throw new ServiceResultException(StatusCodes.BadSessionClosed); } // validate request header. session.ValidateRequest(requestHeader, requestType); // return context. return(new OperationContext(requestHeader, requestType, session)); } } catch (Exception e) { ServiceResultException sre = e as ServiceResultException; if (sre != null && sre.StatusCode == StatusCodes.BadSessionNotActivated) { if (session != null) { CloseSession(session.Id); } } throw new ServiceResultException(e, StatusCodes.BadUnexpectedError); } }
private void PrimeConnection(TcpClient client) { LOG.Info(string.Format("Socket connection established to {0}, initiating session", client.Client.RemoteEndPoint)); ConnectRequest conReq = new ConnectRequest(0, lastZxid, Convert.ToInt32(conn.SessionTimeout.TotalMilliseconds), conn.SessionId, conn.SessionPassword); byte[] buffer; using (MemoryStream ms = new MemoryStream()) using (EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, ms, Encoding.UTF8)) { BinaryOutputArchive boa = BinaryOutputArchive.getArchive(writer); boa.WriteInt(-1, "len"); conReq.Serialize(boa, "connect"); ms.Position = 0; writer.Write(ms.ToArray().Length - 4); buffer = ms.ToArray(); } lock (outgoingQueueLock) { if (!ClientConnection.disableAutoWatchReset && (!zooKeeper.DataWatches.IsEmpty() || !zooKeeper.ExistWatches.IsEmpty() || !zooKeeper.ChildWatches.IsEmpty())) { var sw = new SetWatches(lastZxid, zooKeeper.DataWatches, zooKeeper.ExistWatches, zooKeeper.ChildWatches); var h = new RequestHeader(); h.Type = (int)OpCode.SetWatches; h.Xid = -8; Packet packet = new Packet(h, new ReplyHeader(), sw, null, null, null, null, null); outgoingQueue.AddFirst(packet); } foreach (ClientConnection.AuthData id in conn.authInfo) { outgoingQueue.AddFirst(new Packet(new RequestHeader(-4, (int)OpCode.Auth), null, new AuthPacket(0, id.scheme, id.data), null, null, null, null, null)); } outgoingQueue.AddFirst((new Packet(null, null, null, null, buffer, null, null, null))); } lock (this) { EnableWrite(); } if (LOG.IsDebugEnabled) { LOG.Debug("Session establishment request sent on " + client.Client.RemoteEndPoint); } }
public ResponseHeader CreateSubscription( RequestHeader requestHeader, double requestedPublishingInterval, uint requestedLifetimeCount, uint requestedMaxKeepAliveCount, uint maxNotificationsPerPublish, bool publishingEnabled, byte priority, out uint subscriptionId, out double revisedPublishingInterval, out uint revisedLifetimeCount, out uint revisedMaxKeepAliveCount) { return(m_session.CreateSubscription(requestHeader, requestedPublishingInterval, requestedLifetimeCount, requestedMaxKeepAliveCount, maxNotificationsPerPublish, publishingEnabled, priority, out subscriptionId, out revisedPublishingInterval, out revisedLifetimeCount, out revisedMaxKeepAliveCount)); }
public override Task <object?> Invoke(RequestHeader header, object?request) { var taskCompletion = new TaskCompletionSource <object?>(); _serviceMethod(_serviceInstance.Value, request) .ContinueWith(task => { if (task.IsFaulted) { taskCompletion.SetException(task.Exception); return; } taskCompletion.SetResult(_getTaskResult(task)); }); return(taskCompletion.Task); }
public ICompletes <Response> RequestWith(Request request, ICompletes <Response> completes) { var correlationId = request.Headers.HeaderOf(RequestHeader.XCorrelationID); Request readyRequest; if (correlationId == null) { correlationId = RequestHeader.Of(RequestHeader.XCorrelationID, _randomUuidGenerator.GenerateGuid().ToString()); readyRequest = request.And(correlationId); } else { readyRequest = request; } _completables[correlationId !.Value !] = Stage.World.CompletesFor(completes);
private ArrivalDTO arrivalToArrivalRequestDto(Arrival arrival) { RequestHeader requestHeader = new RequestHeader(); requestHeader.DateRequest = DateTimeOffset.UtcNow.ToString("yyyyMMdd"); requestHeader.TimeRequest = DateTimeOffset.UtcNow.ToString("hhmmss"); requestHeader.RequestId = Guid.NewGuid().ToString(); return(new ArrivalDTO() { Comments = arrival.Comments, FID = arrival.Facility, ArrivalDate = arrival.ArrivalDate, RequestHeader = requestHeader, Serials = arrival.SerialList }); }
public void HandleFailureTest() { Client testClient = new Client(); RequestHeader testHeader = new RequestHeader(9001, "cheese.txt", testClient.key); ResponseHeader testResponse = new ResponseHeader(); testClient.Connect("127.0.0.1", 9001); testClient.SendHeader(testHeader.ReturnRawHeader()); if (testClient.HandleResponse(false, "cheese.txt").Key == 0) { Assert.Pass(); } else { Assert.Fail(); } }
/// <summary> /// Invokes the Read service. /// </summary> public virtual ResponseHeader Read( RequestHeader requestHeader, double maxAge, TimestampsToReturn timestampsToReturn, ReadValueIdCollection nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
/// <summary> /// Invokes the SetMonitoringMode service. /// </summary> public virtual ResponseHeader SetMonitoringMode( RequestHeader requestHeader, uint subscriptionId, MonitoringMode monitoringMode, UInt32Collection monitoredItemIds, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
/// <summary> /// Invokes the Browse service. /// </summary> public virtual ResponseHeader Browse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
/// <summary> /// Invokes the FindServersOnNetwork service. /// </summary> public virtual ResponseHeader FindServersOnNetwork( RequestHeader requestHeader, uint startingRecordId, uint maxRecordsToReturn, StringCollection serverCapabilityFilter, out DateTime lastCounterResetTime, out ServerOnNetworkCollection servers) { lastCounterResetTime = DateTime.MinValue; servers = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
private static void RunTest(Dictionary <string, string> settings) { var uri = settings[UriName]; var verb = settings[MethodName]; var method = GetMethod(verb); var cookieValue = settings[CookieName]; var payload = settings[PayloadName]; var contentType = settings[ContentTypeName]; var runCount = int.Parse(settings[RunCountName]); Console.WriteLine(UriName + ": " + uri); Console.WriteLine(MethodName + ": " + method); Console.WriteLine(CookieName + ": " + cookieValue); Console.WriteLine(PayloadName + ": " + payload); Console.WriteLine(ContentTypeName + ": " + contentType); Console.WriteLine(RunCountName + ": " + runCount); var cookie = new RequestHeader("Cookie", cookieValue); var content = new Everest.Content.StringBodyContent(payload, contentType); var client = new RestClient(cookie, new RequestHeader("X-Requested-With", "XMLHttpRequest")); var firstResponse = client.Send(method, uri, content); if (contentType == "application/json") { if (!firstResponse.Body.StartsWith("{")) { throw new Exception("Epected JSON but got: " + firstResponse.Body); } } firstResponse.Dispose(); var stopwatch = new Stopwatch(); stopwatch.Start(); for (var i = 0; i < runCount; i++) { client.Send(method, uri, content).Dispose(); Console.Write("."); } stopwatch.Stop(); Console.WriteLine(); Console.WriteLine(uri); Console.WriteLine("Average time: " + new TimeSpan(stopwatch.Elapsed.Ticks / runCount)); }
public ReplyHeader SubmitRequest(RequestHeader h, IRecord request, IRecord response, ZooKeeper.WatchRegistration watchRegistration) { ReplyHeader r = new ReplyHeader(); Packet p = QueuePacket(h, r, request, response, null, null, watchRegistration, null, null); lock (p) { while (!p.Finished) { if (!Monitor.Wait(p, SessionTimeout)) { throw new TimeoutException(string.Format("The request {0} timed out while waiting for a resposne from the server.", request)); } } } return(r); }
/// <summary> /// Invokes the ModifyMonitoredItems service. /// </summary> public virtual ResponseHeader ModifyMonitoredItems( RequestHeader requestHeader, uint subscriptionId, TimestampsToReturn timestampsToReturn, MonitoredItemModifyRequestCollection itemsToModify, out MonitoredItemModifyResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
public async Task TransferSubscriptionNative(bool sendInitialData) { Session transferSession = null; try { var requestHeader = new RequestHeader { Timestamp = DateTime.UtcNow, TimeoutHint = MaxTimeout }; // to validate the behavior of the sendInitialValue flag, // use a static variable to avoid sampled notifications in publish requests var namespaceUris = Session.NamespaceUris; NodeId[] testSet = CommonTestWorkers.NodeIdTestSetStatic.Select(n => ExpandedNodeId.ToNodeId(n, namespaceUris)).ToArray(); var clientTestServices = new ClientTestServices(Session); var subscriptionIds = CommonTestWorkers.CreateSubscriptionForTransfer(clientTestServices, requestHeader, testSet, 0, -1); TestContext.Out.WriteLine("Transfer SubscriptionIds: {0}", subscriptionIds[0]); transferSession = await ClientFixture.ConnectAsync(ServerUrl, SecurityPolicies.Basic256Sha256, Endpoints).ConfigureAwait(false); Assert.AreNotEqual(Session.SessionId, transferSession.SessionId); requestHeader = new RequestHeader { Timestamp = DateTime.UtcNow, TimeoutHint = MaxTimeout }; var transferTestServices = new ClientTestServices(transferSession); CommonTestWorkers.TransferSubscriptionTest(transferTestServices, requestHeader, subscriptionIds, sendInitialData, false); // verify the notification of message transfer requestHeader = new RequestHeader { Timestamp = DateTime.UtcNow, TimeoutHint = MaxTimeout }; CommonTestWorkers.VerifySubscriptionTransferred(clientTestServices, requestHeader, subscriptionIds, true); transferSession.Close(); } finally { transferSession?.Dispose(); } }
/// <summary> /// Async browse service /// </summary> /// <param name="client"></param> /// <param name="requestHeader"></param> /// <param name="view"></param> /// <param name="nodeToBrowse"></param> /// <param name="maxResultsToReturn"></param> /// <param name="browseDirection"></param> /// <param name="referenceTypeId"></param> /// <param name="includeSubtypes"></param> /// <param name="nodeClassMask"></param> /// <param name="resultMask"></param> /// <param name="ct"></param> /// <returns></returns> public static Task <BrowseResponse> BrowseAsync(this SessionClient client, RequestHeader requestHeader, ViewDescription view, NodeId nodeToBrowse, uint maxResultsToReturn, BrowseDirection browseDirection, NodeId referenceTypeId, bool includeSubtypes, uint nodeClassMask, BrowseResultMask resultMask = BrowseResultMask.All, CancellationToken ct = default) { return(client.BrowseAsync(requestHeader, view, maxResultsToReturn, new BrowseDescriptionCollection { new BrowseDescription { BrowseDirection = browseDirection, IncludeSubtypes = includeSubtypes, NodeClassMask = nodeClassMask, NodeId = nodeToBrowse, ReferenceTypeId = referenceTypeId, ResultMask = (uint)resultMask } }, ct)); }
/// <summary> /// Invokes the HistoryRead service. /// </summary> public virtual ResponseHeader HistoryRead( RequestHeader requestHeader, ExtensionObject historyReadDetails, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueIdCollection nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
public void AddingHandlerBodyWithMediaTypeMapper() { var request = Request.Has(Method.Post) .And("/user/admin/name".ToMatchableUri()) .And(Body.From("{\"given\":\"John\",\"family\":\"Doe\"}")) .And(RequestHeader.Of(RequestHeader.ContentType, "application/json")) .And(Version.Http1_1); var mappedParameters = new Action.MappedParameters(1, Method.Post, "ignored", new List <Action.MappedParameter> { new Action.MappedParameter("String", "admin") }); var handler1 = new RequestHandler0(Method.Get, "/user/admin/name").Body <NameData>(); AssertResolvesAreEquals(ParameterResolver.Body <NameData>(DefaultMediaTypeMapper.Instance), handler1.Resolver); Assert.Equal(new NameData("John", "Doe"), handler1.Resolver.Apply(request, mappedParameters)); }
public static RequestHeader GetRequestHeader(string deviceType, string deviceDensity, string compCode = null, string userCode = null, string userId = null) { var header = new RequestHeader { UserCode = userCode, UserId = userId, AppVersion = Xamarin.Essentials.AppInfo.VersionString, DeviceType = deviceType, Manufacturer = Xamarin.Essentials.DeviceInfo.Manufacturer, Platform = Xamarin.Essentials.DeviceInfo.Platform.ToString(), Density = deviceDensity, Model = Xamarin.Essentials.DeviceInfo.Model, Timestamp = "", OSVersion = Xamarin.Essentials.DeviceInfo.VersionString }; return(header); }
static void Main(string[] args) { Console.WriteLine("Client starting...."); using (NsiClient client = new NsiClient()) { var header = new RequestHeader(); var request = new exportNsiListRequest(); var result = client.exportNsiList(ref header, request); Console.WriteLine("result id is {0}", result.Id); } using (RegOrgPortsTypeClient client1 = new RegOrgPortsTypeClient()) { //will be implemented later } Console.WriteLine("Client will be terminated."); Console.ReadKey(); }
/// <summary> /// Initializes the context with a session. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="requestType">Type of the request.</param> public OperationContext(RequestHeader requestHeader, RequestType requestType) { if (requestHeader == null) throw new ArgumentNullException("requestHeader"); m_channelContext = SecureChannelContext.Current; m_session = null; m_identity = null; m_preferredLocales = new string[0]; m_diagnosticsMask = (DiagnosticsMasks)requestHeader.ReturnDiagnostics; m_stringTable = new StringTable(); m_auditLogEntryId = requestHeader.AuditEntryId; m_requestId = Utils.IncrementIdentifier(ref s_lastRequestId); m_requestType = requestType; m_clientHandle = requestHeader.RequestHandle; m_operationDeadline = DateTime.MaxValue; if (requestHeader.TimeoutHint > 0) { m_operationDeadline = DateTime.UtcNow.AddMilliseconds(requestHeader.TimeoutHint); } }
static void Main(string[] args) { Console.ReadLine(); Console.WriteLine(@"Upload video"); using (var client = new TcpClient(@"127.0.0.1", 11111)) { var handler = new TransferHandler(client.GetStream(), new byte[16 * 1024]); //var config = new LogConfig(new RequestHeader(ClientPlatform.WinMobile, new Version(0, 0, 0, 0), string.Empty, string.Empty), Category.Logs, @"C:\Temp\"); //new LogsClientHandler(2, handler).ConfigureAsync(config).Wait(); var path = @"C:\Users\bg900343\Desktop\DEV-B318.wmv"; var clientFile = new ClientFile(Path.GetFileName(path), File.ReadAllBytes(path)); var requestHeader = new RequestHeader(ClientPlatform.WinMobile, new Version(0, 0, 0, 0), string.Empty, string.Empty); new LogsClientHandler(2, handler).UploadFilesAsync(requestHeader, new List<ClientFile> { clientFile }).Wait(); handler.CloseAsync().Wait(); } Console.WriteLine(@"Done"); Console.ReadLine(); }
private async void ConfigureFolderTapped(object sender, TappedRoutedEventArgs e) { var btn = (sender as Button); if (btn != null) { var ctx = btn.DataContext as LogCategoryViewModel; if (ctx != null) { btn.IsEnabled = false; try { var path = Path.Combine(new[] { @"C:\Temp\", ctx.Platform.ToString(), ctx.Category.ToString() }); using (var socket = new StreamSocket()) { await socket.ConnectAsync(new HostName(@"127.0.0.1"), @"11111"); var handler = new WinRtTransferHandler(socket); var requestHeader = new RequestHeader(ctx.Platform, new Version(0, 0, 0, 0), string.Empty, string.Empty); var config = new LogConfig(requestHeader, ctx.Category, path); await new LogsClientHandler(2, handler).ConfigureAsync(config); await handler.CloseAsync(); } ctx.Path = path; } catch { } finally { btn.IsEnabled = true; } } } }
/// <summary> /// Invokes the HistoryUpdate service. /// </summary> public virtual ResponseHeader HistoryUpdate( RequestHeader requestHeader, ExtensionObjectCollection historyUpdateDetails, out HistoryUpdateResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the ActivateSession service. /// </summary> public virtual ResponseHeader ActivateSession( RequestHeader requestHeader, SignatureData clientSignature, SignedSoftwareCertificateCollection clientSoftwareCertificates, StringCollection localeIds, ExtensionObject userIdentityToken, SignatureData userTokenSignature, out byte[] serverNonce, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos) { serverNonce = null; results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the HistoryRead service. /// </summary> public virtual ResponseHeader HistoryRead( RequestHeader requestHeader, ExtensionObject historyReadDetails, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueIdCollection nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the Write service. /// </summary> public virtual ResponseHeader Write( RequestHeader requestHeader, WriteValueCollection nodesToWrite, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the Cancel service. /// </summary> public virtual ResponseHeader Cancel( RequestHeader requestHeader, uint requestHandle, out uint cancelCount) { cancelCount = 0; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the Read service. /// </summary> public virtual ResponseHeader Read( RequestHeader requestHeader, double maxAge, TimestampsToReturn timestampsToReturn, ReadValueIdCollection nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the UnregisterNodes service. /// </summary> public virtual ResponseHeader UnregisterNodes( RequestHeader requestHeader, NodeIdCollection nodesToUnregister) { ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the RegisterServer2 service. /// </summary> public virtual ResponseHeader RegisterServer2( RequestHeader requestHeader, RegisteredServer server, ExtensionObjectCollection discoveryConfiguration, out StatusCodeCollection configurationResults, out DiagnosticInfoCollection diagnosticInfos) { configurationResults = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the BrowseNext service. /// </summary> public virtual ResponseHeader BrowseNext( RequestHeader requestHeader, bool releaseContinuationPoints, ByteStringCollection continuationPoints, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the TranslateBrowsePathsToNodeIds service. /// </summary> public virtual ResponseHeader TranslateBrowsePathsToNodeIds( RequestHeader requestHeader, BrowsePathCollection browsePaths, out BrowsePathResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the Browse service. /// </summary> public virtual ResponseHeader Browse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the DeleteReferences service. /// </summary> public virtual ResponseHeader DeleteReferences( RequestHeader requestHeader, DeleteReferencesItemCollection referencesToDelete, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the AddNodes service. /// </summary> public virtual ResponseHeader AddNodes( RequestHeader requestHeader, AddNodesItemCollection nodesToAdd, out AddNodesResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the FindServersOnNetwork service. /// </summary> public virtual ResponseHeader FindServersOnNetwork( RequestHeader requestHeader, uint startingRecordId, uint maxRecordsToReturn, StringCollection serverCapabilityFilter, out DateTime lastCounterResetTime, out ServerOnNetworkCollection servers) { lastCounterResetTime = DateTime.MinValue; servers = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the QueryFirst service. /// </summary> public virtual ResponseHeader QueryFirst( RequestHeader requestHeader, ViewDescription view, NodeTypeDescriptionCollection nodeTypes, ContentFilter filter, uint maxDataSetsToReturn, uint maxReferencesToReturn, out QueryDataSetCollection queryDataSets, out byte[] continuationPoint, out ParsingResultCollection parsingResults, out DiagnosticInfoCollection diagnosticInfos, out ContentFilterResult filterResult) { queryDataSets = null; continuationPoint = null; parsingResults = null; diagnosticInfos = null; filterResult = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the FindServers service. /// </summary> public virtual ResponseHeader FindServers( RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection serverUris, out ApplicationDescriptionCollection servers) { servers = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the QueryNext service. /// </summary> public virtual ResponseHeader QueryNext( RequestHeader requestHeader, bool releaseContinuationPoint, byte[] continuationPoint, out QueryDataSetCollection queryDataSets, out byte[] revisedContinuationPoint) { queryDataSets = null; revisedContinuationPoint = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the GetEndpoints service. /// </summary> public virtual ResponseHeader GetEndpoints( RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection profileUris, out EndpointDescriptionCollection endpoints) { endpoints = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Invokes the CloseSession service. /// </summary> public virtual ResponseHeader CloseSession( RequestHeader requestHeader, bool deleteSubscriptions) { ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Deletes the subscription. /// </summary> public void Delete(OperationContext context) { // delete the diagnostics. if (m_diagnosticsId != null && !m_diagnosticsId.IsNullNodeId) { ServerSystemContext systemContext = m_server.DefaultSystemContext.Copy(m_session); m_server.DiagnosticsNodeManager.DeleteSubscriptionDiagnostics(systemContext, m_diagnosticsId); } lock (m_lock) { try { // TraceState("DELETED"); // the context may be null if the server is cleaning up expired subscriptions. // in this case we create a context with a dummy request and use the current session. if (context == null) { RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = (uint)(int)DiagnosticsMasks.OperationSymbolicIdAndText; context = new OperationContext(requestHeader, RequestType.Unknown); } StatusCodeCollection results; DiagnosticInfoCollection diagnosticInfos; DeleteMonitoredItems( context, new UInt32Collection(m_monitoredItems.Keys), true, out results, out diagnosticInfos); } catch (Exception e) { Utils.Trace(e, "Delete items for subscription failed."); } } }
/// <summary> /// Invokes the CreateSession service. /// </summary> public virtual ResponseHeader CreateSession( RequestHeader requestHeader, ApplicationDescription clientDescription, string serverUri, string endpointUrl, string sessionName, byte[] clientNonce, byte[] clientCertificate, double requestedSessionTimeout, uint maxResponseMessageSize, out NodeId sessionId, out NodeId authenticationToken, out double revisedSessionTimeout, out byte[] serverNonce, out byte[] serverCertificate, out EndpointDescriptionCollection serverEndpoints, out SignedSoftwareCertificateCollection serverSoftwareCertificates, out SignatureData serverSignature, out uint maxRequestMessageSize) { sessionId = null; authenticationToken = null; revisedSessionTimeout = 0; serverNonce = null; serverCertificate = null; serverEndpoints = null; serverSoftwareCertificates = null; serverSignature = null; maxRequestMessageSize = 0; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }