public ASPXHandler(String fileName, Dictionary<String, String> envVariables) { this.fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1); this.fullFilePath = fileName; this.fileExtension = this.fileName.Substring(this.fileName.IndexOf('.')); if (File.Exists(fileName)) { // Create an instance of Host class var aspxHost = new Host(); // Pass to it filename and query string this.responseBody = aspxHost.CreateHost( fileName, envVariables["server_root"], envVariables["query_string"]); this.responseHeader = new ResponseHeader("Status: 200 OK\r\nContent-Type: text/html\r\n"); this.responseHeader.setContentLength(this.responseBody.Length); } else { var error = new Error404(); this.responseHeader = error.getResponseHeader(); this.responseBody = error.getResponseBody(); } }
public static void SendDirectories(Stream stream, string dirs) { Header header = new ResponseHeader(); byte[] response = Encoding.ASCII.GetBytes(dirs); header.SetHeader("ContentLength", response.Length.ToString()); header.SetHeader("ContentType", @"text\html"); SendContentHandler.SendHeader(header, stream); stream.Write(response, 0, response.Length); }
/// <summary> /// ReplicationDetailsResponse constructor /// </summary> /// <param name="ResponseHeader"></param> /// <param name="IndexSize"></param> /// <param name="IndexPath"></param> /// <param name="IsMaster"></param> /// <param name="IsSlave"></param> /// <param name="IndexVersion"></param> /// <param name="Generation"></param> /// <param name="IsReplicating"></param> /// <param name="TotalPercent"></param> /// <param name="TimeRemaining"></param> public ReplicationDetailsResponse(ResponseHeader ResponseHeader, string IndexSize, string IndexPath, string IsMaster, string IsSlave, long IndexVersion, long Generation, string IsReplicating, string TotalPercent, string TimeRemaining) { responseHeader = ResponseHeader; indexSize = IndexSize; indexPath = IndexPath; isMaster = IsMaster; isSlave = IsSlave; indexVersion = IndexVersion; generation = Generation; isReplicating = IsReplicating; totalPercent = TotalPercent; timeRemaining = TimeRemaining; }
public void SendErrorPage(Stream stream, int code) { ResponseHeader header = new ResponseHeader(); using (StreamReader sr = new StreamReader(Statics.Root + @"/Errorpages/" + code + ".html")) { String line; String content = ""; while ((line = sr.ReadLine()) != null) { content += line; } byte[] response = Encoding.ASCII.GetBytes(content); header.Status = code; header.SetHeader("ContentLength", response.Length.ToString()); SendContentHandler.SendHeader(header, stream); stream.Write(response, 0, response.Length); } }
public EchoMode Get_SetEchoMode() { SendCommand('\u0005', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'e') throw new PolhemusException(0xF3); EchoMode e; if (_format == Format.ASCII) { string s = TReader.ReadLine(); e = s == "0" ? EchoMode.Off : EchoMode.On; } else { if (currentHeader.Length != 4) throw new PolhemusException(0xF2); e = BReader.ReadInt32() == 0 ? EchoMode.Off : EchoMode.On; } if (e != _echoMode) throw new PolhemusException(0xF4); return e; }
public Triple Get_SourceMountingFrame() { SendCommand('G', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'G') throw new PolhemusException(0xF3); Triple mfa; if (_format == Format.ASCII) mfa = Triple.FromASCII(TReader, "Sxxx.xxxB"); else { if (currentHeader.Length != 12) throw new PolhemusException(0xF2); mfa = new Triple(BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle()); } return mfa; }
public List<IDataFrameType> Get_OutputDataList(int station) { SendCommand("O" + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'O') throw new PolhemusException(0xF3); if (currentHeader.Station != station) throw new PolhemusException(0xF5); List<IDataFrameType> dfList=_responseFrameDescription[station - 1]; if (_format == Format.ASCII) { foreach (IDataFrameType dft in dfList) { int aa = (int)parseASCIIStream(TReader, "xxB"); if (dft.ParameterValue != aa) throw new PolhemusException(0xF6); //incorrect value in list } parseASCIIStream("<>"); //don't forget ending CR/LF! } else { int c = currentHeader.Length / 4; for (int i = 0; i < c; i++) //should be twenty of them { int p = BReader.ReadInt32(); if (i < dfList.Count) //check actual list member if (dfList[i].ParameterValue != p) throw new PolhemusException(0xF6); //incorrect value in list else ; else if (i == dfList.Count) //check end-of-list value if (p != -1) throw new PolhemusException(0xF6); //incorrect value in list else ; else //check empty site value if (p != 0) throw new PolhemusException(0xF6); //incorrect value in list } } return _responseFrameDescription[station - 1]; //internal list is correct! Return it. }
public Quadruple Get_PositionFilterParameters() { SendCommand('X', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'X') throw new PolhemusException(0xF3); Quadruple fp = new Quadruple(); if (_format == Format.ASCII) { fp = Quadruple.FromASCII(TReader, "Sx.xxxB"); parseASCIIStream("<>"); } else { if (currentHeader.Length != 16) throw new PolhemusException(0xF2); fp = new Quadruple(BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle()); } return fp; }
public FileHandler(String fileName) { this.contentTypes.Add(".txt", "text/plain"); this.contentTypes.Add(".html", "text/html"); this.contentTypes.Add(".htm", "text/html"); this.contentTypes.Add(".json", "application/json"); this.contentTypes.Add(".xml", "application/xml"); this.contentTypes.Add(".png", "image/png"); this.contentTypes.Add(".gif", "image/gif"); this.contentTypes.Add(".jpeg", "image/jpg"); this.contentTypes.Add(".jpg", "image/jpg"); this.contentTypes.Add(".css", "text/css"); this.contentTypes.Add(".js", "application/javascript"); this.fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1); this.fullFilePath = fileName; this.fileExtension = this.fileName.Substring(this.fileName.LastIndexOf('.')); if (File.Exists(fileName)) { var fs = new FileStream(this.fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); this.responseBody = new byte[fs.Length]; this.responseBodyLength = this.responseBody.Length; fs.Read(this.responseBody, 0, this.responseBodyLength); fs.Close(); string tmpHeader = "Status: 200 OK\r\n"; if (this.contentTypes.ContainsKey(this.fileExtension)) { tmpHeader += "Content-Type: " + this.contentTypes[this.fileExtension] + "\r\n"; } this.responseHeader = new ResponseHeader(tmpHeader); this.responseHeader.setContentLength(this.responseBodyLength); } else { var error = new Error404(); this.responseHeader = error.getResponseHeader(); this.responseBody = Encoding.ASCII.GetBytes(error.getResponseBody()); } }
public Triple Get_HemisphereOfOperation(int station) { SendCommand("H" + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'H') throw new PolhemusException(0xF3); Triple cc; if (_format == Format.ASCII) { cc = Triple.FromASCII(TReader, "Sxx.xxxB"); parseASCIIStream("<>"); } else { if (currentHeader.Length != 12) throw new PolhemusException(0xF2); cc = Triple.FromBinary(BReader); } return cc; }
public TodoResponse DeleteToDo(int id) { TodoResponse todoResponse = new TodoResponse(); ResponseHeader responseHeader = new ResponseHeader(); ResponseBody responseBody = new ResponseBody(); string statusMessage = string.Empty; HttpStatusCode statusCode; List <Error> errorlist = new List <Error>(); try { ToDo toDo = _repository.getTodoById(id); //If the item to delete is not present in database if (null == toDo) { statusCode = HttpStatusCode.NotFound; statusMessage = AppConstants.Error; Error error = new Error(string.Format(AppConstants.TODO_NOT_FOUND_MSG, id), AppConstants.TODO_NOT_FOUND); errorlist.Add(error); } else { // return value and check the status and handle error // Database delete takes place here if (_repository.remove(toDo) > 0) { statusCode = HttpStatusCode.OK; statusMessage = AppConstants.Success; } else { statusCode = HttpStatusCode.InternalServerError; statusMessage = AppConstants.Error; errorlist.Add(new Error(AppConstants.DELETE_FAILED_MSG, AppConstants.DELETE_FAILED)); } } } catch (Exception ex) { statusCode = HttpStatusCode.NotModified; statusMessage = AppConstants.Error; string strErrorMsg = AppConstants.Error_Message + ex.Message; Error error = new Error(strErrorMsg, AppConstants.TODO_DELETE_ERROR); errorlist.Add(error); Logger.WriteLog(AppConstants.Error_Message + ex.Message + AppConstants.Inner_Exception + ex.InnerException + AppConstants.Stack_Trace + ex.StackTrace + AppConstants.Soure + ex.Source); } //Write to log file if error is present if (errorlist.Count > 0) { errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in DeleteToDo() for ID : " + id + AppConstants.Error_Code + error.errorCode + AppConstants.Error_Message + error.errorMessage)); } responseHeader.statusCode = statusCode; responseHeader.statusMessage = statusMessage; responseHeader.error = errorlist; todoResponse.responseHeader = responseHeader; responseBody.todo = _repository.getAllTodo(); todoResponse.responseBody = responseBody; return(todoResponse); }
/// <summary> /// ReplicationIndexVersionResponse constructor /// </summary> /// <param name="ResponseHeader">response header</param> /// <param name="IndexVersion">index version</param> /// <param name="Generation">generation</param> public ReplicationIndexVersionResponse(ResponseHeader ResponseHeader, long IndexVersion, long Generation) { responseHeader = ResponseHeader; indexversion = IndexVersion; generation = Generation; }
public TodoResponse PutToDo(int id, ToDo toDo) { TodoResponse todoResponse = new TodoResponse(); ResponseHeader responseHeader = new ResponseHeader(); ResponseBody responseBody = new ResponseBody(); List <Error> errorlist = new List <Error>(); HttpStatusCode statusCode; string statusMessage = string.Empty; errorlist = ValidateUtility.ValidateInput(toDo); try { if (!ModelState.IsValid) { statusCode = HttpStatusCode.BadRequest; statusMessage = AppConstants.Error; errorlist.Add(new Error(AppConstants.MODAL_STATE_INVALID, AppConstants.BAD_REQUEST)); } //Check if any of the input parameters are empty else if (errorlist.Count > 0) { statusCode = HttpStatusCode.BadRequest; statusMessage = AppConstants.Error; //add mulitple error if needed to errorlist errorlist.ForEach(e => Logger.WriteLog(e.errorMessage)); } // check if the ids in the request match else if (id != toDo.SlNo) { statusCode = HttpStatusCode.BadRequest; statusMessage = AppConstants.Error; //add mulitple error if needed to errorlist errorlist.Add(new Error(AppConstants.TODO_ID_MISMATCH_MSG, AppConstants.TODO_ID_MISMATCH)); } // Perform the Edit operation else { // Database update int result = _repository.save(toDo); // return value and check the status and handle error if (result > 0) { statusCode = HttpStatusCode.OK; statusMessage = AppConstants.Success; } else { statusCode = HttpStatusCode.InternalServerError; statusMessage = AppConstants.Error; errorlist.Add(new Error(AppConstants.SAVE_FAILED_MSG, AppConstants.SAVE_FAILED)); } } } catch (DbUpdateConcurrencyException dbEx) { // If the Id for Deletion is not present in the database if (!ToDoIdExists(id)) { statusCode = HttpStatusCode.NotFound; statusMessage = AppConstants.Error; string strErrorMsg = AppConstants.Error_Message + dbEx.Message; errorlist.Add(new Error(strErrorMsg, AppConstants.TODO_NOT_FOUND)); Logger.WriteLog(AppConstants.Error_Message + strErrorMsg + AppConstants.Inner_Exception + dbEx.InnerException + AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source); } else { // This will be caught and handled in the ToDoCustomException handler throw; } } //Write to log file if error is present if (errorlist.Count > 0) { errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in PutToDo() for ID : " + id + AppConstants.Error_Code + error.errorCode + AppConstants.Error_Message + error.errorMessage)); } responseHeader.statusCode = statusCode; responseHeader.statusMessage = statusMessage; responseHeader.error = errorlist; todoResponse.responseHeader = responseHeader; responseBody.todo = _repository.getAllTodo(); todoResponse.responseBody = responseBody; return(todoResponse); }
[HttpPost] // Routing by explicitly specifying the HTTP Action type in the header public TodoResponse AddNewToDo(ToDo toDo) { TodoResponse todoResponse = new TodoResponse(); ResponseHeader responseHeader = new ResponseHeader(); ResponseBody responseBody = new ResponseBody(); HttpStatusCode statusCode; List <Error> errorlist = new List <Error>(); string statusMessage = string.Empty; errorlist = ValidateUtility.ValidateInput(toDo); try { if (!ModelState.IsValid) { statusCode = HttpStatusCode.BadRequest; statusMessage = AppConstants.Error; errorlist.Add(new Error(AppConstants.MODAL_STATE_INVALID, AppConstants.BAD_REQUEST)); } //Check if any of the input parameters are empty else if (errorlist.Count > 0) { statusCode = HttpStatusCode.BadRequest; statusMessage = AppConstants.Error; errorlist.ForEach(e => Logger.WriteLog(e.errorMessage)); } else { // Check if the item with same descrition is already present if (ValidateUtility.ToDoExists(_repository.getAllTodo(), toDo)) { statusCode = HttpStatusCode.Conflict; statusMessage = AppConstants.Error; Error error = new Error(AppConstants.TODO_ALREADY_EXIST_MSG, AppConstants.TODO_ALREADY_EXIST); errorlist.Add(error); Logger.WriteLog(AppConstants.TODO_ALREADY_EXIST_MSG); } //If item not present, then insert new data else { // return value and check the status and handle error // Database insertion takes place here if (_repository.insert(toDo) > 0) { statusCode = HttpStatusCode.OK; statusMessage = AppConstants.Success; } // If database insertion failed then handle the exception else { statusCode = HttpStatusCode.InternalServerError; statusMessage = AppConstants.Error; errorlist.Add(new Error(AppConstants.INSERT_FAILED_MSG, AppConstants.INSERT_FAILED)); } } } } catch (DbUpdateException dbEx) { //If To Do item is already present in database with same id if (ToDoIdExists(toDo.SlNo)) { statusCode = HttpStatusCode.Conflict; statusMessage = AppConstants.Error; string strErrorMsg = AppConstants.Error_Message + dbEx.Message + AppConstants.Inner_Exception + dbEx.InnerException + AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source; Error error = new Error(AppConstants.TODO_ALREADY_EXIST_MSG, AppConstants.TODO_ALREADY_EXIST); errorlist.Add(error); Logger.WriteLog(strErrorMsg); } else { statusCode = HttpStatusCode.InternalServerError; statusMessage = AppConstants.Error; string strErrorMsg = AppConstants.Error_Message + dbEx.Message; errorlist.Add(new Error(AppConstants.INTERNAL_SERVER_ERROR_MSG, AppConstants.INTERNAL_SERVER_ERROR)); Logger.WriteLog(AppConstants.Error_Message + strErrorMsg + AppConstants.Inner_Exception + dbEx.InnerException + AppConstants.Stack_Trace + dbEx.StackTrace + AppConstants.Soure + dbEx.Source); } } //Write to log file if error is present if (errorlist.Count > 0) { //foreach (var error in errorlist) //{ // Logger.WriteLog(AppConstants.Error + " in PostToDo() " +AppConstants.Error_Code // + error.errorCode + AppConstants.Error_Message + error.errorMessage); //} errorlist.ForEach(error => Logger.WriteLog(AppConstants.Error + " in PostToDo() " + AppConstants.Error_Code + error.errorCode + AppConstants.Error_Message + error.errorMessage)); } responseHeader.statusCode = statusCode; responseHeader.statusMessage = statusMessage; responseHeader.error = errorlist; todoResponse.responseHeader = responseHeader; responseBody.todo = _repository.getAllTodo(); todoResponse.responseBody = responseBody; return(todoResponse); }
/// <summary> /// Finds an element identified by the path from the root. /// </summary> private AeBrowseElement Find(Session session, string itemId, AeBrowseElement root, Stack <string> names, bool isArea) { string browseText = null; BrowsePath browsePath = new BrowsePath(); browsePath.StartingNode = root.NodeId; while (names.Count > 0) { RelativePathElement path = new RelativePathElement(); path.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasNotifier; path.IsInverse = false; path.IncludeSubtypes = true; // final hop can be HasEventSource for sources. if (!isArea && names.Count == 1) { path.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasEventSource; } browseText = names.Pop(); path.TargetName = m_mapper.GetRemoteBrowseName(browseText); browsePath.RelativePath.Elements.Add(path); } BrowsePathCollection browsePaths = new BrowsePathCollection(); browsePaths.Add(browsePath); // make the call to the server. BrowsePathResultCollection results; DiagnosticInfoCollection diagnosticInfos; ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds( null, browsePaths, out results, out diagnosticInfos); // ensure that the server returned valid results. Session.ValidateResponse(results, browsePaths); Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths); // check if the start node actually exists. if (StatusCode.IsBad(results[0].StatusCode)) { return(null); } // must be exact one target. if (results[0].Targets.Count != 1) { return(null); } // can't be an external reference. BrowsePathTarget target = results[0].Targets[0]; if (target.RemainingPathIndex != UInt32.MaxValue) { return(null); } // need to check if at the end of the tree. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = (NodeId)target.TargetId; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasEventSource; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.IncludeSubtypes = true; ReferenceDescriptionCollection children = ComAeUtils.Browse(session, nodeToBrowse, false); if (!isArea) { if (children != null && children.Count > 0) { return(null); } } else { if (children == null || children.Count == 0) { return(null); } } // construct the element. AeBrowseElement element = new AeBrowseElement(); element.NodeId = (NodeId)target.TargetId; element.ItemId = itemId; element.BrowseText = browseText; element.IsArea = isArea; return(element); }
/// <summary> /// Worker function to browse the full address space of a server. /// </summary> /// <param name="services">The service interface.</param> /// <param name="operationLimits">The operation limits.</param> public static ReferenceDescriptionCollection BrowseFullAddressSpaceWorker( IServerTestServices services, RequestHeader requestHeader, OperationLimits operationLimits = null, BrowseDescription browseDescription = null) { operationLimits = operationLimits ?? new OperationLimits(); requestHeader.Timestamp = DateTime.UtcNow; // Browse template var startingNode = Objects.RootFolder; var browseTemplate = browseDescription ?? new BrowseDescription { NodeId = startingNode, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, NodeClassMask = 0, ResultMask = (uint)BrowseResultMask.All }; var browseDescriptionCollection = ServerFixtureUtils.CreateBrowseDescriptionCollectionFromNodeId( new NodeIdCollection(new NodeId[] { Objects.RootFolder }), browseTemplate); // Browse ResponseHeader response = null; uint requestedMaxReferencesPerNode = operationLimits.MaxNodesPerBrowse; bool verifyMaxNodesPerBrowse = operationLimits.MaxNodesPerBrowse > 0; var referenceDescriptions = new ReferenceDescriptionCollection(); // Test if server responds with BadNothingToDo { var sre = Assert.Throws <ServiceResultException>(() => _ = services.Browse(requestHeader, null, 0, browseDescriptionCollection.Take(0).ToArray(), out var results, out var infos)); Assert.AreEqual(StatusCodes.BadNothingToDo, sre.StatusCode); } while (browseDescriptionCollection.Any()) { BrowseResultCollection allResults = new BrowseResultCollection(); if (verifyMaxNodesPerBrowse && browseDescriptionCollection.Count > operationLimits.MaxNodesPerBrowse) { verifyMaxNodesPerBrowse = false; // Test if server responds with BadTooManyOperations var sre = Assert.Throws <ServiceResultException>(() => _ = services.Browse(requestHeader, null, 0, browseDescriptionCollection, out var results, out var infos)); Assert.AreEqual(StatusCodes.BadTooManyOperations, sre.StatusCode); // Test if server responds with BadTooManyOperations var tempBrowsePath = browseDescriptionCollection.Take((int)operationLimits.MaxNodesPerBrowse + 1).ToArray(); sre = Assert.Throws <ServiceResultException>(() => _ = services.Browse(requestHeader, null, 0, tempBrowsePath, out var results, out var infos)); Assert.AreEqual(StatusCodes.BadTooManyOperations, sre.StatusCode); } bool repeatBrowse; var maxNodesPerBrowse = operationLimits.MaxNodesPerBrowse; BrowseResultCollection browseResultCollection = new BrowseResultCollection(); DiagnosticInfoCollection diagnosticsInfoCollection; do { var browseCollection = (maxNodesPerBrowse == 0) ? browseDescriptionCollection : browseDescriptionCollection.Take((int)maxNodesPerBrowse).ToArray(); repeatBrowse = false; try { requestHeader.Timestamp = DateTime.UtcNow; response = services.Browse(requestHeader, null, requestedMaxReferencesPerNode, browseCollection, out browseResultCollection, out diagnosticsInfoCollection); ServerFixtureUtils.ValidateResponse(response); ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticsInfoCollection, browseCollection); allResults.AddRange(browseResultCollection); } catch (ServiceResultException sre) { if (sre.StatusCode == StatusCodes.BadEncodingLimitsExceeded || sre.StatusCode == StatusCodes.BadResponseTooLarge) { // try to address by overriding operation limit maxNodesPerBrowse = maxNodesPerBrowse == 0 ? (uint)browseCollection.Count / 2 : maxNodesPerBrowse / 2; repeatBrowse = true; } else { throw; } } } while (repeatBrowse); if (maxNodesPerBrowse == 0) { browseDescriptionCollection.Clear(); } else { browseDescriptionCollection = browseDescriptionCollection.Skip((int)maxNodesPerBrowse).ToArray(); } // Browse next var continuationPoints = ServerFixtureUtils.PrepareBrowseNext(browseResultCollection); while (continuationPoints.Any()) { requestHeader.Timestamp = DateTime.UtcNow; response = services.BrowseNext(requestHeader, false, continuationPoints, out var browseNextResultCollection, out diagnosticsInfoCollection); ServerFixtureUtils.ValidateResponse(response); ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticsInfoCollection, continuationPoints); allResults.AddRange(browseNextResultCollection); continuationPoints = ServerFixtureUtils.PrepareBrowseNext(browseNextResultCollection); } // Build browse request for next level var browseTable = new NodeIdCollection(); foreach (var result in allResults) { referenceDescriptions.AddRange(result.References); foreach (var reference in result.References) { browseTable.Add(ExpandedNodeId.ToNodeId(reference.NodeId, null)); } } browseDescriptionCollection = ServerFixtureUtils.CreateBrowseDescriptionCollectionFromNodeId(browseTable, browseTemplate); } referenceDescriptions.Sort((x, y) => (x.NodeId.CompareTo(y.NodeId))); TestContext.Out.WriteLine("Found {0} references on server.", referenceDescriptions.Count); foreach (var reference in referenceDescriptions) { TestContext.Out.WriteLine("NodeId {0} {1} {2}", reference.NodeId, reference.NodeClass, reference.BrowseName); } return(referenceDescriptions); }
public Triple Get_TipOffsets(int station) { SendCommand("N" + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'N') throw new PolhemusException(0xF3); if (currentHeader.Station != station) throw new PolhemusException(0xF5); Triple co = new Triple(); if (_format == Format.ASCII) { co = Triple.FromASCII(TReader, "Sx.xxxB"); parseASCIIStream("<>"); } else { if (currentHeader.Length != 12) throw new PolhemusException(0xF2); co = new Triple(BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle()); } return co; }
/// <summary> /// Returns the node ids for a set of relative paths. /// </summary> /// <param name="session">An open session with the server to use.</param> /// <param name="startNodeId">The starting node for the relative paths.</param> /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param> /// <param name="relativePaths">The relative paths.</param> /// <returns>A collection of local nodes.</returns> public static List <NodeId> TranslateBrowsePaths( Session session, NodeId startNodeId, NamespaceTable namespacesUris, params string[] relativePaths) { // build the list of browse paths to follow by parsing the relative paths. BrowsePathCollection browsePaths = new BrowsePathCollection(); if (relativePaths != null) { for (int ii = 0; ii < relativePaths.Length; ii++) { BrowsePath browsePath = new BrowsePath(); // The relative paths used indexes in the namespacesUris table. These must be // converted to indexes used by the server. An error occurs if the relative path // refers to a namespaceUri that the server does not recognize. // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object // allows the parser to look up the server's NodeId for the ReferenceType. browsePath.RelativePath = RelativePath.Parse( relativePaths[ii], session.TypeTree, namespacesUris, session.NamespaceUris); browsePath.StartingNode = startNodeId; browsePaths.Add(browsePath); } } // make the call to the server. BrowsePathResultCollection results; DiagnosticInfoCollection diagnosticInfos; ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds( null, browsePaths, out results, out diagnosticInfos); // ensure that the server returned valid results. Session.ValidateResponse(results, browsePaths); Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths); // collect the list of node ids found. List <NodeId> nodes = new List <NodeId>(); for (int ii = 0; ii < results.Count; ii++) { // check if the start node actually exists. if (StatusCode.IsBad(results[ii].StatusCode)) { nodes.Add(null); continue; } // an empty list is returned if no node was found. if (results[ii].Targets.Count == 0) { nodes.Add(null); continue; } // Multiple matches are possible, however, the node that matches the type model is the // one we are interested in here. The rest can be ignored. BrowsePathTarget target = results[ii].Targets[0]; if (target.RemainingPathIndex != UInt32.MaxValue) { nodes.Add(null); continue; } // The targetId is an ExpandedNodeId because it could be node in another server. // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId. nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris)); } // return whatever was found. return(nodes); }
/// <summary> /// Processes the response from a publish request. /// </summary> private void ProcessPublishResponse( ResponseHeader responseHeader, uint subscriptionId, UInt32Collection availableSequenceNumbers, bool moreNotifications, NotificationMessage notificationMessage) { Subscription subscription = null; // send notification that the server is alive. OnKeepAlive(m_serverState, responseHeader.Timestamp); // collect the current set if acknowledgements. lock (SyncRoot) { // clear out acknowledgements for messages that the server does not have any more. SubscriptionAcknowledgementCollection acknowledgementsToSend = new SubscriptionAcknowledgementCollection(); for (int ii = 0; ii < m_acknowledgementsToSend.Count; ii++) { SubscriptionAcknowledgement acknowledgement = m_acknowledgementsToSend[ii]; if (acknowledgement.SubscriptionId != subscriptionId) { acknowledgementsToSend.Add(acknowledgement); } else { if (availableSequenceNumbers == null || availableSequenceNumbers.Contains(acknowledgement.SequenceNumber)) { acknowledgementsToSend.Add(acknowledgement); } } } // create an acknowledgement to be sent back to the server. if (notificationMessage.NotificationData.Count > 0) { SubscriptionAcknowledgement acknowledgement = new SubscriptionAcknowledgement(); acknowledgement.SubscriptionId = subscriptionId; acknowledgement.SequenceNumber = notificationMessage.SequenceNumber; acknowledgementsToSend.Add(acknowledgement); } uint lastSentSequenceNumber = 0; if (availableSequenceNumbers != null) { foreach (uint availableSequenceNumber in availableSequenceNumbers) { if (m_latestAcknowledgementsSent.ContainsKey(subscriptionId)) { lastSentSequenceNumber = m_latestAcknowledgementsSent[subscriptionId]; // If the last sent sequence number is uint.Max do not display the warning; the counter rolled over // If the last sent sequence number is greater or equal to the available sequence number (returned by the publish), a warning must be logged. if (((lastSentSequenceNumber >= availableSequenceNumber) && (lastSentSequenceNumber != uint.MaxValue)) || (lastSentSequenceNumber == availableSequenceNumber) && (lastSentSequenceNumber == uint.MaxValue)) { Utils.Trace("Received sequence number which was already acknowledged={0}", availableSequenceNumber); } } } } if (m_latestAcknowledgementsSent.ContainsKey(subscriptionId)) { lastSentSequenceNumber = m_latestAcknowledgementsSent[subscriptionId]; // If the last sent sequence number is uint.Max do not display the warning; the counter rolled over // If the last sent sequence number is greater or equal to the notificationMessage's sequence number (returned by the publish), a warning must be logged. if (((lastSentSequenceNumber >= notificationMessage.SequenceNumber) && (lastSentSequenceNumber != uint.MaxValue)) || (lastSentSequenceNumber == notificationMessage.SequenceNumber) && (lastSentSequenceNumber == uint.MaxValue)) { Utils.Trace("Received sequence number which was already acknowledged={0}", notificationMessage.SequenceNumber); } } if (availableSequenceNumbers != null) { foreach (var acknowledgement in acknowledgementsToSend) { if (acknowledgement.SubscriptionId == subscriptionId && !availableSequenceNumbers.Contains(acknowledgement.SequenceNumber)) { Utils.Trace("Sequence number={0} was not received in the available sequence numbers.", acknowledgement.SequenceNumber); } } } m_acknowledgementsToSend = acknowledgementsToSend; if (notificationMessage.IsEmpty) { Utils.Trace("Empty notification message received for SessionId {0} with PublishTime {1}", SessionId, notificationMessage.PublishTime.ToLocalTime()); } // find the subscription. foreach (Subscription current in m_subscriptions) { if (current.Id == subscriptionId) { subscription = current; break; } } } // ignore messages with a subscription that has been deleted. if (subscription != null) { // Validate publish time and reject old values. if (notificationMessage.PublishTime.AddMilliseconds(subscription.CurrentPublishingInterval * subscription.CurrentLifetimeCount) < DateTime.UtcNow) { Utils.Trace("PublishTime {0} in publish response is too old for SubscriptionId {1}.", notificationMessage.PublishTime.ToLocalTime(), subscription.Id); } // Validate publish time and reject old values. if (notificationMessage.PublishTime > DateTime.UtcNow.AddMilliseconds(subscription.CurrentPublishingInterval * subscription.CurrentLifetimeCount)) { Utils.Trace("PublishTime {0} in publish response is newer than actual time for SubscriptionId {1}.", notificationMessage.PublishTime.ToLocalTime(), subscription.Id); } // update subscription cache. subscription.SaveMessageInCache( availableSequenceNumbers, notificationMessage, responseHeader.StringTable); // raise the notification. lock (m_eventLock) { NotificationEventArgs args = new NotificationEventArgs(subscription, notificationMessage, responseHeader.StringTable); if (m_Publish != null) { ThreadPool.QueueUserWorkItem(OnRaisePublishNotification, args); } } } else { Utils.Trace("Received Publish Response for Unknown SubscriptionId={0}", subscriptionId); } }
private async Task <Packet> ProcessPacket(byte[] data) { string str = Encoding.UTF8.GetString(data); if (Regex.IsMatch(str, "^GET")) { requestHeader = new RequestHeader(str); requestHeader.resource = requestHeader.resource.Replace("/csf-websocket-url", ""); Logger.Info($"Requesting resource: {requestHeader.resource}"); string ip1 = tcpclient.Client.RemoteEndPoint.ToString(); string[] ip_parts = ip1.Split("."); Logger.Info($"IP: {ip1}"); Logger.Debug($"Recieved header: {str}"); if (ip_parts[0] != "172" && ip_parts[0] != "127") { ResponseHeader respheader = new ResponseHeader { responseCode = HttpCodes.OK }; await Send(respheader); await Send("Hello World!"); stillOk = false; } else if (requestHeader.parameters.ContainsKey("Sec-WebSocket-Key")) { ResponseHeader respheader = new ResponseHeader { responseCode = HttpCodes.SwitchingProtocols }; respheader.parameters["Server"] = "CSF-Websocket"; respheader.parameters["Connection"] = "Upgrade"; respheader.parameters["Upgrade"] = "websocket"; respheader.parameters["Sec-WebSocket-Accept"] = GenerateSecWebSocketKey(requestHeader.parameters["Sec-WebSocket-Key"]); try { if (requestHeader.parameters.ContainsKey("Sec-WebSocket-Extensions")) { Logger.Info($"Supported extensions: {requestHeader.parameters["Sec-WebSocket-Extensions"]}"); Chiper = StreamCipher.Factory(requestHeader.parameters["Sec-WebSocket-Extensions"]); } else { Chiper = StreamCipher.Factory("permessage-deflate"); } if (requestHeader.parameters.ContainsKey("Sec-WebSocket-Protocol")) { string[] options = requestHeader.parameters["Sec-WebSocket-Protocol"].Split(","); foreach (string option_raw in options) { string option = option_raw.Trim(); if (option.Contains("csf-socket-")) { respheader.parameters["Sec-WebSocket-Protocol"] = option; } } } await Send(respheader); await SendHello(); } catch (UnsupportedExtension) { ResponseHeader invext = new ResponseHeader { responseCode = HttpCodes.NotAcceptable }; await Send(invext); await Send("The requested websokcet extension is not supported"); stillOk = false; } } else { ResponseHeader respheader = new ResponseHeader { responseCode = HttpCodes.UpgradeRequired }; await Send(respheader); await Send("This is not a website! Upgrade your connection to WebSocket"); stillOk = false; } } else { WsPacket WebSocketPacket = Chiper.Decode(data); OpCode opcode = WebSocketPacket.GetOpCode(); if (opcode == OpCode.TextFrame) { string pstr = WebSocketPacket.GetPayload(); try { Packet p = new Packet(pstr); PacketType type = p.GetPacketType(); if (type == PacketType.Heartbeat) { HeartBeatNow(); Packet ack = new Packet(PacketType.HeartbeatACK); await Send(ack); return(null); } else if (type == PacketType.Reconnect) { Reconnect rp = p.GetPacketData <Reconnect>(); if (UsedSessions.Contains(rp.session_id)) { this.session = rp.session_id; await SendHello(); } else { Packet invsess = new Packet(PacketType.InvalidSession); await Send(invsess); stillOk = false; } return(null); } else if (type == PacketType.Identify) { identity = p.GetPacketData <Identity>(); } else { if (identity == null) { stillOk = false; return(null); } } return(p); } catch (Exception e) { Logger.Error($"Packet conversion error: {e.Message}"); Logger.Error($"Receied data: {string.Join(" ", data)}"); Logger.Error($"Decoded: {pstr}"); Logger.Error($"{e.StackTrace}"); } } else if (opcode == OpCode.Ping) { Logger.Debug("Ping Pong"); WsPacket pong = new WsPacket(OpCode.Pong); await Send(pong); } } return(null); }
/// <summary> /// Sets the MIME type in the response header based on the file requested. See /// <see cref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types "/> for /// a list of MIME types /// </summary> /// <param name="file"></param> /// <param name="header"></param> private void SetMimeType(string file, ResponseHeader header) { //PA3 TODO: Set mime type based on file extension header.ContentType = ContentType.HTML; }
/// <summary> /// This method executes a scalar values test. /// </summary> /// <param name="channelContext">This parameter stores the channel related data.</param> /// <param name="testCaseContext">This parameter stores the test case parameter values.</param> /// <param name="testCase">This parameter stores the test case related data.</param> /// <param name="iteration">This parameter stores the current iteration number.</param> /// <remarks> /// The test parameters required for this test case are of the /// following types: /// <list type="bullet"> /// <item>MinTimeout <see cref="TestCaseContext.MinTimeout"/></item> /// <item>MaxTimeout <see cref="TestCaseContext.MaxTimeout"/></item> /// <item>MaxStringLength <see cref="TestCaseContext.MaxStringLength"/></item> /// <item>MaxTransportDelay <see cref="TestCaseContext.MaxTransportDelay"/></item> /// </list> /// </remarks> private void ExecuteTest_ServerTimout(ChannelContext channelContext, TestCaseContext testCaseContext, TestCase testCase, int iteration) { bool isSetupStep = TestUtils.IsSetupIteration(iteration); if (!isSetupStep) { channelContext.EventLogger.LogStartEvent(testCase, iteration); } isSetupStep = TestUtils.IsSetupIteration(iteration); RequestHeader requestHeader = new RequestHeader(); requestHeader.Timestamp = DateTime.UtcNow; requestHeader.ReturnDiagnostics = (uint)DiagnosticsMasks.All; Variant input; Variant output; if (isSetupStep) { input = Variant.Null; ResponseHeader responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); } else { int serverSleepTime = 0; DateTime startTime = DateTime.UtcNow; try { channelContext.Random.Start( (int)(testCase.Seed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); input = channelContext.Random.GetScalarVariant(false); // Server's sleep time serverSleepTime = channelContext.Random.GetTimeout(); channelContext.ClientSession.OperationTimeout = serverSleepTime - 100; ResponseHeader responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); channelContext.EventLogger.LogErrorEvent(testCase, iteration, new Exception("Test failed. Expected a TimeoutException, but did not occur.")); return; } catch (Exception e) { ServiceResultException sre = e as ServiceResultException; if (e is TimeoutException || (sre != null && sre.StatusCode == StatusCodes.BadRequestTimeout)) { // This indicates that Stack did timeout the request. } else { throw e; } } TimeSpan timeSpent = DateTime.UtcNow.Subtract(startTime); if (timeSpent.TotalMilliseconds > serverSleepTime * 1.10) { channelContext.EventLogger.LogErrorEvent(testCase, iteration, new Exception("Test failed. Timeout took too long.")); return; } } if (!isSetupStep) { channelContext.EventLogger.LogCompleteEvent(testCase, iteration); } }
public void SubscribeToStream(string streamName, Type feedClass, int feedPayload, int feedInterval, string feedDefaultId) { var clientContext = Context?.ClientContext; clientContext?.WhenClosing(UnsubscribeRequest() !); var correlationId = Context?.Request?.HeaderValueOr(RequestHeader.XCorrelationID, string.Empty); var subscriber = new SseSubscriber( streamName, new SseClient(clientContext), correlationId, Context?.Request?.HeaderValueOr(RequestHeader.LastEventID, string.Empty)); PublisherFor(streamName, feedClass, feedPayload, feedInterval, feedDefaultId).Subscribe(subscriber); Completes?.With(Response.Of(ResponseStatus.Ok, ResponseHeader.WithHeaders(ResponseHeader.WithCorrelationId(correlationId)))); }
public HttpResponse(ResponseHeader responseHeader) : base(responseHeader ?? new ResponseHeader()) { content = new Content(); }
public string[] Get_OperationalConfigurationID() { SendCommand('\u0018', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'x') throw new PolhemusException(0xF3); if (_format == Format.ASCII) { string[] ret = new string[4]; for (int i = 0; i < 4; i++) ret[i] = ((string)parseASCIIStream("AAAAAAAAAAAAAAAAB")).Trim(); parseASCIIStream("<>"); return ret; } else { string[] ret = new string[6]; char[] c = new char[16]; for (int i = 0; i < 6; i++) { c = BReader.ReadChars(16); ret[i] = (new string(c)).Trim(); } return ret; } }
public HttpResponse(ResponseHeader responseHeader, Content content) : base(responseHeader ?? new ResponseHeader()) { this.content = content ?? new Content(); }
public Format Get_OutputFormat() { SendCommand('F', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'F') throw new PolhemusException(0xF3); Format f; if (_format == Format.ASCII) { string s = TReader.ReadLine(); f = s == "0" ? Format.ASCII : Format.Binary; } else { if (currentHeader.Length != 4) throw new PolhemusException(0xF2); f = BReader.ReadInt32() == 0 ? Format.ASCII : Format.Binary; } if (f != _format) throw new PolhemusException(0xF4); return f; }
public static byte[] Serialize(Content content, ResponseHeader responseHeader) { return(System.Text.Encoding.UTF8.GetBytes(HeaderToString(responseHeader) + $"content-length: {content.ContentLength}\r\n\r\n").Append(content.ContentBytes)); }
public void Get_RS232PortConfiguration(out int baudRate, out Parity parity) { SendCommand('\u000F', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'o') throw new PolhemusException(0xF3); if (_format == Format.ASCII) { baudRate = Convert.ToInt32((string)parseASCIIStream("AAAAAAB")) * 100; parity = (Parity)Convert.ToInt32((string)parseASCIIStream("A<>")); } else { baudRate = BREncoding[BReader.ReadInt32() - 1]; parity = (Parity)BReader.ReadInt32(); } }
/// <summary> /// Fetches the references for the node. /// </summary> private List <ReferenceDescription> Browse(Session session, NodeId nodeId) { List <ReferenceDescription> references = new List <ReferenceDescription>(); // specify the references to follow and the fields to return. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.References; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.BrowseDirection = BrowseDirection.Both; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = session.Browse( null, null, 2, nodesToBrowse, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add first batch. references.AddRange(results[0].References); // check if server limited the results. while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); // continue browse operation. responseHeader = session.BrowseNext( null, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add next batch. references.AddRange(results[0].References); } return(references); }
public Units Get_SetUnits() { SendCommand('U', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'U') throw new PolhemusException(0xF3); Units u; if (_format == Format.ASCII) { string s = TReader.ReadLine(); u = s == "0" ? Units.English : Units.Metric; } else { if (currentHeader.Length != 4) throw new PolhemusException(0xF2); u = BReader.ReadInt32() == 0 ? Units.English : Units.Metric; } if (u != _units) throw new PolhemusException(0xF4); return u; }
public async Task HandlePushFileAsync(IAsyncStreamReader <PushFileRequest> requestStream, IServerStreamWriter <PushFileResponse> responseStream, ServerCallContext callContext) { OperationStarted(); // Detaching from the calling thread to (potentially) avoid IO Completion port thread exhaustion await Task.Yield(); var startTime = DateTime.UtcNow; var pushRequest = PushRequest.FromMetadata(callContext.RequestHeaders); var hash = pushRequest.Hash; var cacheContext = new Context(pushRequest.TraceId, Logger); var token = callContext.CancellationToken; var store = _contentStoreByCacheName.Values.OfType <IPushFileHandler>().FirstOrDefault(); if (!CanHandlePushRequest(cacheContext, hash, store)) { await callContext.WriteResponseHeadersAsync(PushResponse.DoNotCopy.Metadata); return; } try { // Running the logic inside try/finally block to remove the hash being processed regardless of the result of this method. await callContext.WriteResponseHeadersAsync(PushResponse.Copy.Metadata); PutResult?result = null; using (var disposableFile = new DisposableFile(cacheContext, _fileSystem, _temporaryDirectory !.CreateRandomFileName())) { // NOTE(jubayard): DeleteOnClose not used here because the file needs to be placed into the CAS. // Opening a file for read/write and then doing pretty much anything to it leads to weird behavior // that needs to be tested on a case by case basis. Since we don't know what the underlying store // plans to do with the file, it is more robust to just use the DisposableFile construct. using (var tempFile = await _fileSystem.OpenSafeAsync(disposableFile.Path, FileAccess.Write, FileMode.CreateNew, FileShare.None)) { while (await requestStream.MoveNext()) { if (token.IsCancellationRequested) { return; } var request = requestStream.Current; var bytes = request.Content.ToByteArray(); await tempFile.WriteAsync(bytes, 0, bytes.Length, token); } } result = await store.HandlePushFileAsync(cacheContext, hash, disposableFile.Path, token); } var response = result ? new PushFileResponse { Header = ResponseHeader.Success(startTime) } : new PushFileResponse { Header = ResponseHeader.Failure(startTime, result.ErrorMessage) }; await responseStream.WriteAsync(response); } finally { _ongoingPushes.Remove(hash); } }
public StylusMode Get_StylusButtonFunction(int station) { SendCommand("L" + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'L') throw new PolhemusException(0xF3); if (currentHeader.Station != station) throw new PolhemusException(0xF5); StylusMode sm; if (_format == Format.ASCII) sm = TReader.ReadLine() == "0" ? StylusMode.Marker : StylusMode.PointTrack; else { if (currentHeader.Length != 4) throw new PolhemusException(0xF2); sm = BReader.ReadInt32() == 0 ? StylusMode.Marker : StylusMode.PointTrack; } if (sm != CurrentStylusMode(station)) throw new PolhemusException(0xF4); return sm; }
/// <summary> /// Creates the response header. /// </summary> /// <param name="requestHeader">The object that contains description for the RequestHeader DataType.</param> /// <param name="exception">The exception used to create DiagnosticInfo assigned to the ServiceDiagnostics.</param> /// <returns>Returns a description for the ResponseHeader DataType. </returns> protected virtual ResponseHeader CreateResponse(RequestHeader requestHeader, Exception exception) { ResponseHeader responseHeader = new ResponseHeader(); responseHeader.Timestamp = DateTime.UtcNow; responseHeader.RequestHandle = requestHeader.RequestHandle; StringTable stringTable = new StringTable(); responseHeader.ServiceDiagnostics = new DiagnosticInfo(exception, (DiagnosticsMasks)requestHeader.ReturnDiagnostics, true, stringTable); responseHeader.StringTable = stringTable.ToArray(); return responseHeader; }
/// <summary> /// Verifies the result of a publish /// </summary> private bool VerifyPublishResponse( ResponseHeader responseHeader, Subscription subscription, UInt32Collection availableSequenceNumbers, bool moreNotifications, NotificationMessage notificationMessage, StatusCodeCollection results, DiagnosticInfoCollection diagnosticInfos) { /* Utils.Trace( "PublishReceived: SubId={0} SeqNo={1}, PublishTime={2:mm:ss.fff}, Time={3:mm:ss.fff}", subscription.SubscriptionId, notificationMessage.SequenceNumber, notificationMessage.PublishTime, DateTime.UtcNow); */ // check if there is an odd delay. if (responseHeader.Timestamp > notificationMessage.PublishTime.AddMilliseconds(100)) { Log( "WARNING. Unexpected delay between PublishTime and ResponseTime. SeqNo={0}, PublishTime={1:hh:mm:ss.fff}, ResponseTime={2:hh:mm:ss.fff}", notificationMessage.SequenceNumber, notificationMessage.PublishTime, responseHeader.Timestamp); } // save results. subscription.AvailableSequenceNumbers = availableSequenceNumbers; if (notificationMessage.NotificationData.Count == 0) { // keep alives do not increment the sequence number. if (subscription.NextExpectedSequenceNumber != notificationMessage.SequenceNumber) { Log( "Incorrect sequence number for keep alive. SubscriptionId = {0}, Actual = {1}, Expected = {2}", subscription.SubscriptionId, notificationMessage.SequenceNumber, subscription.NextExpectedSequenceNumber); subscription.Failed = true; return false; } // save the message. DateTime timestamp = responseHeader.Timestamp; DateTime start = subscription.States[subscription.States.Count - 1].Start; // check if this is an old request being processed late. if (start > timestamp && subscription.States.Count > 1) { subscription.States[subscription.States.Count - 2].KeepAlives.Add(timestamp); } else { subscription.States[subscription.States.Count - 1].KeepAlives.Add(timestamp); } } else { // check for replays. if (subscription.NextExpectedSequenceNumber > notificationMessage.SequenceNumber) { // check for out of order responses. bool found = false; for (int ii = 0; ii < subscription.MissingSequenceNumbers.Count; ii++) { if (subscription.MissingSequenceNumbers[ii] == notificationMessage.SequenceNumber) { subscription.MissingSequenceNumbers.RemoveAt(ii); found = true; break; } } // oops - duplicate. if (!found) { Log( "Duplicate sequence number for message. SubscriptionId = {0}, Actual = {1}, Expected = {2}", subscription.SubscriptionId, notificationMessage.SequenceNumber, subscription.NextExpectedSequenceNumber); subscription.Failed = true; return false; } } // increment message counter. if (notificationMessage.SequenceNumber >= subscription.NextExpectedSequenceNumber) { for (uint ii = subscription.NextExpectedSequenceNumber; ii < notificationMessage.SequenceNumber; ii++) { if (!subscription.MissingSequenceNumbers.Contains(ii)) { subscription.MissingSequenceNumbers.Add(ii); } } subscription.NextExpectedSequenceNumber = notificationMessage.SequenceNumber+1; } // save the largest received message number (gap exist because of client side threading issues). if (subscription.LastReceivedSequenceNumber < notificationMessage.SequenceNumber) { subscription.LastReceivedSequenceNumber = notificationMessage.SequenceNumber; } // save the message. DateTime timestamp = responseHeader.Timestamp; DateTime start = subscription.States[subscription.States.Count-1].Start; // check if this is an old request being processed late. if (start > timestamp && subscription.States.Count > 1) { subscription.States[subscription.States.Count - 2].KeepAlives.Add(timestamp); } else { subscription.States[subscription.States.Count - 1].KeepAlives.Add(timestamp); } subscription.NotificationMessages.Add(notificationMessage); subscription.ReceiveTimes.Add(responseHeader.Timestamp); // change to keep alive mode. if (subscription.StaticData) { PublishingState state = new PublishingState(); state.KeepAliveCount = subscription.KeepAliveCount; state.PublishingInterval = subscription.PublishingInterval; state.Start = timestamp; state.KeepAliveMode = true; subscription.States[subscription.States.Count-1].End = state.Start; subscription.States.Add(state); } // save the acknowlegements. SaveAcknowledgement(subscription.SubscriptionId, notificationMessage.SequenceNumber); } return true; }
/// <summary> /// Calls the method. /// </summary> public void Call() { // build list of methods to call. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(); CallMethodRequest methodToCall = new CallMethodRequest(); methodToCall.ObjectId = m_objectId; methodToCall.MethodId = m_methodId; foreach (DataRow row in m_dataset.Tables[0].Rows) { Argument argument = (Argument)row[0]; Variant value = (Variant)row[4]; argument.Value = value.Value; methodToCall.InputArguments.Add(value); } methodsToCall.Add(methodToCall); // call the method. CallMethodResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_session.Call( null, methodsToCall, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, methodsToCall); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, methodsToCall); for (int ii = 0; ii < results.Count; ii++) { // display any input argument errors. if (results[ii].InputArgumentResults != null) { for (int jj = 0; jj < results[ii].InputArgumentResults.Count; jj++) { if (StatusCode.IsBad(results[ii].InputArgumentResults[jj])) { DataRow row = m_dataset.Tables[0].Rows[jj]; row[5] = results[ii].InputArgumentResults[jj].ToString(); ResultCH.Visible = true; } } } // throw an exception on error. if (StatusCode.IsBad(results[ii].StatusCode)) { throw ServiceResultException.Create(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable); } // display the output arguments ResultCH.Visible = false; NoArgumentsLB.Visible = m_outputArguments == null || m_outputArguments.Length == 0; NoArgumentsLB.Text = "Method invoked successfully.\r\nNo output arguments to display."; m_dataset.Tables[0].Rows.Clear(); if (m_outputArguments != null) { for (int jj = 0; jj < m_outputArguments.Length; jj++) { DataRow row = m_dataset.Tables[0].NewRow(); if (results[ii].OutputArguments.Count > jj) { UpdateRow(row, m_outputArguments[jj], results[ii].OutputArguments[jj], true); } else { UpdateRow(row, m_outputArguments[jj], Variant.Null, true); } m_dataset.Tables[0].Rows.Add(row); } } } }
/// <summary> /// ReplicationStatusResponse constructor /// </summary> /// <param name="ResponseHeader">response header</param> /// <param name="Status">status</param> /// <param name="Message">message</param> public ReplicationStatusResponse(ResponseHeader ResponseHeader, string Status, string Message) { responseHeader = ResponseHeader; status = Status; message = Message; }
/// <summary> /// Updates the object with the results of a modify monitored item request. /// </summary> public void SetModifyResult( MonitoredItemModifyRequest request, MonitoredItemModifyResult result, int index, DiagnosticInfoCollection diagnosticInfos, ResponseHeader responseHeader) { ServiceResult error = null; if (StatusCode.IsBad(result.StatusCode)) { error = ClientBase.GetResult(result.StatusCode, index, diagnosticInfos, responseHeader); } m_status.SetModifyResult(request, result, error); m_attributesModified = false; }
/// <summary> /// Creates the response header. /// </summary> /// <param name="requestHeader">The object that contains description for the RequestHeader DataType.</param> /// <param name="statusCode">The status code.</param> /// <exception cref="ServiceResultException">If statusCode is bad.</exception> /// <returns>Returns a description for the ResponseHeader DataType. </returns> protected virtual ResponseHeader CreateResponse(RequestHeader requestHeader, uint statusCode) { if (StatusCode.IsBad(statusCode)) { throw new ServiceResultException(statusCode); } ResponseHeader responseHeader = new ResponseHeader(); responseHeader.Timestamp = DateTime.UtcNow; responseHeader.RequestHandle = requestHeader.RequestHandle; return responseHeader; }
/// <summary> /// Creates the response header. /// </summary> /// <param name="requestHeader">The object that contains description for the RequestHeader DataType.</param> /// <param name="stringTable">The thread safe table of string constants.</param> /// <returns>Returns a description for the ResponseHeader DataType. </returns> protected virtual ResponseHeader CreateResponse(RequestHeader requestHeader, StringTable stringTable) { ResponseHeader responseHeader = new ResponseHeader(); responseHeader.Timestamp = DateTime.UtcNow; responseHeader.RequestHandle = requestHeader.RequestHandle; responseHeader.StringTable.AddRange(stringTable.ToArray()); return responseHeader; }
public void Get_ActiveStationState(int station, out byte return1, out byte return2) { SendCommand('\u0015' + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'u') throw new PolhemusException(0xF3); if (_format == Format.ASCII) { return1 = (byte)parseASCIIStream(station == 0 ? "XXXX" : "X"); return2 = (byte)parseASCIIStream(station == 0 ? "XXXX<>" : "X<>"); } else { uint v = BReader.ReadUInt32(); return1 = (byte)(v & 0xFF); return2 = (byte)(v >> 16); } }
/// <summary> /// Updates the object with the results of a translate browse path request. /// </summary> public void SetResolvePathResult( BrowsePathResult result, int index, DiagnosticInfoCollection diagnosticInfos, ResponseHeader responseHeader) { ServiceResult error = null; if (StatusCode.IsBad(result.StatusCode)) { error = ClientBase.GetResult(result.StatusCode, index, diagnosticInfos, responseHeader); } else { ResolvedNodeId = NodeId.Null; // update the node id. if (result.Targets.Count > 0) { ResolvedNodeId = ExpandedNodeId.ToNodeId(result.Targets[0].TargetId, m_subscription.Session.NamespaceUris); } } m_status.SetResolvePathResult(result, error); }
public Triple[] Get_AlignmentReferenceFrame() { SendCommand('A', false); currentHeader = ReadHeader(); if (currentHeader.Command != 'A') throw new PolhemusException(0xF3); Triple[] cc = new Triple[3]; if (_format == Format.ASCII) { for (int i = 0; i < 3; i++) cc[i] = Triple.FromASCII(TReader, "Sxxx.xx"); } else { if (currentHeader.Length != 36) throw new PolhemusException(0xF2); for (int i = 0; i < 3; i++) cc[i] = new Triple(BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle()); } return cc; }
/// <summary> /// Updates the object with the results of a modify monitored item request. /// </summary> public void SetDeleteResult( StatusCode result, int index, DiagnosticInfoCollection diagnosticInfos, ResponseHeader responseHeader) { ServiceResult error = null; if (StatusCode.IsBad(result)) { error = ClientBase.GetResult(result, index, diagnosticInfos, responseHeader); } m_status.SetDeleteResult(error); }
public Triple Get_Boresight(int station) { SendCommand("B" + station.ToString("0"), false); currentHeader = ReadHeader(); if (currentHeader.Command != 'B') throw new PolhemusException(0xF3); Triple ra; if (_format == Format.ASCII) { ra = Triple.FromASCII(TReader, "Sxxx.xxB"); PolhemusController.parseASCIIStream(TReader, "<>"); } else { if (currentHeader.Length != 12) throw new PolhemusException(0xF2); ra = new Triple(BReader.ReadSingle(), BReader.ReadSingle(), BReader.ReadSingle()); } return ra; }
private bool ProcessResponseErrors(ResponseHeader objResponseHeader) { bool bErrors = false; if (!objResponseHeader.Success) { for (int i = 0; i < objResponseHeader.Errors.Length; i++) { ((XnGR_WBS_Page)Page).AddPageError(XnGR_WBS_Page.PageErrorType.WbsApiError, objResponseHeader.Errors[i].Code); bErrors = true; } } return bErrors; }
public void Log(ResponseHeader header, object?body, bool isSending) => Log("Response", header.RequestNo, header.MessageId, header.Flags.ToString(), body, isSending);