public void OnStatusChanged(StatusCode statusCode) { DebugReturn("OnStatusChanged():" + (StatusCode) statusCode); //handle returnCodes for connect, disconnect and errors (non-operations) switch ((StatusCode) statusCode) { case StatusCode.Connect: this.DebugReturn("Connect(ed)"); this.peer.OpJoin(this.lobbyName); // The LobbyHandler simply joins the lobby to get updates from it break; case StatusCode.Disconnect: this.DebugReturn("Disconnect(ed) Peer.state: " + peer.PeerState); break; case StatusCode.ExceptionOnConnect: this.DebugReturn("ExceptionOnConnect(ed) Peer.state: " + peer.PeerState); break; case StatusCode.Exception: this.DebugReturn("Exception(ed) Peer.state: " + peer.PeerState); break; default: this.DebugReturn("OnStatusChanged: " + statusCode); break; } }
public override void OnPeerStatusCallback(ClientConnection client, StatusCode returnCode) { switch (returnCode) { case StatusCode.DisconnectByServerUserLimit: case StatusCode.Disconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerLogic: case StatusCode.TimeoutDisconnect: { if (log.IsInfoEnabled) { log.InfoFormat("{0}", returnCode); } Counters.ConnectedClients.Decrement(); WindowsCounters.ConnectedClients.Decrement(); client.State = Disconnected.Instance; client.OnDisconnected(); break; } default: { log.WarnFormat("Connected: OnPeerStatusCallback: unexpected return code {0}", returnCode); break; } } }
/// <summary> /// Sends error page to the client /// </summary> /// <param name="statusCode">Status code</param> /// <param name="message">Error message</param> public void SendError(StatusCode statusCode, string message) { string page = GetErrorPage(statusCode, message); SendHeader("text/html", page.Length, statusCode); SendToClient(page); End(); }
/// <summary> /// ctor for product purchases /// </summary> public Receipt(Product product, StatusCode status, string storeReceipt) { PurchaseType = PurchaseType.Product; Product = product; Status = status; StoreReceipt = storeReceipt; }
/// <summary> /// The on peer status callback. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="returnCode"> /// The return code. /// </param> public void OnPeerStatusCallback(Game game, StatusCode returnCode) { switch (returnCode) { case StatusCode.Connect: { InterestArea camera; game.TryGetCamera(0, out camera); camera.ResetViewDistance(); game.Avatar.SetInterestAreaAttached(true); game.SetConnected(); //Operations.Authenticate(game, game.Avatar.Token); break; } case StatusCode.Disconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerLogic: case StatusCode.DisconnectByServerUserLimit: case StatusCode.TimeoutDisconnect: { game.SetDisconnected(returnCode); break; } default: { game.DebugReturn(DebugLevel.ERROR, returnCode.ToString()); break; } } }
public void OnStatusChanged(StatusCode statusCode) { Debug.Log("OnStatusChanged:" + statusCode.ToString()); switch (statusCode) { case StatusCode.Connect: stopwatch.Stop(); Debug.Log(string.Format("连线成功,耗时:{0}秒",stopwatch.Elapsed.TotalSeconds.ToString())); stopwatch.Reset(); break; case StatusCode.Disconnect: Debug.Log("断线"); break; case StatusCode.DisconnectByServerUserLimit: Debug.Log("人数达上线"); break; case StatusCode.ExceptionOnConnect: Debug.Log("连线时意外错误"); break; case StatusCode.DisconnectByServer: Debug.Log("被Server强制断线"); break; case StatusCode.TimeoutDisconnect: Debug.Log("超时断线"); break; case StatusCode.Exception: case StatusCode.ExceptionOnReceive: Debug.Log("其他例外"); break; } }
public Response(StatusCode code, string contentType, string content, string redirectoinPath) { // throw new NotImplementedException(); // TODO: Add headlines (Content-Type, Content-Length,Date, [location if there is redirection]) int content_length = content.Length; string content_length_string = content_length.ToString(); DateTime date = DateTime.Now; string date_string = date.ToString(); headerLines.Add("Content-Type"+ contentType); headerLines.Add("Content-Length"+ content_length_string); headerLines.Add("Date" + date_string); if (redirectoinPath!="") { headerLines.Add("Redirection Path" + redirectoinPath); } // TODO: Create the request string string status_line=GetStatusLine(code); string header_line = ""; for (int i = 0; i < headerLines.Count; i++) { header_line += headerLines[i]+ " "; } //header_line += "\r\n"; responseString = status_line + header_line + "\r\n" + content; }
private void Patrolling() { if (statusCode != StatusCode.Patrol) { statusCode = StatusCode.Patrol; nav.ResetPath(); } nav.speed = patrolSpeed; if (nav.destination == lastPlayerSighting.resetPosition || nav.remainingDistance < nav.stoppingDistance) { patrolTimer += Time.deltaTime; if (patrolTimer > patrolWaitTime) { if (wayPointIndex == patrolWayPoints.Length - 1) { wayPointIndex = 0; } else { wayPointIndex++; } patrolTimer = 0f; } } else { patrolTimer = 0f; } nav.destination = patrolWayPoints[wayPointIndex].position; }
/// <summary> /// Creates a response to the specified request with the specified response code. /// The destination endpoint of the response is the source endpoint of the request. /// The response has the same token as the request. /// Type and ID are usually set automatically by the <see cref="CoAP.Stack.ReliabilityLayer"/>. /// </summary> public static Response CreateResponse(Request request, StatusCode code) { Response response = new Response(code); response.Destination = request.Source; response.Token = request.Token; return response; }
public void OnStatusChanged(StatusCode statusCode) { switch (statusCode) { case StatusCode.Connect: { Peer.EstablishEncryption(); break; } case StatusCode.Disconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerLogic: case StatusCode.DisconnectByServerUserLimit: case StatusCode.TimeoutDisconnect: case StatusCode.Exception: case StatusCode.ExceptionOnConnect: { Controller.OnDisconnected("" + statusCode); State = new Disconnected(this); break; } case StatusCode.EncryptionEstablished: { State = new Connected(this); break; } default: { Controller.OnUnexpectedStatusCode(statusCode); break; } } }
private void Chasing() { if (statusCode != StatusCode.Chasing) { statusCode = StatusCode.Chasing; nav.Resume(); } Vector3 sightingPosDelta = enemySight.personalLastSighting - transform.position; if (sightingPosDelta.sqrMagnitude > 4f) { nav.destination = enemySight.personalLastSighting; } nav.speed = chaseSpeed; if (nav.remainingDistance < nav.stoppingDistance) { chaseTimer += Time.deltaTime; if (chaseTimer >= chaseWaitTime) { lastPlayerSighting.position = lastPlayerSighting.resetPosition; enemySight.personalLastSighting = lastPlayerSighting.resetPosition; chaseTimer = 0f; } } else { chaseTimer = 0f; } }
public void OnPeerStatusCallback(Game game, StatusCode returnCode) { switch (returnCode) { case StatusCode.Connect: { break; } case StatusCode.Disconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerLogic: case StatusCode.DisconnectByServerUserLimit: case StatusCode.TimeoutDisconnect: { game.SetDisconnected(returnCode); break; } default: { game.DebugReturn(DebugLevel.ERROR, returnCode.ToString()); break; } } }
public void OnStatusChanged(StatusCode statusCode) { Debug.Log (statusCode.ToString ()); switch (statusCode) { case StatusCode.Connect: // connect success Debug.Log("connect success"); break; case StatusCode.Disconnect: // disconnected Debug.Log("disconnect from server"); break; case StatusCode.DisconnectByServerUserLimit: // limit on connected user Debug.Log ("room full"); break; case StatusCode.ExceptionOnConnect: // error on connection Debug.Log("connection error"); break; case StatusCode.DisconnectByServer: // disconnected by server Debug.Log("disconnect by server"); break; case StatusCode.TimeoutDisconnect: // disconnected while timeout Debug.Log("time out"); break; case StatusCode.Exception: // other exception case StatusCode.ExceptionOnReceive: Debug.Log("unexpect error"); break; } }
private void Execute() { if (Interlocked.Exchange(ref flag, 1) == 0) { System.Threading.Tasks.Task.Factory.StartNew(() => { try { Status = StatusCode.Running; Message = "Running"; if (initialize != null) initialize(); Status = StatusCode.Success; Message = "Success"; } catch (Exception ex) { Thread.VolatileWrite(ref flag, 0); Message = ex.ToString(); Status = StatusCode.Failure; } }); } }
/// <summary>Initializes a new instance of the FormMain class.</summary> public FormMain(bool startLogging) { // This call is required by the designer InitializeComponent(); // Initialize private variables p_CurrentIP = "-"; p_CurrentStatus = StatusCode.None; p_ElapsedSeconds = 0; p_StartLogging = startLogging; p_StartupTime = DateTime.Now; p_TimerLog = null; // Initialize FormMain properties this.ClientSize = new Size(660, 480); this.Font = SystemFonts.MenuFont; // Initialize tray icon IconMain.ContextMenu = MenuMain; // Initialize Menu/ToolBar MenuShowSuccessful.Checked = Settings.Default.ShowSuccessful; MenuShowStatusChanges.Checked = Settings.Default.ShowStatusChanges; MenuShowErrors.Checked = Settings.Default.ShowErrors; ToolBarShowSuccessful.Pushed = MenuShowSuccessful.Checked; ToolBarShowStatusChanges.Pushed = MenuShowStatusChanges.Checked; ToolBarShowErrors.Pushed = MenuShowErrors.Checked; }
void request_OnComplete(TransferRequest request, AssetType type, UUID assetID, byte[] data) { AssetType = type; AssetID = assetID; AssetData = data; Status = StatusCode.Done; completeEvent.Set(); }
public void OnStatusChanged(StatusCode statusCode) { Console.WriteLine("Status: " + statusCode); if (statusCode == StatusCode.Connect) { this.connected = true; } }
public void OnStatusChanged(StatusCode statusCode) { Debug.Log("Status: " + statusCode); if (statusCode == StatusCode.Connect) { connected = true; } }
/// <summary> /// Creates a piggy-backed response with the specified response code /// to the specified request. /// </summary> public static Response CreatePiggybackedResponse(Request request, StatusCode code) { Response response = new Response(code); response.ID = request.ID; response.Type = MessageType.ACK; response.Destination = request.Source; response.Token = request.Token; return response; }
void IPhotonPeerListener.OnStatusChanged(StatusCode statusCode) { if (statusCode == StatusCode.Connect) _program.Context.OnConnect(); if (statusCode == StatusCode.Disconnect) _program.Context.Dispose(); Console.WriteColor($"Network status changed: {statusCode}", ConsoleColor.Cyan); }
public void OnStatusChanged(StatusCode statusCode) { // connected to Photon Server if (statusCode == StatusCode.Connect) { connected = true; } // log status change Debug.Log("Status change" + statusCode.ToString()); }
public DiagnosticInfo(int namespaceUri = -1, int symbolicId = -1, int locale = -1, int localizedText = -1, string additionalInfo = null, StatusCode innerStatusCode = default(StatusCode), DiagnosticInfo innerDiagnosticInfo = null) { this.NamespaceUri = namespaceUri; this.SymbolicId = symbolicId; this.Locale = locale; this.LocalizedText = localizedText; this.AdditionalInfo = additionalInfo; this.InnerStatusCode = innerStatusCode; this.InnerDiagnosticInfo = innerDiagnosticInfo; }
private string GetStatusLine(StatusCode code) { // TODO: Create the response status line and return it string statusLine = string.Empty; statusLine = "HTTP/1.1 " + ((int)code).ToString() + " " + code.ToString() + "\r\n"; return statusLine; }
public MitchellClaimType(string CN, string CFN, string CLN, StatusCode stt, DateTime LDate, LossInfoType LI, long aaID, VehicleListType vehi) { ClaimNumber = CN; ClaimFirstName = CFN; ClaimLastName = CLN; Status = stt; LossDate = LDate; LossInfo = LI; AssignedAdjusterID = aaID; Vehicles = vehi; }
public void onSucces(StatusCode.NETSTATE nst, object response) { if (nst == StatusCode.NETSTATE.STRING_RESPONSE) { } else if (nst == StatusCode.NETSTATE.TEXTURE_RESPONSE) { gameShowImg.GetComponentInChildren<UITexture>().mainTexture = (Texture2D)response; } }
//List<string> headerLines = new List<string>(); public Response(StatusCode code, string contentType, string content, string redirectoinPath) { string HeaderLines = "Server: " + Configuration.ServerType+"\r\n"; HeaderLines += "Content-Type: " + contentType+"\r\n"; HeaderLines += "Content-Length: " + content.Length.ToString() + "\r\n"; HeaderLines += "Date: " + DateTime.Now.ToString() + "\r\n"; if (redirectoinPath != string.Empty) HeaderLines+="Location: "+redirectoinPath+"\r\n"; responseString = GetStatusLine(code)+"\r\n"+HeaderLines+"\r\n"+content; }
public void OnStatusChanged(StatusCode statusCode) { if (statusCode == StatusCode.Connect) { this.Connected = true; } else { ChatGUI.MessagesTab1.Add("Status: " + statusCode); } }
public void OnStatusChanged(StatusCode statusCode) { if (statusCode == StatusCode.Connect) { _connected = true; Console.WriteLine("Connected."); } else { Console.WriteLine("Status: " + statusCode); } }
/// <summary> /// Initializes a new instance of the <see cref="Response"/> class. /// </summary> public Response() { this.cookies = new CookieCollection(); this.headers = new HeaderCollection(); this.headersSent = false; this.contentType = MimeType.Default; this.outputBuffer = new List<byte>(); this.sent = 0; this.status = StatusCode.Http500InternalServerError; this.useChunkedTransferEncoding = false; this.useCompression = false; }
private static bool IsTransientStatusCode(StatusCode code) { switch (code) { case StatusCode.Cancelled: case StatusCode.DeadlineExceeded: case StatusCode.ResourceExhausted: case StatusCode.Unavailable: return true; default: return false; } }
/// <summary> /// Loads the history data from a stream. /// </summary> private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader reader) { DataSet dataset = CreateDataSet(); ServiceMessageContext messageContext = new ServiceMessageContext(); if (context != null) { messageContext.NamespaceUris = context.NamespaceUris; messageContext.ServerUris = context.ServerUris; messageContext.Factory = context.EncodeableFactory; } else { messageContext.NamespaceUris = ServiceMessageContext.GlobalContext.NamespaceUris; messageContext.ServerUris = ServiceMessageContext.GlobalContext.ServerUris; messageContext.Factory = ServiceMessageContext.GlobalContext.Factory; } int sourceTimeOffset = 0; int serverTimeOffset = 0; StatusCode status = StatusCodes.Good; int recordType = 0; int modificationTimeOffet = 0; string modificationUser = String.Empty; BuiltInType valueType = BuiltInType.String; Variant value = Variant.Null; int annotationTimeOffet = 0; string annotationUser = String.Empty; string annotationMessage = String.Empty; int lineCount = 0; while (!reader.EndOfStream) { string line = reader.ReadLine(); // check for end or error. if (line == null) { break; } // ignore blank lines. line = line.Trim(); lineCount++; if (String.IsNullOrEmpty(line)) { continue; } // ignore commented out lines. if (line.StartsWith("//")) { continue; } // get source time. if (!ExtractField(lineCount, ref line, out sourceTimeOffset)) { continue; } // get server time. if (!ExtractField(lineCount, ref line, out serverTimeOffset)) { continue; } // get status code. if (!ExtractField(lineCount, ref line, out status)) { continue; } // get modification type. if (!ExtractField(lineCount, ref line, out recordType)) { continue; } // get modification time. if (!ExtractField(lineCount, ref line, out modificationTimeOffet)) { continue; } // get modification user. if (!ExtractField(lineCount, ref line, out modificationUser)) { continue; } if (recordType >= 0) { // get value type. if (!ExtractField(lineCount, ref line, out valueType)) { continue; } // get value. if (!ExtractField(lineCount, ref line, messageContext, valueType, out value)) { continue; } } else { // get annotation time. if (!ExtractField(lineCount, ref line, out annotationTimeOffet)) { continue; } // get annotation user. if (!ExtractField(lineCount, ref line, out annotationUser)) { continue; } // get annotation message. if (!ExtractField(lineCount, ref line, out annotationMessage)) { continue; } } // add values to data table. DataValue dataValue = new DataValue(); dataValue.WrappedValue = value; dataValue.SourceTimestamp = baseline.AddMilliseconds(sourceTimeOffset); dataValue.ServerTimestamp = baseline.AddMilliseconds(serverTimeOffset); dataValue.StatusCode = status; DataRow row = null; if (recordType == 0) { row = dataset.Tables[0].NewRow(); row[0] = dataValue.SourceTimestamp; row[1] = dataValue.ServerTimestamp; row[2] = dataValue; row[3] = valueType; row[4] = (value.TypeInfo != null) ? value.TypeInfo.ValueRank : ValueRanks.Any; dataset.Tables[0].Rows.Add(row); } else if (recordType > 0) { row = dataset.Tables[1].NewRow(); row[0] = dataValue.SourceTimestamp; row[1] = dataValue.ServerTimestamp; row[2] = dataValue; row[3] = valueType; row[4] = (value.TypeInfo != null) ? value.TypeInfo.ValueRank : ValueRanks.Any; row[5] = recordType; ModificationInfo info = new ModificationInfo(); info.UpdateType = (HistoryUpdateType)recordType; info.ModificationTime = baseline.AddMilliseconds(modificationTimeOffet); info.UserName = modificationUser; row[6] = info; dataset.Tables[1].Rows.Add(row); } else if (recordType < 0) { row = dataset.Tables[2].NewRow(); Annotation annotation = new Annotation(); annotation.AnnotationTime = baseline.AddMilliseconds(annotationTimeOffet); annotation.UserName = annotationUser; annotation.Message = annotationMessage; dataValue.WrappedValue = new ExtensionObject(annotation); row[0] = dataValue.SourceTimestamp; row[1] = dataValue.ServerTimestamp; row[2] = dataValue; row[3] = valueType; row[4] = (value.TypeInfo != null) ? value.TypeInfo.ValueRank : ValueRanks.Any; row[5] = annotation; dataset.Tables[2].Rows.Add(row); } dataset.AcceptChanges(); } return(dataset); }
public async Task StackTest() { var channel = new UaTcpSessionChannel( this.localDescription, this.certificateStore, new AnonymousIdentity(), EndpointUrl, loggerFactory: this.loggerFactory); await channel.OpenAsync(); logger.LogInformation($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'."); logger.LogInformation($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'."); logger.LogInformation($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'."); logger.LogInformation($"Activated session '{channel.SessionId}'."); var readRequest = new ReadRequest { NodesToRead = new[] { new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Boolean") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.SByte") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int16") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int32") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int64") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Byte") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt16") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt32") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt64") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Float") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Double") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.String") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.DateTime") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Guid") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.ByteString") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.XmlElement") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.LocalizedText") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.QualifiedName") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Boolean") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.SByte") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int16") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int32") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int64") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Byte") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt16") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt32") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt64") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Float") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Double") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.String") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.DateTime") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Guid") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.ByteString") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.XmlElement") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.LocalizedText") }, new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.QualifiedName") }, }, }; readRequest = new ReadRequest { NodesToRead = new[] { new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("i=11494") }, }, }; var sw = new Stopwatch(); sw.Restart(); for (int i = 0; i < 1; i++) { var readResponse = await channel.ReadAsync(readRequest); foreach (var result in readResponse.Results) { StatusCode.IsGood(result.StatusCode) .Should().BeTrue(); var obj = result.GetValue(); } } sw.Stop(); logger.LogInformation($"{sw.ElapsedMilliseconds} ms"); logger.LogInformation($"Closing session '{channel.SessionId}'."); await channel.CloseAsync(); }
public static void GrpcStatusError(ILogger logger, StatusCode status, string message) { _grpcStatusError(logger, status, message, null); }
public DuplexStreamingResult <TRequest, TResponse> ReturnStatus(StatusCode statusCode, string detail) { context.CallContext.Status = new Status(statusCode, detail); return(default(DuplexStreamingResult <TRequest, TResponse>)); // dummy }
public void TestValidCodes(string code) { Assert.True(StatusCode.CheckValidCode(code)); Assert.NotNull(new StatusCode(code)); }
/// <summary> /// Encodes a dataSet field /// </summary> private void EncodeField(JsonEncoder encoder, Field field) { string fieldName = field.FieldMetaData.Name; Variant valueToEncode = field.Value.WrappedValue; // The StatusCode.Good value is not encoded correctly then it shall be committed if (valueToEncode == StatusCodes.Good && m_fieldTypeEncoding != FieldTypeEncodingMask.Variant) { valueToEncode = Variant.Null; } if (m_fieldTypeEncoding != FieldTypeEncodingMask.DataValue && StatusCode.IsBad(field.Value.StatusCode)) { valueToEncode = field.Value.StatusCode; } switch (m_fieldTypeEncoding) { case FieldTypeEncodingMask.Variant: // If the DataSetFieldContentMask results in a Variant representation, // the field value is encoded as a Variant encoded using the reversible OPC UA JSON Data Encoding // defined in OPC 10000-6. encoder.ForceNamespaceUri = false; encoder.WriteVariant(fieldName, valueToEncode, true); break; case FieldTypeEncodingMask.RawData: // If the DataSetFieldContentMask results in a RawData representation, // the field value is a Variant encoded using the non-reversible OPC UA JSON Data Encoding // defined in OPC 10000-6 encoder.ForceNamespaceUri = true; encoder.WriteVariant(fieldName, valueToEncode, false); break; case FieldTypeEncodingMask.DataValue: DataValue dataValue = new DataValue(); dataValue.WrappedValue = valueToEncode; if ((FieldContentMask & DataSetFieldContentMask.StatusCode) != 0) { dataValue.StatusCode = field.Value.StatusCode; } if ((FieldContentMask & DataSetFieldContentMask.SourceTimestamp) != 0) { dataValue.SourceTimestamp = field.Value.SourceTimestamp; } if ((FieldContentMask & DataSetFieldContentMask.SourcePicoSeconds) != 0) { dataValue.SourcePicoseconds = field.Value.SourcePicoseconds; } if ((FieldContentMask & DataSetFieldContentMask.ServerTimestamp) != 0) { dataValue.ServerTimestamp = field.Value.ServerTimestamp; } if ((FieldContentMask & DataSetFieldContentMask.ServerPicoSeconds) != 0) { dataValue.ServerPicoseconds = field.Value.ServerPicoseconds; } // If the DataSetFieldContentMask results in a DataValue representation, // the field value is a DataValue encoded using the non-reversible OPC UA JSON Data Encoding encoder.ForceNamespaceUri = true; encoder.WriteDataValue(fieldName, dataValue, false); break; } }
// Perform a document operation on the specified database private static CouchbaseLiteResponse UpdateDb(ICouchbaseListenerContext context, Database db, string docId, Body body, bool deleting) { var response = context.CreateResponse(); if (docId != null) { // On PUT/DELETE, get revision ID from either ?rev= query, If-Match: header, or doc body: string revParam = context.GetQueryParam("rev"); string ifMatch = context.RequestHeaders["If-Match"]; if (ifMatch != null) { if (revParam == null) { revParam = ifMatch; } else if (!revParam.Equals(ifMatch)) { return(context.CreateResponse(StatusCode.BadRequest)); } } if (revParam != null && body != null) { var revProp = body.GetPropertyForKey("_rev"); if (revProp == null) { // No _rev property in body, so use ?rev= query param instead: var props = body.GetProperties(); props["_rev"] = revParam; body = new Body(props); } else if (!revProp.Equals(revParam)) { return(context.CreateResponse(StatusCode.BadRequest)); // mismatch between _rev and rev } } } RevisionInternal rev; StatusCode status = UpdateDocument(context, db, docId, body, deleting, false, out rev); if ((int)status < 300) { context.CacheWithEtag(rev.GetRevId()); // set ETag if (!deleting) { var url = context.RequestUrl; if (docId != null) { response["Location"] = url.AbsoluteUri; } } response.JsonBody = new Body(new Dictionary <string, object> { { "ok", true }, { "id", rev.GetDocId() }, { "rev", rev.GetRevId() } }); } response.InternalStatus = status; return(response); }
/// <summary> /// Sends the RST. /// </summary> /// <param name="streamId">The stream id.</param> /// <param name="reason">The reason for RST.</param> public void SendRST(int streamId, StatusCode reason) { this.SendFrame(this.builder.BuildRSTFrame(streamId, reason)); }
/// <summary> /// Sends the RST. /// </summary> /// <param name="stream">The stream.</param> /// <param name="reason">The reason for RST.</param> public void SendRST(SMStream stream, StatusCode reason) { this.SendFrame(stream, this.builder.BuildRSTFrame(stream, reason)); }
public Response(string message, StatusCode code) { Message = message; Code = code; }
/// <summary> /// Writes an item value to the OPC server. /// </summary> private bool WriteItemValue(CommandConfig commandConfig, double cmdVal, string cmdData) { // get data type string dataTypeName = commandConfig.DataTypeName; Type itemDataType = null; object itemVal; if (string.IsNullOrEmpty(dataTypeName)) { if (DeviceTags.TryGetTag(commandConfig.CmdCode, out DeviceTag deviceTag) && deviceTag.Aux is DeviceTagMeta tagMeta) { itemDataType = tagMeta.ActualDataType; } } else { itemDataType = Type.GetType(dataTypeName, false, true); } if (itemDataType == null) { throw new ScadaException(Locale.IsRussian ? "Не удалось получить тип данных {0}" : "Unable to get data type {0}", dataTypeName); } if (itemDataType.IsArray) { throw new ScadaException(Locale.IsRussian ? "Тип данных {0} не поддерживается" : "Data type {0} not supported", dataTypeName); } // define command value try { if (itemDataType == typeof(string)) { itemVal = cmdData; } else if (itemDataType == typeof(DateTime)) { itemVal = DateTime.FromOADate(cmdVal); } else { itemVal = Convert.ChangeType(cmdVal, itemDataType); } } catch { throw new ScadaException(Locale.IsRussian ? "Не удалось привести значение к типу {0}" : "Unable to convert value to the type {0}", itemDataType.FullName); } // write value Log.WriteLine(Locale.IsRussian ? "Отправка значения OPC-серверу: {0} = {1}" : "Send value to the OPC server: {0} = {1}", commandConfig.DisplayName, itemVal); WriteValue valueToWrite = new WriteValue { NodeId = commandConfig.NodeID, AttributeId = Attributes.Value, Value = new DataValue(new Variant(itemVal)) }; opcSession.Write(null, new WriteValueCollection { valueToWrite }, out StatusCodeCollection results, out _); if (StatusCode.IsGood(results[0])) { Log.WriteLine(CommPhrases.ResponseOK); return(true); } else { Log.WriteLine(CommPhrases.ResponseError); return(false); } }
private static StatusCode reconcileDataA <T, EType>(System.Collections.IDictionary dictA, System.Collections.IDictionary dictB, Models.ReconcileResult <T, EType> result, string strPrefix, int[] customFields) where T : Models.BaseItemRecord, new() where EType : struct { StatusCode retVal = StatusCode.SUCCEED_STATUS; string strKey = null; foreach (object key in dictA.Keys) { string strItem = null; if (key.GetType().IsEnum) { strItem = EnumAccess.GetEnumValueDescription(key); } else { strItem = key.ToString(); } strKey = strPrefix; object valA = dictA[key]; if (strKey == null) { strKey = strItem; } else { strKey += ":" + strItem; } if (dictB.Contains(key) == false) { T item = new T(); result.Add(strKey, default(EType), item, null, null); continue; } object valB = dictB[key]; if (valA is System.Collections.IDictionary colA) { System.Collections.IDictionary colB = (System.Collections.IDictionary)valB; retVal = reconcileDataA <T, EType>(colA, colB, result, strKey, customFields); if (retVal.IsSucceeded == false) { return(retVal); } } else if (valA is T tA) { T tB = (T)valB; if (customFields != null) { foreach (int fld in customFields) { if (tA[fld].Equals(tB[fld]) == false) { result.Add(strKey, (EType)((object)fld), tA, tB, null); } } } else { foreach (int fld in tA.Fields) { if (tA[fld].Equals(tB[fld]) == false) { result.Add(strKey, (EType)((object)fld), tA, tB, null); } } } } else { //Throw Exception } } return(retVal); }
public Status UpdateIndexes(IEnumerable <IViewStore> inputViews) { Log.D(TAG, "Checking indexes of ({0}) for {1}", ViewNames(inputViews.Cast <SqliteViewStore>()), Name); var db = _dbStorage; Status status = null; status = db.RunInTransaction(() => { // If the view the update is for doesn't need any update, don't do anything: long dbMaxSequence = db.LastSequence; long forViewLastSequence = LastSequenceIndexed; if (forViewLastSequence >= dbMaxSequence) { return(new Status(StatusCode.NotModified)); } // Check whether we need to update at all, // and remove obsolete emitted results from the 'maps' table: long minLastSequence = dbMaxSequence; long[] viewLastSequence = new long[inputViews.Count()]; int deletedCount = 0; int i = 0; HashSet <string> docTypes = new HashSet <string>(); IDictionary <string, string> viewDocTypes = null; bool allDocTypes = false; IDictionary <int, int> viewTotalRows = new Dictionary <int, int>(); List <SqliteViewStore> views = new List <SqliteViewStore>(inputViews.Count()); List <MapDelegate> mapBlocks = new List <MapDelegate>(); foreach (var view in inputViews.Cast <SqliteViewStore>()) { var viewDelegate = view.Delegate; var mapBlock = viewDelegate == null ? null : viewDelegate.Map; if (mapBlock == null) { Debug.Assert(view != this, String.Format("Cannot index view {0}: no map block registered", view.Name)); Log.V(TAG, " {0} has no map block; skipping it", view.Name); continue; } views.Add(view); mapBlocks.Add(mapBlock); int viewId = view.ViewID; Debug.Assert(viewId > 0, String.Format("View '{0}' not found in database", view.Name)); int totalRows = view.TotalRows; viewTotalRows[viewId] = totalRows; long last = view == this ? forViewLastSequence : view.LastSequenceIndexed; viewLastSequence[i++] = last; if (last < 0) { return(new Status(StatusCode.DbError)); } if (last < dbMaxSequence) { if (last == 0) { CreateIndex(); } minLastSequence = Math.Min(minLastSequence, last); Log.V(TAG, " {0} last indexed at #{1}", view.Name, last); string docType = viewDelegate.DocumentType; if (docType != null) { docTypes.Add(docType); if (viewDocTypes == null) { viewDocTypes = new Dictionary <string, string>(); } viewDocTypes[view.Name] = docType; } else { // can't filter by doc_type allDocTypes = true; } bool ok = true; int changes = 0; if (last == 0) { try { // If the lastSequence has been reset to 0, make sure to remove all map results: changes = db.StorageEngine.ExecSQL(view.QueryString("DELETE FROM 'maps_#'")); } catch (Exception) { ok = false; } } else { db.OptimizeSQLIndexes(); // ensures query will use the right indexes // Delete all obsolete map results (ones from since-replaced revisions): try { changes = db.StorageEngine.ExecSQL(view.QueryString("DELETE FROM 'maps_#' WHERE sequence IN (" + "SELECT parent FROM revs WHERE sequence>?" + "AND +parent>0 AND +parent<=?)"), last, last); } catch (Exception) { ok = false; } } if (!ok) { return(new Status(StatusCode.DbError)); } // Update #deleted rows deletedCount += changes; // Only count these deletes as changes if this isn't a view reset to 0 if (last != 0) { viewTotalRows[viewId] -= changes; } } } if (minLastSequence == dbMaxSequence) { return(new Status(StatusCode.NotModified)); } Log.D(TAG, "Updating indexes of ({0}) from #{1} to #{2} ...", ViewNames(views), minLastSequence, dbMaxSequence); // This is the emit() block, which gets called from within the user-defined map() block // that's called down below. SqliteViewStore currentView = null; IDictionary <string, object> currentDoc = null; long sequence = minLastSequence; Status emitStatus = new Status(StatusCode.Ok); int insertedCount = 0; EmitDelegate emit = (key, value) => { StatusCode s = currentView.Emit(key, value, value == currentDoc, sequence); if (s != StatusCode.Ok) { emitStatus.Code = s; } else { viewTotalRows[currentView.ViewID] += 1; insertedCount++; } }; // Now scan every revision added since the last time the views were indexed: bool checkDocTypes = docTypes.Count > 1 || (allDocTypes && docTypes.Count > 0); var sql = new StringBuilder("SELECT revs.doc_id, sequence, docid, revid, json, deleted "); if (checkDocTypes) { sql.Append(", doc_type "); } sql.Append("FROM revs, docs WHERE sequence>? AND sequence <=? AND current!=0 "); if (minLastSequence == 0) { sql.Append("AND deleted=0 "); } if (!allDocTypes && docTypes.Count > 0) { sql.AppendFormat("AND doc_type IN ({0}) ", Database.JoinQuoted(docTypes)); } sql.Append("AND revs.doc_id = docs.doc_id " + "ORDER BY revs.doc_id, deleted, revid DESC"); Cursor c = null; Cursor c2 = null; try { c = db.StorageEngine.IntransactionRawQuery(sql.ToString(), minLastSequence, dbMaxSequence); bool keepGoing = c.MoveToNext(); while (keepGoing) { // Get row values now, before the code below advances 'c': long doc_id = c.GetLong(0); sequence = c.GetLong(1); string docId = c.GetString(2); if (docId.StartsWith("_design/")) // design documents don't get indexed { keepGoing = c.MoveToNext(); continue; } string revId = c.GetString(3); var json = c.GetBlob(4); bool deleted = c.GetInt(5) != 0; string docType = checkDocTypes ? c.GetString(6) : null; // Skip rows with the same doc_id -- these are losing conflicts. while ((keepGoing = c.MoveToNext()) && c.GetLong(0) == doc_id) { } long realSequence = sequence; // because sequence may be changed, below if (minLastSequence > 0) { // Find conflicts with documents from previous indexings. using (c2 = db.StorageEngine.IntransactionRawQuery("SELECT revid, sequence FROM revs " + "WHERE doc_id=? AND sequence<=? AND current!=0 AND deleted=0 " + "ORDER BY revID DESC " + "LIMIT 1", doc_id, minLastSequence)) { if (c2.MoveToNext()) { string oldRevId = c2.GetString(0); // This is the revision that used to be the 'winner'. // Remove its emitted rows: long oldSequence = c2.GetLong(1); foreach (var view in views) { int changes = db.StorageEngine.ExecSQL(QueryString("DELETE FROM 'maps_#' WHERE sequence=?"), oldSequence); deletedCount += changes; viewTotalRows[view.ViewID] -= changes; } if (deleted || RevisionInternal.CBLCompareRevIDs(oldRevId, revId) > 0) { // It still 'wins' the conflict, so it's the one that // should be mapped [again], not the current revision! revId = oldRevId; deleted = false; sequence = oldSequence; json = db.QueryOrDefault <byte[]>(x => x.GetBlob(0), true, null, "SELECT json FROM revs WHERE sequence=?", sequence); } } } } if (deleted) { continue; } // Get the document properties, to pass to the map function: currentDoc = db.GetDocumentProperties(json, docId, revId, deleted, sequence); if (currentDoc == null) { Log.W(TAG, "Failed to parse JSON of doc {0} rev {1}", docId, revId); continue; } currentDoc["_local_seq"] = sequence; // Call the user-defined map() to emit new key/value pairs from this revision: int viewIndex = -1; var e = views.GetEnumerator(); while (e.MoveNext()) { currentView = e.Current; ++viewIndex; if (viewLastSequence[viewIndex] < realSequence) { if (checkDocTypes) { var viewDocType = viewDocTypes[currentView.Name]; if (viewDocType != null && viewDocType != docType) { // skip; view's documentType doesn't match this doc continue; } } Log.V(TAG, " #{0}: map \"{1}\" for view {2}...", sequence, docId, e.Current.Name); try { mapBlocks[viewIndex](currentDoc, emit); } catch (Exception x) { Log.E(TAG, String.Format("Exception in map() block for view {0}", currentView.Name), x); emitStatus.Code = StatusCode.Exception; } if (emitStatus.IsError) { c.Dispose(); return(emitStatus); } } } currentView = null; } } catch (Exception) { return(new Status(StatusCode.DbError)); } finally { if (c != null) { c.Dispose(); } } // Finally, record the last revision sequence number that was indexed and update #rows: foreach (var view in views) { view.FinishCreatingIndex(); int newTotalRows = viewTotalRows[view.ViewID]; Debug.Assert(newTotalRows >= 0); var args = new ContentValues(); args["lastSequence"] = dbMaxSequence; args["total_docs"] = newTotalRows; try { db.StorageEngine.Update("views", args, "view_id=?", view.ViewID.ToString()); } catch (Exception) { return(new Status(StatusCode.DbError)); } } Log.D(TAG, "...Finished re-indexing ({0}) to #{1} (deleted {2}, added {3})", ViewNames(views), dbMaxSequence, deletedCount, insertedCount); return(new Status(StatusCode.Ok)); }); if (status.Code >= StatusCode.BadRequest) { Log.W(TAG, "CouchbaseLite: Failed to rebuild views ({0}): {1}", ViewNames(inputViews.Cast <SqliteViewStore>()), status); } return(status); }
public Status(StatusCode statusCode, string detail) { this.statusCode = statusCode; this.detail = detail; }
public void WriteStatusCode(string fieldName, StatusCode value) { this.WriteUInt32(null, value.Value); }
/// <summary> /// The on disconnect. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="returnCode"> /// The return code. /// </param> public void OnDisconnect(Game game, StatusCode returnCode) { this.LogInfo(game, string.Format("{0}: {1}", game.Avatar.Id, returnCode)); this.running = false; }
public ActionResult Forbidden(StatusCode code, string url) { ParseResults(code); return(PartialView("_ErrorPage")); }
public IDictionary <string, object> Handshake() { if (_end == ConnectionEnd.Client) { // Build the request var builder = new StringBuilder(); builder.AppendFormat("{0} {1} {2}\r\n", Verbs.Get, _headers[CommonHeaders.Path], Protocols.Http1); //TODO pass here requested filename builder.AppendFormat("Host: {0}\r\n", _headers[CommonHeaders.Host]); builder.Append(String.Format("{0}: {1}, {2}\r\n", CommonHeaders.Connection, CommonHeaders.Upgrade, CommonHeaders.Http2Settings)); builder.Append(String.Format("{0}: {1}\r\n", CommonHeaders.Upgrade, Protocols.Http2NoTls)); var settingsPayload = String.Format("{0}, {1}", 200000, 100); var settingsBytes = Encoding.UTF8.GetBytes(settingsPayload); var settingsBase64 = Convert.ToBase64String(settingsBytes); builder.Append(String.Format("{0}: {1}", CommonHeaders.Http2Settings, settingsBase64)); builder.Append("\r\n\r\n"); byte[] requestBytes = Encoding.UTF8.GetBytes(builder.ToString()); _handshakeResult = new Dictionary <string, object>(_headers) { { CommonHeaders.Method, Verbs.Get.ToLower() } }; IoStream.Write(requestBytes, 0, requestBytes.Length); IoStream.Flush(); ReadHeadersAndInspectHandshake(); } else { ReadHeadersAndInspectHandshake(); if (_response.Result == HandshakeResult.Upgrade) { const int status = StatusCode.Code101SwitchingProtocols; string protocol = Protocols.Http1; string postfix = StatusCode.GetReasonPhrase(status); var builder = new StringBuilder(); builder.AppendFormat("{0} {1} {2}\r\n", protocol, status, postfix); builder.Append(String.Format("{0}: {1}\r\n", CommonHeaders.Connection, CommonHeaders.Upgrade)); builder.Append(String.Format("{0}: {1}\r\n", CommonHeaders.Upgrade, Protocols.Http2NoTls)); builder.Append("\r\n"); byte[] requestBytes = Encoding.ASCII.GetBytes(builder.ToString()); IoStream.Write(requestBytes, 0, requestBytes.Length); IoStream.Flush(); } } if (!_wasResponseReceived) { throw new Http2HandshakeFailed(HandshakeFailureReason.Timeout); } if (_response.Result != HandshakeResult.Upgrade) { _handshakeResult.Add(HandshakeKeys.Successful, HandshakeKeys.False); var path = _headers[CommonHeaders.Path] as string; Http2Logger.LogDebug("Handling with http11"); var http11Adapter = new Http11ClientMessageHandler(IoStream, path); http11Adapter.HandleHttp11Response(_response.ResponseBytes.Array, 0, _response.ResponseBytes.Count); return(_handshakeResult); } _handshakeResult.Add(HandshakeKeys.Successful, HandshakeKeys.True); return(_handshakeResult); }
//--------------------------------------------------------------------- // OPC UA Server .NET Interface // (Called by the generic server) //--------------------------------------------------------------------- /// <summary>This method is called when a client executes a 'write' server call. The <see cref="BaseDataVariableState"/> includes all information required to identify the item /// as well as original (unmodified) value, timestamp and quality. Depending on the returned result code the cache is updated or not in the generic server after returning from this method.</summary> /// <param name="originalVariableState">The <see cref="BaseVariableState"/> of the variable including the original state of the variable. Can be used to check what changes happens</param> /// <param name="value">The value which should be written. The returned value is used for updating the cache depending on the returned result code.</param> /// <param name="statusCode">A <see cref="StatusCode"/> code which should be used as new status code for the value.</param> /// <param name="timestamp">The timestamp the value was written. The returned value is used for updating the cache depending on the returned result code.</param> /// <returns>A <see cref="StatusCode"/> code with the result of the operation.</returns> /// <remarks> /// <para>Rules for updating the cache:</para> /// <list type="number"> /// <item>If the returned <see cref="StatusCode"/> is Bad (something like Bad...) the cache is not updated with timestamp and value.</item> /// <item>If the returned <see cref="StatusCode"/> is <see cref="StatusCodes.GoodCompletesAsynchronously">OpcStatusCodes.GoodCompletesAsynchronously</see> the cache is not updated with /// timestamp and value. After the customization DLL has finished its operation it can use <see cref="IUaServer.WriteBaseVariable">WriteBaseVariable</see> to update the cache.</item> /// <item>In all other cases the cache is updated with timestamp and value.</item> /// <item>In all cases the status code is updated with the status code set in the 'statusCode' parameter.</item> /// </list> /// </remarks> public StatusCode OnWriteBaseVariable(BaseVariableState originalVariableState, ref object value, ref StatusCode statusCode, ref DateTime timestamp) { // V1.3.0.0: To be compliant the provided timestamp must be used. So only if the provided timestamp is invalid set a correct one. if (timestamp == DateTime.MinValue) { timestamp = DateTime.UtcNow; } return(StatusCodes.Good); }
public LmsException(SerializationInfo serializationInfo, StreamingContext context, StatusCode status = StatusCode.PlatformError) : base(serializationInfo, context) { _exceptionCode = status; }
/// <summary> /// Attempt to update a document based on the information in the HTTP request /// </summary> /// <returns>The resulting status of the operation</returns> /// <param name="context">The request context</param> /// <param name="db">The database in which the document exists</param> /// <param name="docId">The ID of the document being updated</param> /// <param name="body">The new document body</param> /// <param name="deleting">Whether or not the document is being deleted</param> /// <param name="allowConflict">Whether or not to allow a conflict to be inserted</param> /// <param name="outRev">The resulting revision of the document</param> public static StatusCode UpdateDocument(ICouchbaseListenerContext context, Database db, string docId, Body body, bool deleting, bool allowConflict, out RevisionInternal outRev) { outRev = null; if (body != null && !body.IsValidJSON()) { return(StatusCode.BadJson); } string prevRevId; if (!deleting) { var properties = body.GetProperties(); deleting = properties.GetCast <bool>("_deleted"); if (docId == null) { // POST's doc ID may come from the _id field of the JSON body. docId = properties.GetCast <string>("_id"); if (docId == null && deleting) { return(StatusCode.BadId); } } // PUT's revision ID comes from the JSON body. prevRevId = properties.GetCast <string>("_rev"); } else { // DELETE's revision ID comes from the ?rev= query param prevRevId = context.GetQueryParam("rev"); } // A backup source of revision ID is an If-Match header: if (prevRevId == null) { prevRevId = context.IfMatch(); } if (docId == null && deleting) { return(StatusCode.BadId); } RevisionInternal rev = new RevisionInternal(docId, null, deleting); rev.SetBody(body); StatusCode status = deleting ? StatusCode.Ok : StatusCode.Created; try { if (docId != null && docId.StartsWith("_local")) { outRev = db.Storage.PutLocalRevision(rev, prevRevId, true); //TODO: Doesn't match iOS } else { outRev = db.PutRevision(rev, prevRevId, allowConflict); } } catch (CouchbaseLiteException e) { status = e.Code; } return(status); }
public LmsException(string message, Exception innerException, StatusCode status = StatusCode.PlatformError) : base(message, innerException) { _exceptionCode = status; }
public void TestInvalidCodes(string code) { Assert.False(StatusCode.CheckValidCode(code)); Assert.ThrowsAny <Exception>(() => new StatusCode(code)); }
/// <summary> /// Returns a subscription that is ready to publish. /// </summary> public Subscription Publish(uint clientHandle, DateTime deadline, bool requeue, AsyncPublishOperation operation) { QueuedRequest request = null; // DateTime queueTime = DateTime.UtcNow; // DateTime dequeueTime = DateTime.UtcNow; lock (m_lock) { if (m_queuedSubscriptions.Count == 0) { // TraceState("PUBLISH ERROR (BadNoSubscription)"); throw new ServiceResultException(StatusCodes.BadNoSubscription); } // find the waiting subscription with the highest priority. List <QueuedSubscription> subscriptions = new List <QueuedSubscription>(); for (int ii = 0; ii < m_queuedSubscriptions.Count; ii++) { QueuedSubscription subscription = m_queuedSubscriptions[ii]; if (subscription.ReadyToPublish && !subscription.Publishing) { subscriptions.Add(subscription); } } // find waiting the subscription that has been waiting the longest. if (subscriptions.Count > 0) { byte maxPriority = 0; DateTime earliestTimestamp = DateTime.MaxValue; QueuedSubscription subscriptionToPublish = null; for (int ii = 0; ii < subscriptions.Count; ii++) { QueuedSubscription subscription = subscriptions[ii]; if (subscription.Priority > maxPriority) { maxPriority = subscription.Priority; earliestTimestamp = DateTime.MaxValue; } if (subscription.Priority >= maxPriority && earliestTimestamp > subscription.Timestamp) { earliestTimestamp = subscription.Timestamp; subscriptionToPublish = subscription; } } // reset subscriptions flag. m_subscriptionsWaiting = false; for (int jj = 0; jj < m_queuedSubscriptions.Count; jj++) { if (m_queuedSubscriptions[jj].ReadyToPublish) { m_subscriptionsWaiting = true; break; } } // TraceState("REQUEST #{0} ASSIGNED TO WAITING SUBSCRIPTION", clientHandle); subscriptionToPublish.Publishing = true; return(subscriptionToPublish.Subscription); } // queue request because there is nothing waiting. if (subscriptions.Count == 0) { LinkedListNode <QueuedRequest> node = m_queuedRequests.First; while (node != null) { LinkedListNode <QueuedRequest> next = node.Next; QueuedRequest queuedRequest = node.Value; StatusCode requestStatus = StatusCodes.Good; // check if expired. if (queuedRequest.Deadline < DateTime.MaxValue && queuedRequest.Deadline.AddMilliseconds(500) < DateTime.UtcNow) { requestStatus = StatusCodes.BadTimeout; } // check secure channel. else if (!m_session.IsSecureChannelValid(queuedRequest.SecureChannelId)) { requestStatus = StatusCodes.BadSecureChannelIdInvalid; } // remove bad requests. if (StatusCode.IsBad(requestStatus)) { queuedRequest.Error = requestStatus; queuedRequest.Set(); m_queuedRequests.Remove(node); } node = next; } // clear excess requests - keep the newest ones. while (m_maxPublishRequests > 0 && m_queuedRequests.Count >= m_maxPublishRequests) { request = m_queuedRequests.First.Value; request.Error = StatusCodes.BadTooManyPublishRequests; request.Set(); m_queuedRequests.RemoveFirst(); } request = new QueuedRequest(); request.SecureChannelId = SecureChannelContext.Current.SecureChannelId; request.Deadline = deadline; request.Subscription = null; request.Error = StatusCodes.Good; if (operation == null) { request.Event = new ManualResetEvent(false); } else { request.Operation = operation; } if (requeue) { m_queuedRequests.AddFirst(request); // TraceState("REQUEST #{0} RE-QUEUED", clientHandle); } else { m_queuedRequests.AddLast(request); // TraceState("REQUEST #{0} QUEUED", clientHandle); } } } // check for non-blocking operation. if (operation != null) { // TraceState("PUBLISH: #{0} Async Request Queued.", clientHandle); return(null); } // wait for subscription. ServiceResult error = request.Wait(Timeout.Infinite); // check for error. if (ServiceResult.IsGood(error)) { if (StatusCode.IsBad(request.Error)) { error = request.Error; } } // must reassign subscription on error. if (ServiceResult.IsBad(request.Error)) { if (request.Subscription != null) { lock (m_lock) { request.Subscription.Publishing = false; AssignSubscriptionToRequest(request.Subscription); } } // TraceState("REQUEST #{0} PUBLISH ERROR ({1})", clientHandle, error.StatusCode); throw new ServiceResultException(request.Error); } // must be shuting down if this is null but no error. if (request.Subscription == null) { throw new ServiceResultException(StatusCodes.BadNoSubscription); } // TraceState("REQUEST #{0} ASSIGNED", clientHandle); // return whatever was assigned. return(request.Subscription.Subscription); }
public async Task TransferSubscription() { var channel1 = new UaTcpSessionChannel( this.localDescription, this.certificateStore, new UserNameIdentity("root", "secret"), EndpointUrl, loggerFactory: this.loggerFactory); await channel1.OpenAsync(); logger.LogInformation($"Opened session with endpoint '{channel1.RemoteEndpoint.EndpointUrl}'."); logger.LogInformation($"SecurityPolicy: '{channel1.RemoteEndpoint.SecurityPolicyUri}'."); logger.LogInformation($"SecurityMode: '{channel1.RemoteEndpoint.SecurityMode}'."); logger.LogInformation($"Activated session '{channel1.SessionId}'."); // create the keep alive subscription. var subscriptionRequest = new CreateSubscriptionRequest { RequestedPublishingInterval = 1000f, RequestedMaxKeepAliveCount = 30, RequestedLifetimeCount = 30 * 3, PublishingEnabled = true, }; var subscriptionResponse = await channel1.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false); var id = subscriptionResponse.SubscriptionId; var token = channel1.Where(pr => pr.SubscriptionId == id).Subscribe(pr => { // loop thru all the data change notifications var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>(); foreach (var dcn in dcns) { foreach (var min in dcn.MonitoredItems) { logger.LogInformation($"channel: 1; sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}"); } } }); var itemsRequest = new CreateMonitoredItemsRequest { SubscriptionId = id, ItemsToCreate = new MonitoredItemCreateRequest[] { new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } } }, }; var itemsResponse = await channel1.CreateMonitoredItemsAsync(itemsRequest); await Task.Delay(3000); var channel2 = new UaTcpSessionChannel( this.localDescription, this.certificateStore, new UserNameIdentity("root", "secret"), EndpointUrl); await channel2.OpenAsync(); var token2 = channel2.Where(pr => pr.SubscriptionId == id).Subscribe(pr => { // loop thru all the data change notifications var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>(); foreach (var dcn in dcns) { foreach (var min in dcn.MonitoredItems) { logger.LogInformation($"channel: 2; sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}"); } } }); var transferRequest = new TransferSubscriptionsRequest { SubscriptionIds = new[] { id }, SendInitialValues = true }; var transferResult = await channel2.TransferSubscriptionsAsync(transferRequest); StatusCode.IsGood(transferResult.Results[0].StatusCode) .Should().BeTrue(); await Task.Delay(3000); logger.LogInformation($"Closing session '{channel1.SessionId}'."); await channel1.CloseAsync(); logger.LogInformation($"Closing session '{channel2.SessionId}'."); await channel2.CloseAsync(); }
public void OnStatusChanged(StatusCode statusCode) { Debug.Log("Status: " + statusCode); }
public async Task ReadHistorical() { var channel = new UaTcpSessionChannel( this.localDescription, this.certificateStore, new AnonymousIdentity(), "opc.tcp://localhost:48010", loggerFactory: this.loggerFactory); await channel.OpenAsync(); logger.LogInformation($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'."); logger.LogInformation($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'."); logger.LogInformation($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'."); logger.LogInformation($"Activated session '{channel.SessionId}'."); var historyReadRequest = new HistoryReadRequest { HistoryReadDetails = new ReadRawModifiedDetails { StartTime = DateTime.UtcNow - TimeSpan.FromMinutes(10), EndTime = DateTime.UtcNow, ReturnBounds = true, IsReadModified = false }, NodesToRead = new[] { new HistoryReadValueId { NodeId = NodeId.Parse("ns=2;s=Demo.History.DoubleWithHistory") } }, }; var historyReadResponse = await channel.HistoryReadAsync(historyReadRequest); var result = historyReadResponse.Results[0]; StatusCode.IsGood(result.StatusCode) .Should().BeTrue(); logger.LogInformation($"HistoryRead response status code: {result.StatusCode}, HistoryData count: {((HistoryData)result.HistoryData).DataValues.Length}."); if (false) // UaCPPserver does not appear to store event history. { var historyReadRequest2 = new HistoryReadRequest { HistoryReadDetails = new ReadEventDetails { StartTime = DateTime.UtcNow - TimeSpan.FromMinutes(10), EndTime = DateTime.UtcNow, Filter = new EventFilter // Use EventHelper to select all the fields of AlarmCondition. { SelectClauses = EventHelper.GetSelectClauses<AlarmCondition>() } }, NodesToRead = new[] { new HistoryReadValueId { NodeId = NodeId.Parse("ns=2;s=Demo.History.DoubleWithHistory") } }, }; var historyReadResponse2 = await channel.HistoryReadAsync(historyReadRequest2); var result2 = historyReadResponse2.Results[0]; StatusCode.IsGood(result2.StatusCode) .Should().BeTrue(); logger.LogInformation($"HistoryRead response status code: {result2.StatusCode}, HistoryEvent count: {((HistoryEvent)result2.HistoryData).Events.Length}."); // Use EventHelper to create AlarmConditions from the HistoryEventFieldList var alarms = ((HistoryEvent)result2.HistoryData).Events.Select(e => EventHelper.Deserialize<AlarmCondition>(e.EventFields)); } logger.LogInformation($"Closing session '{channel.SessionId}'."); await channel.CloseAsync(); }
protected UnaryResult <TResponse> ReturnStatus <TResponse>(StatusCode statusCode, string detail) { Context.CallContext.Status = new Status(statusCode, detail); return(default(UnaryResult <TResponse>)); // dummy }
/// <summary> /// Browses the children of the node and updates the tree. /// </summary> private bool BrowseChildren(TreeNode parent) { ReferenceDescription reference = parent.Tag as ReferenceDescription; if (reference == null) { return(false); } parent.Nodes.Clear(); if (reference.NodeId.IsAbsolute) { return(false); } BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = (NodeId)reference.NodeId; nodeToBrowse.BrowseDirection = m_browseDirection; nodeToBrowse.ReferenceTypeId = m_referenceTypeId; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)(int)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); ViewDescription view = null; if (NodeId.IsNull(m_viewId)) { view = new ViewDescription(); view.ViewId = m_viewId; view.Timestamp = DateTime.MinValue; view.ViewVersion = 0; } BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Browse( null, view, 0, nodesToBrowse, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return(false); } UpdateNode(parent, results[0].References); while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); m_session.BrowseNext( null, parent == null, continuationPoints, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return(false); } UpdateNode(parent, results[0].References); } return(true); }
public RestException(System.Net.Http.HttpResponseMessage response) { StatusCode = response.StatusCode; //CloneWithContent will not work here since the content is disposed after sendAsync //Besides, it seems there is no need for the request content cloned here. RequestMessage = response.RequestMessage.Clone(); ResponseBody = response.Content.ReadAsStringAsync().Result; ResponseHeaders = response.Headers; RequestId = response.GetFirstHeader("x-ms-request-id"); ClientRequestId = response.GetFirstHeader("x-ms-client-request-id"); try { // try to parse the body as JSON, and see if a code and message are in there. var json = Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject; // see if there is an error block in the body json = json.Property("error") ?? json; { Code = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } { message = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("message"), out var m) ? (string)m : (string)Message; } { Action = If(json?.PropertyT <Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("action"), out var a) ? (string)a : (string)Action; } } #if DEBUG catch (System.Exception E) { System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); } #else catch { // couldn't get the code/message from the body response. // we'll create one below. } #endif if (string.IsNullOrEmpty(message)) { if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) { message = $"The server responded with a Request Error, Status: {StatusCode}"; } else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) { message = $"The server responded with a Server Error, Status: {StatusCode}"; } else { message = $"The server responded with an unrecognized response, Status: {StatusCode}"; } } }