public void SimulateTimeout() { var gate = new AutoResetEvent(false); var testWeb = "Http://localhost:21266"; var client = new ClientBase(new Serializer()); client.BeginRequest(RequestMethod.GET, testWeb, "/DelayHandler.ashx", null, null, ContentType.TEXT, ContentType.TEXT, TimeSpan.FromSeconds(1), 3000, 0, ar => { Console.WriteLine("we are in the callback about to end the request"); // any time your code utilizes network resources you need to be ready to handle exceptions. try { var response = client.EndRequest(ar); Console.WriteLine("you will not see this line output, exception had already been triggered by .EndRequest()"); } catch (TimeoutException ex) { Console.Write("our code properly caught a timeout exception:\r\n" + ex.ToString()); } gate.Set(); }, null); gate.WaitOne(20000); client.Dispose(); }
public void CanPurgeAndSHutdown() { //#FIXME - not a test - just an excercise - need to expose internals so we can peek the request queue var server = new CassiniDevServer(); server.StartServer(ContentLocation); string root = server.RootUrl.TrimEnd('/'); var client = new ClientBase(new Serializer()); try { for (int i = 0; i < 50; i++) { client.BeginRequest(RequestMethod.GET, root, "/SampleClientHandler.ashx?foo={foo}", null, new Dictionary<string, object>() { { "foo", "foo" + i } }, ContentType.TEXT, ContentType.JSON, TimeSpan.FromSeconds(1), 3000, 0, ar => { }, null); } var handle = client.ShutDown(); if (!handle.WaitOne(20000)) { throw new Exception("timed out"); } } finally { server.Dispose(); } }
public void Noid() { var c = new ClientBase(new Serializer()); var r = c.Request(RequestMethod.GET, "http://gooogle.com", "", null, null, ContentType.TEXT, ContentType.TEXT, TimeSpan.FromMinutes(1), 10000, 3); Assert.IsTrue(!string.IsNullOrEmpty(r)); }
public void CanPurgeAndSHutdownWithNoPendingRequests() { var client = new ClientBase(new Serializer()); var handle = client.ShutDown(); if(!handle.WaitOne(1000)) { Assert.Fail("handle should already be set"); } }
public void RemoveClient(ClientBase client) { lock (m_clients.SyncRoot) { if (m_clients.Contains(client)) { m_clients.Remove(client); } } }
public void ConnectAndLogin() { if(_connection != null) { this.Dispose(); } _connection = getClientObject(); try { if (_encryption == EncryptionType.Unencrypted) { _connection.Connect(this._server, this._port); } else { _connection.ConnectSSL(this._server, this._port); if (_encryption == EncryptionType.STARTTLS) startTSL(); } login(_username, _password); } catch(ImapResponseException ire) { //aditional authentication by gmail if (ire.Message.StartsWith(GMAIL_LOGINONBROWSER_MESSAGE, StringComparison.InvariantCultureIgnoreCase) && _server.EndsWith(GMAIL_DOMAIN, StringComparison.InvariantCultureIgnoreCase)) { //tried to open the gmail authentication page, but it doesn't help //if (ire.Response.Lines.Count > 0) //{ // System.Diagnostics.Process.Start(ire.Response.Lines[0].Substring(ire.Response.Lines[0].IndexOf("http"))); // StatusProvider.DisplayStatus("Please authenticate on the opened web page, and try again."); //} //switching "unsafe authentication" is needed in gmail settings, so displaying the support page describing it var httpPos = ire.Message.IndexOf("http"); if(httpPos>-1) { var url = ire.Message.Substring(httpPos); var spacePos = url.IndexOf(" "); if (spacePos > -1) url = url.Substring(0, spacePos); System.Diagnostics.Process.Start(url); ErrorProvider.DisplayError("Gmail authentication failed, please read the opened support page."); } } else throw new MailServerException(ire.Message); } catch(ServerException se) { throw new MailServerException(se.Message); } }
public void TestRecorder() { var client = new ClientBase(new Serializer()); var recorder = new Recorder(client); recorder.Start(); var gate = new AutoResetEvent(false); Exception exception = null; FooClass result = null; Guid id = client.BeginRequest(RequestMethod.GET, "http://api.geonames.org", "/citiesJSON?north={north}&south={south}&east{east}&west={west}&lang={lang}&username={username}", new Dictionary<string, string>(), new Dictionary<string, object> { {"north",44.1}, {"south",-9.9}, {"east",-22.4}, {"west",55.2}, {"lang","de"}, {"username","demo"} }, ContentType.TEXT, ContentType.JSON, TimeSpan.FromSeconds(1), 3000, 0, ar => { try { result = client.EndRequest<FooClass>(ar); var responsetext = ar.ResponseText; } catch (Exception ex) { exception = ex; } gate.Set(); }, null); if (!gate.WaitOne(10000)) { throw new Exception("timed out"); } // verify cache has purged gate.WaitOne(3000); if (exception != null) { Assert.Fail(exception.Message); } recorder.Stop(); List<RequestInfoBase> recorded = recorder.GetRequests(); recorder.Dispose(); Assert.IsTrue(recorded.Count == 1); var recordedJson = client.Serializer.SerializeObject(recorded); List<RequestInfoBase> deserializedRecording = client.Serializer.DeserializeObject<List<RequestInfoBase>>(recordedJson); Assert.IsTrue(deserializedRecording.Count == 1); }
public void AddClient(ClientBase client) { lock (m_clients.SyncRoot) { if (m_clients.Contains(client)) return; m_clients.Add(client, client); client.Disconnected += new DisconnectDelegate(client_Disconnected); } }
private void InitRestClients() { RestClient = new RestClient("http://localhost:8989/api"); Series = new SeriesClient(RestClient, _runner.ApiKey); Releases = new ReleaseClient(RestClient, _runner.ApiKey); RootFolders = new ClientBase<RootFolderResource>(RestClient, _runner.ApiKey); Commands = new ClientBase<CommandResource>(RestClient, _runner.ApiKey); History = new ClientBase<HistoryResource>(RestClient, _runner.ApiKey); Indexers = new IndexerClient(RestClient, _runner.ApiKey); Episodes = new EpisodeClient(RestClient, _runner.ApiKey); NamingConfig = new ClientBase<NamingConfigResource>(RestClient, _runner.ApiKey, "config/naming"); }
public ClientBase[] GetAllClients() { ClientBase[] list; lock (m_clients.SyncRoot) { list = new ClientBase[m_clients.Count]; m_clients.Keys.CopyTo(list, 0); } return list; }
public void Test() { var client = new ClientBase(new Serializer()); var gate = new AutoResetEvent(false); Exception exception = null; FooClass result = null; Guid id = client.BeginRequest(RequestMethod.GET, "http://api.geonames.org", "/citiesJSON?north={north}&south={south}&east{east}&west={west}&lang={lang}&username={username}", new Dictionary<string, object> { {"north",44.1}, {"south",-9.9}, {"east",-22.4}, {"west",55.2}, {"lang","de"}, {"username","demo"} }, ContentType.TEXT, ContentType.JSON, TimeSpan.FromSeconds(1), 3000, 0, ar => { try { result = client.EndRequest<FooClass>(ar); var responsetext = ar.ResponseText; } catch (Exception ex) { exception = ex; } gate.Set(); }, null); if (!gate.WaitOne(10000)) { throw new Exception("timed out"); } // verify cache has purged gate.WaitOne(3000); if (exception != null) { Assert.Fail(exception.Message); } var output = GetLogOutput(); }
/// <summary> /// Deletes the recent history. /// </summary> private void DeleteHistory(NodeId areaId, List <VariantCollection> events, FilterDeclaration filter) { // find the event id. int index = 0; foreach (FilterDeclarationField field in filter.Fields) { if (field.InstanceDeclaration.BrowseName == Opc.Ua.BrowseNames.EventId) { break; } index++; } // can't delete events if no event id. if (index >= filter.Fields.Count) { throw ServiceResultException.Create(StatusCodes.BadEventIdUnknown, "Cannot delete events if EventId was not selected."); } // build list of nodes to delete. DeleteEventDetails details = new DeleteEventDetails(); details.NodeId = areaId; foreach (VariantCollection e in events) { byte[] eventId = null; if (e.Count > index) { eventId = e[index].Value as byte[]; } details.EventIds.Add(eventId); } // delete the events. ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection(); nodesToUpdate.Add(new ExtensionObject(details)); HistoryUpdateResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.HistoryUpdate( null, nodesToUpdate, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToUpdate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } // check for item level errors. if (results[0].OperationResults.Count > 0) { int count = 0; for (int ii = 0; ii < results[0].OperationResults.Count; ii++) { if (StatusCode.IsBad(results[0].OperationResults[ii])) { count++; } } // raise an error. if (count > 0) { throw ServiceResultException.Create( StatusCodes.BadEventIdUnknown, "Error deleting events. Only {0} of {1} deletes succeeded.", events.Count - count, events.Count); } } }
public static void GetData(TimeSeriesBlock tsb) { if (session != null) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = startTime; details.EndTime = endTime; details.NumValuesPerNode = 0; details.IsReadModified = false; details.ReturnBounds = true; var nodesToRead = new HistoryReadValueIdCollection(); for (int i = 0; i < tsb.opcNodes.Count; i++) { var nodeToRead = new HistoryReadValueId(); string[] split = tsb.opcNodes[i].Split(','); nodeToRead.NodeId = new NodeId(split[1], (ushort)Convert.ToInt32(split[0])); nodesToRead.Add(nodeToRead); } table = new List <List <object> >(); HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; bool loop = true; while (loop) { session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); foreach (var res in results) { if (StatusCode.IsBad(res.StatusCode)) { throw new ServiceResultException(res.StatusCode); } } var historyData1 = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; var historyData2 = ExtensionObject.ToEncodeable(results[1].HistoryData) as HistoryData; for (int i = 0; i < historyData1.DataValues.Count; i++) { var row = new List <object>(); row.Add(historyData1.DataValues[i].SourceTimestamp); row.Add(historyData1.DataValues[i].Value); row.Add(historyData2.DataValues[i].Value); table.Add(row); } for (int i = 0; i < results.Count; i++) { if (results[i].ContinuationPoint == null || results[i].ContinuationPoint.Length == 0) { loop = false; break; } nodesToRead[i].ContinuationPoint = results[i].ContinuationPoint; } } } }
/// <summary> /// 读取一个节点的所有属性 /// </summary> /// <param name="tag">节点信息</param> /// <returns>节点的特性值</returns> public OpcNodeAttribute[] ReadNoteAttributes(string tag) { NodeId sourceId = new NodeId(tag); ReadValueIdCollection nodesToRead = new ReadValueIdCollection( ); // attempt to read all possible attributes. // 尝试着去读取所有可能的特性 for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++) { ReadValueId nodeToRead = new ReadValueId( ); nodeToRead.NodeId = sourceId; nodeToRead.AttributeId = ii; nodesToRead.Add(nodeToRead); } int startOfProperties = nodesToRead.Count; // find all of the pror of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription( ); nodeToBrowse1.NodeId = sourceId; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = 0; nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( ); nodesToBrowse.Add(nodeToBrowse1); // fetch property references from the server. ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false); if (references == null) { return(new OpcNodeAttribute[0]); } for (int ii = 0; ii < references.Count; ii++) { // ignore external references. if (references[ii].NodeId.IsAbsolute) { continue; } ReadValueId nodeToRead = new ReadValueId( ); nodeToRead.NodeId = (NodeId)references[ii].NodeId; nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); } // read all values. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // process results. List <OpcNodeAttribute> nodeAttribute = new List <OpcNodeAttribute>( ); for (int ii = 0; ii < results.Count; ii++) { OpcNodeAttribute item = new OpcNodeAttribute( ); // process attribute value. if (ii < startOfProperties) { // ignore attributes which are invalid for the node. if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid) { continue; } // get the name of the attribute. item.Name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId); // display any unexpected error. if (StatusCode.IsBad(results[ii].StatusCode)) { item.Type = Utils.Format("{0}", Attributes.GetDataTypeId(nodesToRead[ii].AttributeId)); item.Value = Utils.Format("{0}", results[ii].StatusCode); } // display the value. else { TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value); item.Type = typeInfo.BuiltInType.ToString( ); if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions) { item.Type += "[]"; } item.Value = results[ii].Value;//Utils.Format("{0}", results[ii].Value); } } // process property value. else { // ignore properties which are invalid for the node. if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown) { continue; } // get the name of the property. item.Name = Utils.Format("{0}", references[ii - startOfProperties]); // display any unexpected error. if (StatusCode.IsBad(results[ii].StatusCode)) { item.Type = String.Empty; item.Value = Utils.Format("{0}", results[ii].StatusCode); } // display the value. else { TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value); item.Type = typeInfo.BuiltInType.ToString( ); if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions) { item.Type += "[]"; } item.Value = results[ii].Value; //Utils.Format("{0}", results[ii].Value); } } nodeAttribute.Add(item); } return(nodeAttribute.ToArray( )); }
protected override void InitRestClients() { base.InitRestClients(); DiskSpace = new ClientBase <DiskSpaceResource>(RestClient, ApiKey, "diskSpace"); }
public StreamRecorder(ClientBase client,Stream stream) : base(client) { _stream = stream; }
public HeartbeatHandler(ClientBase worker) : base(worker) { }
void client_Disconnected(ClientBase client) { RemoveClient(client); }
protected RecorderBase(ClientBase client) { Paused = true; Client = client; Client.RequestCompleted += OnRequestCompleted; }
public static void SetContext <T>(this ClientBase <T> proxy, IDictionary <string, string> context) where T : class { SetContext(proxy.InnerChannel, context); }
protected virtual void InitRestClients() { RestClient = new RestClient(RootUrl + "api/"); RestClient.AddDefaultHeader("Authentication", ApiKey); RestClient.AddDefaultHeader("X-Api-Key", ApiKey); Blacklist = new ClientBase<BlacklistResource>(RestClient, ApiKey); Commands = new CommandClient(RestClient, ApiKey); DownloadClients = new DownloadClientClient(RestClient, ApiKey); Episodes = new EpisodeClient(RestClient, ApiKey); History = new ClientBase<HistoryResource>(RestClient, ApiKey); HostConfig = new ClientBase<HostConfigResource>(RestClient, ApiKey, "config/host"); Indexers = new IndexerClient(RestClient, ApiKey); NamingConfig = new ClientBase<NamingConfigResource>(RestClient, ApiKey, "config/naming"); Notifications = new NotificationClient(RestClient, ApiKey); Profiles = new ClientBase<ProfileResource>(RestClient, ApiKey); Releases = new ReleaseClient(RestClient, ApiKey); RootFolders = new ClientBase<RootFolderResource>(RestClient, ApiKey); Series = new SeriesClient(RestClient, ApiKey); Tags = new ClientBase<TagResource>(RestClient, ApiKey); WantedMissing = new ClientBase<EpisodeResource>(RestClient, ApiKey, "wanted/missing"); WantedCutoffUnmet = new ClientBase<EpisodeResource>(RestClient, ApiKey, "wanted/cutoff"); }
public ChartViewModel(PlotServiceClient service) { _service = service; }
/// <summary> /// Browses the address space and returns the references found. /// </summary> public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError) { try { ReferenceDescriptionCollection references = new ReferenceDescriptionCollection(); // construct browse request. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, view, 0, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); do { // check for error. if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } // process results. for (int ii = 0; ii < results[0].References.Count; ii++) { references.Add(results[0].References[ii]); } // check if all references have been fetched. if (results[0].References.Count == 0 || results[0].ContinuationPoint == null) { break; } // continue browse operation. ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); session.BrowseNext( null, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); }while (true); //return complete list. return(references); } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return(null); } }
public HeaderHandler(ClientBase<AmadeusWebServicesPT> client) { mClient = client; }
public PacketHandlers(ClientBase client) { m_client = client; }
public Recorder(ClientBase client) : base(client) { Requests = new List<RequestInfoBase>(); }
/// <summary> /// Browses the node and returns the references found. /// </summary> protected virtual bool Browse( Node node, BrowseDescription nodeToBrowse, ReferenceDescriptionCollection references) { BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); BrowseResultCollection results; DiagnosticInfoCollection diagnosticInfos; RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = 0; Session.Browse( requestHeader, new ViewDescription(), 0, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); // check diagnostics. if (diagnosticInfos != null && diagnosticInfos.Count > 0) { Log("Returned non-empty DiagnosticInfos array during Browse."); return(false); } // process results. ByteStringCollection continuationPoints = new ByteStringCollection(); for (int ii = 0; ii < results.Count; ii++) { // check status code. if (StatusCode.IsBad(results[ii].StatusCode)) { Log( "Browse Failed for Node '{0}'. Status = {2}, NodeId = {1}", node, node.NodeId, results[ii].StatusCode); return(false); } // save references. references.AddRange(results[ii].References); if (results[ii].ContinuationPoint != null) { continuationPoints.Add(results[ii].ContinuationPoint); } } // process continuation points. while (continuationPoints.Count > 0) { requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = 0; Session.BrowseNext( requestHeader, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); // check diagnostics. if (diagnosticInfos != null && diagnosticInfos.Count > 0) { Log("Returned non-empty DiagnosticInfos array during BrowseNext."); return(false); } continuationPoints.Clear(); // process results. for (int ii = 0; ii < results.Count; ii++) { // check status code. if (StatusCode.IsBad(results[ii].StatusCode)) { Log( "BrowseNext Failed for Node '{0}'. Status = {2}, NodeId = {1}", node, node.NodeId, results[ii].StatusCode); return(false); } // save references. references.AddRange(results[ii].References); if (results[ii].ContinuationPoint != null) { // check max references. if (results[ii].References.Count == 0) { Log( "No references returned with a continuation point for Node '{0}'. NodeId = {1}", node, node.NodeId); return(false); } continuationPoints.Add(results[ii].ContinuationPoint); } } } return(true); }
/// <summary> /// Browses the address space and returns the references found. /// </summary> public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescriptionCollection nodesToBrowse, bool throwOnError) { try { ReferenceDescriptionCollection references = new ReferenceDescriptionCollection(); BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection(); while (nodesToBrowse.Count > 0) { // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, view, 0, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); ByteStringCollection continuationPoints = new ByteStringCollection(); for (int ii = 0; ii < nodesToBrowse.Count; ii++) { // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { // this error indicates that the server does not have enough simultaneously active // continuation points. This request will need to be resent after the other operations // have been completed and their continuation points released. if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints) { unprocessedOperations.Add(nodesToBrowse[ii]); } continue; } // check if all references have been fetched. if (results[ii].References.Count == 0) { continue; } // save results. references.AddRange(results[ii].References); // check for continuation point. if (results[ii].ContinuationPoint != null) { continuationPoints.Add(results[ii].ContinuationPoint); } } // process continuation points. ByteStringCollection revisedContiuationPoints = new ByteStringCollection(); while (continuationPoints.Count > 0) { // continue browse operation. session.BrowseNext( null, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); for (int ii = 0; ii < continuationPoints.Count; ii++) { // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { continue; } // check if all references have been fetched. if (results[ii].References.Count == 0) { continue; } // save results. references.AddRange(results[ii].References); // check for continuation point. if (results[ii].ContinuationPoint != null) { revisedContiuationPoints.Add(results[ii].ContinuationPoint); } } // check if browsing must continue; revisedContiuationPoints = continuationPoints; } // check if unprocessed results exist. nodesToBrowse = unprocessedOperations; } // return complete list. return(references); } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return(null); } }
/// <summary> /// Displays the target of a browse operation in the control. /// </summary> private void Browse(NodeId startId) { if (m_browser == null || NodeId.IsNull(startId)) { Clear(); return; } List <ItemData> variables = new List <ItemData>(); // browse the references from the node and build list of variables. BeginUpdate(); foreach (ReferenceDescription reference in m_browser.Browse(startId)) { Node target = m_session.NodeCache.Find(reference.NodeId) as Node; if (target == null) { continue; } ReferenceTypeNode referenceType = m_session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode; Node typeDefinition = null; if ((target.NodeClass & (NodeClass.Variable | NodeClass.Object)) != 0) { typeDefinition = m_session.NodeCache.Find(reference.TypeDefinition) as Node; } else { typeDefinition = m_session.NodeCache.Find(m_session.NodeCache.TypeTree.FindSuperType(target.NodeId)) as Node; } ItemData item = new ItemData(referenceType, !reference.IsForward, target, typeDefinition); AddItem(item, GuiUtils.GetTargetIcon(m_browser.Session, reference), -1); if ((target.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) != 0) { variables.Add(item); } } EndUpdate(); // read the current value for any variables. if (variables.Count > 0) { ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (ItemData item in variables) { ReadValueId valueId = new ReadValueId(); valueId.NodeId = item.Target.NodeId; valueId.AttributeId = Attributes.Value; valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } DataValueCollection values; DiagnosticInfoCollection diagnosticInfos; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out values, out diagnosticInfos); ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); for (int ii = 0; ii < variables.Count; ii++) { variables[ii].Value = values[ii]; foreach (ListViewItem item in ItemsLV.Items) { if (Object.ReferenceEquals(item.Tag, variables[ii])) { UpdateItem(item, variables[ii]); break; } } } } }
/// <summary> /// Finds the targets for the specified reference. /// </summary> private static List <NodeId> FindTargetOfReference(Session session, List <NodeId> nodeIds, NodeId referenceTypeId, bool throwOnError) { try { // construct browse request. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); for (int ii = 0; ii < nodeIds.Count; ii++) { BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeIds[ii]; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = referenceTypeId; nodeToBrowse.IncludeSubtypes = false; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.None; nodesToBrowse.Add(nodeToBrowse); } // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, null, 1, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); List <NodeId> targetIds = new List <NodeId>(); ByteStringCollection continuationPoints = new ByteStringCollection(); for (int ii = 0; ii < nodeIds.Count; ii++) { targetIds.Add(null); // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { continue; } // check for continuation point. if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0) { continuationPoints.Add(results[ii].ContinuationPoint); } // get the node id. if (results[ii].References.Count > 0) { if (NodeId.IsNull(results[ii].References[0].NodeId) || results[ii].References[0].NodeId.IsAbsolute) { continue; } targetIds[ii] = (NodeId)results[ii].References[0].NodeId; } } // release continuation points. if (continuationPoints.Count > 0) { session.BrowseNext( null, true, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); } //return complete list. return(targetIds); } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return(null); } }
public static async Task <Tuple <TClientResponse, bool> > RunWithAbortAsync <TClientResponse, TClient>(int delayBeforeCheck, Func <Task <TClientResponse> > func, ClientBase <TClient> cleintBase) where TClient : class { var statusChecker = new StatusChecker(2); TimerCallback tcb = statusChecker.CheckStatus3 <TClient>; using (var stateTimer = new Timer(tcb, cleintBase, 1000, delayBeforeCheck)) { var clientResponse = await func().ConfigureAwait(false); stateTimer.Change(Timeout.Infinite, Timeout.Infinite); return(Tuple.Create(clientResponse, statusChecker.IsAborted)); } }
/// <summary> /// 读取一个节点的指定属性 /// </summary> /// <param name="nodeId"></param> /// <param name="attribute"></param> /// <returns></returns> private DataValue ReadNoteDataValueAttributes(NodeId nodeId, uint attribute) { NodeId sourceId = nodeId; ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = sourceId; nodeToRead.AttributeId = attribute; nodesToRead.Add(nodeToRead); int startOfProperties = nodesToRead.Count; // find all of the pror of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription(); nodeToBrowse1.NodeId = sourceId; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = 0; nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse1); // fetch property references from the server. ReferenceDescriptionCollection references = FormUtils.Browse(m_OpcUaClient.Session, nodesToBrowse, false); if (references == null) { return(null); } for (int ii = 0; ii < references.Count; ii++) { // ignore external references. if (references[ii].NodeId.IsAbsolute) { continue; } ReadValueId nodeToRead2 = new ReadValueId(); nodeToRead2.NodeId = (NodeId)references[ii].NodeId; nodeToRead2.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead2); } // read all values. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_OpcUaClient.Session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); return(results[0]); }
private void OnRecieveLocalScripts(ClientBase sender, SendLocalScripts packet) { Console.WriteLine("Recieved packet " + packet.code[1]); for (int i = 0; i < packet.eventId.Length; i++) { int eventId = packet.eventId[i]; string code = packet.code[i]; if (code.Trim() == "") { continue; } Game1.worldActionScript.LoadCode(code); Action func = Game1.worldActionScript.Compile(); switch ((EventTypes)eventId) { case EventTypes.OnLoad: //Parent.OnAddedEvent -= functions[eventId]; //Parent.OnAddedEvent += OnlyThis; //TODO: this may not work if this object was instantiated in the client. OnlyThis(Parent); break; case EventTypes.OnUpdate: Parent.OnUpdateEvent -= functions[eventId]; Parent.OnUpdateEvent += OnlyThis; functions[eventId] = OnlyThis; break; case EventTypes.OnCollisionStay: Collider collider = Parent.GetFirst <Collider>(); collider.ContinouslyCheckCollisions = true; collider.OnCollisionStay -= onCollisionStay; collider.OnCollisionStay += Collider_OnCollisionStay; break; case EventTypes.OnStringMessage: //TODO: Have an UnOn function in the low level library. Parent.On <WUIShared.Packets.ScriptSendString>(OnHandleScriptSendString); break; default: break; } void OnlyThis(GameObject go) { Game1.worldActionScript.SetVariable(new string[] { "this" }, Game1.worldActionScript.GetVariable(new string[] { go.name })); func(); } void Collider_OnCollisionStay(Collider go, Collider other) { if (go.Parent == null || other.Parent == null) { return; } Game1.worldActionScript.SetVariable(new string[] { "other" }, Game1.worldActionScript.GetVariable(new string[] { other.Parent.name })); Game1.worldActionScript.SetVariable(new string[] { "this" }, Game1.worldActionScript.GetVariable(new string[] { go.Parent.name })); func(); } void OnHandleScriptSendString(ClientBase sender2, ScriptSendString packet2) { string[] path = new string[] { "args" }; Game1.worldActionScript.SetVariable(new string[] { "this" }, Game1.worldActionScript.GetVariable(new string[] { Parent.name })); Game1.worldActionScript.SetVariable(path, new Dictionary <string, object>() { { "message", packet2.message } }); func(); Game1.worldActionScript.SetVariable(path, null); //To force it to be shortlived. (Fast GC). } } }
/// <summary> /// 读取一个节点的所有属性 /// </summary> /// <param name="tag">节点值</param> /// <returns>所有的数据</returns> public DataValue[] ReadNoteDataValueAttributes(string tag) { NodeId sourceId = new NodeId(tag); ReadValueIdCollection nodesToRead = new ReadValueIdCollection( ); // attempt to read all possible attributes. // 尝试着去读取所有可能的特性 for (uint ii = Attributes.NodeId; ii <= Attributes.UserExecutable; ii++) { ReadValueId nodeToRead = new ReadValueId( ); nodeToRead.NodeId = sourceId; nodeToRead.AttributeId = ii; nodesToRead.Add(nodeToRead); } int startOfProperties = nodesToRead.Count; // find all of the pror of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription( ); nodeToBrowse1.NodeId = sourceId; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = 0; nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( ); nodesToBrowse.Add(nodeToBrowse1); // fetch property references from the server. ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false); if (references == null) { return(new DataValue[0]); } for (int ii = 0; ii < references.Count; ii++) { // ignore external references. if (references[ii].NodeId.IsAbsolute) { continue; } ReadValueId nodeToRead = new ReadValueId( ); nodeToRead.NodeId = (NodeId)references[ii].NodeId; nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); } // read all values. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); return(results.ToArray( )); }
public void HandleClient(ClientBase client) { client.On <SaveWorldPacket>(SaveWorld_Requested); }
public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container) { HtmlDocument doc = container.ResponseHtml.Value; HtmlNode message = doc.DocumentNode.SelectSingleNode("//div[@class='detail_msg']"); if (message == null) { yield break; } OGameClient oClient = (OGameClient)client; // Message info int messageId = message.GetAttributeValue("data-msg-id", 0); MessageTabType tabType = MessageTabType.FleetsEspionage; string dateText = message.SelectSingleNode(".//span[contains(@class, 'msg_date')]").InnerText; DateTime date = DateTime.ParseExact(dateText, "dd.MM.yyyy HH:mm:ss", oClient.ServerCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); EspionageReport result = new EspionageReport { MessageId = messageId, TabType = tabType, Sent = new DateTimeOffset(date).Add(-oClient.Settings.ServerUtcOffset).ToOffset(oClient.Settings.ServerUtcOffset) }; // Establish location HtmlNode locationLink = message.SelectSingleNode(".//a[contains(@href, 'page=galaxy')]"); string locationType = locationLink.SelectSingleNode("./figure").GetCssClasses(s => s == "moon" || s == "planet").First(); CoordinateType coordinateType = locationType == "moon" ? CoordinateType.Moon : CoordinateType.Planet; result.Coordinate = Coordinate.Parse(locationLink.InnerText, coordinateType); // Parts HtmlNodeCollection partsNodesList = message.SelectNodes(".//ul[@data-type and not(./li[@class='detail_list_fail'])]"); Dictionary <string, HtmlNode> partsNodes = partsNodesList.ToDictionary(s => s.GetAttributeValue("data-type", "")); // Parts - Resources HtmlNode details; if (partsNodes.TryGetValue("resources", out details)) { HtmlNodeCollection values = details.SelectNodes(".//span[@class='res_value']"); Debug.Assert(values.Count == 4); var oneThousandAdd = oClient.ServerCulture.NumberFormat.NumberGroupSeparator + "000"; string[] vals = values.Select(s => s.InnerText .Replace("M", oneThousandAdd) .Replace("Bn", oneThousandAdd + oneThousandAdd)).ToArray(); Resources resources = new Resources { Metal = int.Parse(vals[0], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Crystal = int.Parse(vals[1], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Deuterium = int.Parse(vals[2], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Energy = int.Parse(vals[3], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture) }; result.Resources = resources; result.Details |= ReportDetails.Resources; } // Parts - Ships if (partsNodes.TryGetValue("ships", out details)) { result.DetectedShips = ParseList <ShipType>(oClient, details); result.Details |= ReportDetails.Ships; } // Parts - Defense if (partsNodes.TryGetValue("defense", out details)) { result.DetectedDefence = ParseList <DefenceType>(oClient, details); result.Details |= ReportDetails.Defense; } // Parts - Buildings if (partsNodes.TryGetValue("buildings", out details)) { result.DetectedBuildings = ParseList <BuildingType>(oClient, details); result.Details |= ReportDetails.Buildings; } // Parts - Research if (partsNodes.TryGetValue("research", out details)) { result.DetectedResearch = ParseList <ResearchType>(oClient, details); result.Details |= ReportDetails.Research; } // Return yield return(result); }
private void SaveWorld_Requested(ClientBase sender, SaveWorldPacket packet) { SaveWorld(packet.name); }
/// <summary> /// Adds the properties to the control. /// </summary> private void AddProperties() { // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); Browser browser = new Browser(m_session); browser.BrowseDirection = BrowseDirection.Forward; browser.ReferenceTypeId = ReferenceTypeIds.HasProperty; browser.IncludeSubtypes = true; browser.NodeClassMask = (int)NodeClass.Variable; browser.ContinueUntilDone = true; ReferenceDescriptionCollection references = browser.Browse(m_nodeId); foreach (ReferenceDescription reference in references) { ReadValueId valueId = new ReadValueId(); valueId.NodeId = (NodeId)reference.NodeId; valueId.AttributeId = Attributes.Value; valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } // check for empty list. if (nodesToRead.Count == 0) { return; } // read values. DataValueCollection values; DiagnosticInfoCollection diagnosticInfos; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out values, out diagnosticInfos); ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // update control. for (int ii = 0; ii < nodesToRead.Count; ii++) { NodeField field = new NodeField(); field.ValueId = nodesToRead[ii]; field.Name = references[ii].ToString(); field.Value = values[ii].Value; field.StatusCode = values[ii].StatusCode; if (diagnosticInfos != null && diagnosticInfos.Count > ii) { field.DiagnosticInfo = diagnosticInfos[ii]; } AddItem(field, "Property", -1); } }
/// <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); } } } }
//Proxy extensions public static void SetContext <T>(this ClientBase <T> proxy, string key, string value) where T : class { SetContext(proxy.InnerChannel, key, value); }
/// <summary> /// Reads the arguments for the method. /// </summary> private void ReadArguments(NodeId nodeId) { m_inputArguments = null; m_outputArguments = null; // build list of references to browse. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasProperty; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = (uint)NodeClass.Variable; nodeToBrowse.ResultMask = (uint)BrowseResultMask.BrowseName; nodesToBrowse.Add(nodeToBrowse); // find properties. ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, nodesToBrowse, false); // build list of properties to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); for (int ii = 0; references != null && ii < references.Count; ii++) { ReferenceDescription reference = references[ii]; // ignore out of server references. if (reference.NodeId.IsAbsolute) { continue; } // ignore other properties. if (reference.BrowseName != Opc.Ua.BrowseNames.InputArguments && reference.BrowseName != Opc.Ua.BrowseNames.OutputArguments) { continue; } ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)reference.NodeId; nodeToRead.AttributeId = Attributes.Value; nodeToRead.Handle = reference; nodesToRead.Add(nodeToRead); } // method has no arguments. if (nodesToRead.Count == 0) { return; } // read the arguments. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // save the results. for (int ii = 0; ii < results.Count; ii++) { ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle; if (StatusCode.IsGood(results[ii].StatusCode)) { if (reference.BrowseName == Opc.Ua.BrowseNames.InputArguments) { m_inputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue <ExtensionObject[]>(null), typeof(Argument)); } if (reference.BrowseName == Opc.Ua.BrowseNames.OutputArguments) { m_outputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue <ExtensionObject[]>(null), typeof(Argument)); } } } // set default values for input arguments. if (m_inputArguments != null) { foreach (Argument argument in m_inputArguments) { argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree); } } }
public static IDictionary <string, string> UpdateContext <T>(this ClientBase <T> proxy, string key, string value) where T : class { return(UpdateContext(proxy.InnerChannel, key, value)); }
public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container) { var doc = container.ResponseHtml.Value.DocumentNode; var leftContent = doc.SelectSingleNode(".//div[@class='left_content']"); var rightContent = doc.SelectSingleNode(".//div[@class='right_content']"); if (leftContent == null) { yield break; } AuctionStatus status = new AuctionStatus(); var auctionInfo = leftContent.SelectSingleNode("./p[@class='auction_info']"); var remaining = auctionInfo.SelectSingleNode("./span")?.InnerText ?? string.Empty; Match match = timeParser.Match(remaining); if (match.Success) { var time = int.Parse(match.Groups[1].Value); if (match.Groups[2].Value == "m") { status.MinutesRemaining = time; } else { status.NextIn = TimeSpan.FromSeconds(time); } } var bid = leftContent.SelectSingleNode("./div[contains(@class, 'currentSum')]"); status.CurrentBid = int.Parse(bid.InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture); var count = leftContent.SelectSingleNode("./div[contains(@class, 'numberOfBids')]"); status.BidCount = int.Parse(count.InnerText, NumberStyles.Integer); var bidder = leftContent.SelectSingleNode("./a[contains(@class, 'currentPlayer')]"); status.HighestBidderName = bidder.InnerText.Trim(); status.HighestBidderId = int.Parse(bidder.Attributes["data-player-id"]?.Value ?? "0"); var item = leftContent.SelectSingleNode(".//a[contains(@class, 'detail_button')]"); string reference = item.Attributes["ref"].Value; IEnumerable <ShopItem> all = ShopItem.All(); status.Item = all.Where(si => si.Reference == reference).FirstOrDefault(); var ownBid = rightContent.SelectSingleNode(".//td[contains(@class, 'js_alreadyBidden')]"); status.OwnBid = int.Parse(ownBid.InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture); var minBid = rightContent.SelectSingleNode(".//td[contains(@class, 'js_price')]"); status.MinimumBid = int.Parse(minBid.InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture); HtmlNodeCollection scriptBlocks = doc.SelectNodes("//script[@type='text/javascript' and not(@src)]"); if (scriptBlocks != null) { foreach (HtmlNode block in scriptBlocks) { Match tokenMatch = TokenRegex.Match(block.InnerText); if (tokenMatch.Success) { status.Token = tokenMatch.Groups[1].Value; break; } } } yield return(status); }
private IMethodReturn invoke(IMethodInvocation input, ClientBase<IVCSmyServerService> proxy) { var args = input.Arguments.Cast<object>().ToArray(); var result = input.MethodBase.Invoke(proxy, args); //моделируем закрытие канала, чтобы проверить корректность работы WCFCannel.Create() //при следующем вызове какого-либо метода IService2 через proxy //proxy.Close(); return input.CreateMethodReturn(result, args); }
public static void SetServiceBusCredentials <T>(this ClientBase <T> proxy, string issuer, string secret) where T : class { TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, secret); SetServiceBusCredentials(proxy, tokenProvider); }
private void InitRestClients() { RestClient = new RestClient(RootUrl + "api/"); RestClient.AddDefaultHeader("Authentication", _runner.ApiKey); RestClient.AddDefaultHeader("X-Api-Key", _runner.ApiKey); Series = new SeriesClient(RestClient, _runner.ApiKey); Releases = new ReleaseClient(RestClient, _runner.ApiKey); RootFolders = new ClientBase<RootFolderResource>(RestClient, _runner.ApiKey); Commands = new ClientBase<CommandResource>(RestClient, _runner.ApiKey); History = new ClientBase<HistoryResource>(RestClient, _runner.ApiKey); Indexers = new IndexerClient(RestClient, _runner.ApiKey); Episodes = new EpisodeClient(RestClient, _runner.ApiKey); NamingConfig = new ClientBase<NamingConfigResource>(RestClient, _runner.ApiKey, "config/naming"); Notifications = new NotificationClient(RestClient, _runner.ApiKey); }
public LogReceiverServerClientChannel(ClientBase <ILogReceiverOneWayClient> client) : base(client) { }
protected override void InitRestClients() { base.InitRestClients(); FileSystem = new ClientBase(RestClient, ApiKey, "filesystem"); }
public RealmListUpdater(ClientBase client) { m_client = client; }
public RealmListUpdater(ClientBase client, string pwd) { m_client = client; Password = pwd; }
/// <summary> /// Initializes a service client for a request to the specified server type. /// </summary> /// <param name="client"> /// An object representing a service client. /// </param> /// <param name="serviceAddress"> /// A string containing the service address. /// </param> /// <param name="credentials"> /// The credentials required to access the server. /// </param> public static void InitializeClient <TChannel>(ClientBase <TChannel> client, string serviceAddress, Credentials credentials) where TChannel : class { InitializeClient(client, ConfigurationSettings.GetSiteConfigurationSection( ).SiteSettings.Address, serviceAddress, credentials); }
protected override void InitRestClients() { base.InitRestClients(); DiskSpace = new ClientBase<DiskSpaceResource>(RestClient, ApiKey, "diskSpace"); }
/// <summary> /// Finds the targets for the specified reference. /// </summary> private static void UpdateInstanceDescriptions(Session session, List <InstanceDeclaration> instances, bool throwOnError) { try { ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); for (int ii = 0; ii < instances.Count; ii++) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = instances[ii].NodeId; nodeToRead.AttributeId = Attributes.Description; nodesToRead.Add(nodeToRead); nodeToRead = new ReadValueId(); nodeToRead.NodeId = instances[ii].NodeId; nodeToRead.AttributeId = Attributes.DataType; nodesToRead.Add(nodeToRead); nodeToRead = new ReadValueId(); nodeToRead.NodeId = instances[ii].NodeId; nodeToRead.AttributeId = Attributes.ValueRank; nodesToRead.Add(nodeToRead); } // start the browse operation. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // update the instances. for (int ii = 0; ii < nodesToRead.Count; ii += 3) { InstanceDeclaration instance = instances[ii / 3]; instance.Description = results[ii].GetValue <LocalizedText>(LocalizedText.Null).Text; instance.DataType = results[ii + 1].GetValue <NodeId>(NodeId.Null); instance.ValueRank = results[ii + 2].GetValue <int>(ValueRanks.Any); if (!NodeId.IsNull(instance.DataType)) { instance.BuiltInType = DataTypes.GetBuiltInType(instance.DataType, session.TypeTree); instance.DataTypeDisplayText = session.NodeCache.GetDisplayText(instance.DataType); if (instance.ValueRank >= 0) { instance.DataTypeDisplayText += "[]"; } } } } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } } }
protected override void InitRestClients() { base.InitRestClients(); Calendar = new ClientBase<EpisodeResource>(RestClient, ApiKey, "calendar"); }
public CiapiLatencyRecorder(ClientBase client, Tracker tracker) : base(client) { _tracker = tracker; }