public async Task AbleToMigrate_delayed_delivery_does_exist_should_indicate_no_problems() { var sut = new SqlTTimeoutsTarget(new TestLoggingAdapter(), connectionString, schema); await using var connection = new SqlConnection(connectionString); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = string.Format(@" CREATE TABLE [{1}].[{0}] ( RowVersion bigint IDENTITY(1,1) NOT NULL ); ", $"{ExistingEndpointName}.Delayed", schema); await command.ExecuteNonQueryAsync(); var info = new EndpointInfo { EndpointName = ExistingEndpointName, ShortestTimeout = DateTime.UtcNow.AddDays(3), LongestTimeout = DateTime.UtcNow.AddDays(5), Destinations = new List <string> { ExistingDestination } }; var result = await sut.AbleToMigrate(info); Assert.IsTrue(result.CanMigrate); }
public async Task AbleToMigrate_delayed_delivery_does_not_exist_should_indicate_problems() { var sut = new SqlTTimeoutsTarget(new TestLoggingAdapter(), connectionString, schema); await using var connection = new SqlConnection(connectionString); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = string.Format(@" IF OBJECT_ID('{0}.{1}', 'u') IS NOT NULL DROP TABLE {0}.{1}; ", $"{ExistingEndpointName}.Delayed", schema); await command.ExecuteNonQueryAsync(); var info = new EndpointInfo { EndpointName = ExistingEndpointName, ShortestTimeout = DateTime.UtcNow.AddDays(3), LongestTimeout = DateTime.UtcNow.AddDays(5), Destinations = new List <string> { ExistingDestination } }; var result = await sut.AbleToMigrate(info); Assert.IsFalse(result.CanMigrate); }
public async ValueTask <MigrationCheckResult> AbleToMigrate(EndpointInfo endpoint) { var migrationsResult = new MigrationCheckResult(); try { var table = client.GetTableReference(delayedDeliveryTableNameProvider.GetDelayedDeliveryTableName(endpoint.EndpointName)); var exists = await table.ExistsAsync(); if (!exists) { migrationsResult.Problems.Add($"Target delayed delivery table {delayedDeliveryTableNameProvider.GetDelayedDeliveryTableName(endpoint.EndpointName)} does not exist."); } } catch (StorageException ex) { migrationsResult.Problems.Add($"Unable to connect to the storage instance on account '{client.Credentials.AccountName}'. Verify the connection string. Exception message '{ex.Message}'"); } try { await EnsureStagingTableExists($"{delayedDeliveryTableNameProvider.GetStagingTableName(endpoint.EndpointName)}"); } catch (StorageException ex) { migrationsResult.Problems.Add($"Unable to create staging queue '{delayedDeliveryTableNameProvider.GetDelayedDeliveryTableName(endpoint.EndpointName)}staging'. Exception message '{ex.Message}'"); } return(migrationsResult); }
public void SetLookupReply(ILookupReplyPrx lookupReply) { // // Use a lookup reply proxy whose address matches the interface used to send multicast datagrams. // var single = new Ice.IEndpoint[1]; foreach (ILookupPrx key in new List <ILookupPrx>(_lookups.Keys)) { var info = (Ice.UDPEndpointInfo)key.Endpoints[0].GetInfo(); if (info.McastInterface.Length > 0) { foreach (IEndpoint q in lookupReply.Endpoints) { EndpointInfo r = q.GetInfo(); if (r is Ice.IPEndpointInfo && ((Ice.IPEndpointInfo)r).Host.Equals(info.McastInterface)) { single[0] = q; _lookups[key] = lookupReply.Clone(endpoints: single); } } } if (_lookups[key] == null) { // Fallback: just use the given lookup reply proxy if no matching endpoint found. _lookups[key] = lookupReply; } } }
public async Task CommunicationPost_UnparseablePayload_Returns400BadRequest(EndpointInfo endpoint) { // Arrange using var httpClient = CreateHttpClient(); var httpContent = new StringContent("{ bad Json", Encoding.UTF8, "application/json"); var correlationId = Guid.NewGuid().ToString(); // Act var response = await httpClient.PostAsync(endpoint.Path, httpContent, correlationId); // Assert response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var operationOutcome = await ParseOperationOutcome(response); var issue = operationOutcome.Issue.Single(); issue.Severity.Should().Be(OperationOutcome.IssueSeverity.Error); issue.Code.Should().Be(OperationOutcome.IssueType.Invalid); issue.Diagnostics.Should().Contain("Invalid Json encountered."); response.Headers.ShouldContainHeader("X-Correlation-ID", correlationId); }
private void RefreshMetadataAndContentUrl() { try { if (File.Exists(CacheFilePath) && (DateTime.Now - File.GetLastWriteTime(CacheFilePath)) < KEEP_CACHE_FILE_TIME) { m_endPointInfo = JsonConvert.DeserializeObject <EndpointInfo>(File.ReadAllText(CacheFilePath)); return; } } catch { } m_endPointInfo = m_oauth.GetJSONData <EndpointInfo>(CLOUDRIVE_MASTER_URL); try { if (m_endPointInfo.CustomerExists && m_endPointInfo.ContentUrl != null && m_endPointInfo.MetadataUrl != null) { File.WriteAllText(CacheFilePath, JsonConvert.SerializeObject(m_endPointInfo)); } } catch { } }
/// <summary> /// Test that no edge intersection is the endpoint of a closed line. /// To check this we compute the degree of each endpoint. /// The degree of endpoints of closed lines must be exactly 2. /// </summary> private bool HasClosedEndpointIntersection(GeometryGraph graph) { IDictionary endPoints = new SortedList(); for (IEdgeEnumerator i = graph.EdgeIterator; i.MoveNext();) { Edge e = i.Current; // int maxSegmentIndex = e.MaximumSegmentIndex; bool isClosed = e.IsClosed; Coordinate p0 = e.GetCoordinate(0); AddEndpoint(endPoints, p0, isClosed); Coordinate p1 = e.GetCoordinate(e.NumPoints - 1); AddEndpoint(endPoints, p1, isClosed); } for (IEnumerator i = endPoints.Values.GetEnumerator(); i.MoveNext();) { EndpointInfo eiInfo = (EndpointInfo)i.Current; if (eiInfo.isClosed && eiInfo.degree != 2) { return(true); } } return(false); }
/// <summary> /// Helper method to copy data from an <see cref="EndpointData"/> /// to an <see cref="EndpointInfo"/> instance. /// </summary> /// <param name="info">The full data instance.</param> /// <param name="data">The data instance.</param> public static void CopyFrom(this EndpointInfo info, EndpointData data) { info.Link = data?.Link; info.Name = data?.Name; info.RoomId = data?.Room; info.Tags = data?.Tags; }
public Task <DeviceAction> PerformActionAsync(DeviceAction action) { return(Task.Run(() => { DeviceAction devparam = new DeviceAction(); // find protocol //TODO protocol priority EndpointInfo epi = action.Device.EndpInfo; if (epi.SupportsSconnProtocol) { } else if (epi.SupportsRESTfulProtocol) { } else if (epi.SupportsCoAPProtocol) { } else if (epi.SupportsMQTTProtocol) { } else if (epi.SupportsAllJoynProtocol) { } //perform action //parse result return devparam; })); }
protected WSEndpointInfo(EndpointInfo underlying, int timeout, bool compress, string resource) : base(underlying, timeout, compress) { this.resource = resource; }
/// <summary> /// Activate or deactivate an endpoint /// </summary> /// <param name="endpointId"></param> /// <param name="checkedValue"></param> /// <returns></returns> private async Task SetActivationAsync(EndpointInfo endpoint) { string endpointId = endpoint.EndpointModel.Registration.Id; if (!IsEndpointActivated(endpoint)) { try { await RegistryService.ActivateEndpointAsync(endpointId); } catch (Exception e) { if (e.Message.Contains("404103")) { Status = "The endpoint is not available."; } else { Status = e.Message; } } } else { try { await RegistryService.DeactivateEndpointAsync(endpointId); } catch (Exception e) { Status = e.Message; } } }
public void PickEndpoint_DeficitRoundRobin_Works() { var loadBalancer = Create <LoadBalancer>(); var first = new EndpointInfo("1"); var second = new EndpointInfo("2"); var third = new EndpointInfo("3"); var endpoints = new[] { first, second, third }; var quanta = new Dictionary <EndpointInfo, int> { [first] = 1, [second] = 2, [third] = 3 }; var options = new BackendConfig.BackendLoadBalancingOptions(LoadBalancingMode.DeficitRoundRobin, deficitRoundRobinQuanta: quanta); // choose first X 1 var next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(first, next); // choose second X 2 next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(second, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(second, next); // choose third X 3 next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); // choose first X 1 next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(first, next); // choose second X 2 next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(second, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(second, next); // choose third X 3 next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); next = loadBalancer.PickEndpoint(endpoints.ToList().AsReadOnly(), options); Assert.Equal(third, next); }
protected TCPEndpointInfo(EndpointInfo underlying, int timeout, bool compress, string host, int port, string sourceAddress) : base(underlying, timeout, compress, host, port, sourceAddress) { }
protected OpaqueEndpointInfo(EndpointInfo underlying, int timeout, bool compress, EncodingVersion rawEncoding, byte[] rawBytes) : base(underlying, timeout, compress) { this.rawEncoding = rawEncoding; this.rawBytes = rawBytes; }
/// <summary> /// Add an endpoint to the map, creating an entry for it if none exists. /// </summary> /// <param name="endPoints"></param> /// <param name="p"></param> /// <param name="isClosed"></param> private void AddEndpoint(IDictionary endPoints, ICoordinate p, bool isClosed) { EndpointInfo eiInfo = (EndpointInfo) endPoints[p]; if (eiInfo == null) { eiInfo = new EndpointInfo(p); endPoints.Add(p, eiInfo); } eiInfo.AddEndpoint(isClosed); }
public void PickEndpoint_WithoutEndpoints_Null() { var loadBalancer = Create <LoadBalancer>(); var endpoints = new EndpointInfo[0]; var options = new BackendConfig.BackendLoadBalancingOptions((LoadBalancingMode)(-1)); var result = loadBalancer.PickEndpoint(endpoints, in options); Assert.Null(result); }
/// <summary> /// Add an endpoint to the map, creating an entry for it if none exists. /// </summary> /// <param name="endPoints"></param> /// <param name="p"></param> /// <param name="isClosed"></param> private void AddEndpoint(IDictionary endPoints, ICoordinate p, bool isClosed) { EndpointInfo eiInfo = (EndpointInfo)endPoints[p]; if (eiInfo == null) { eiInfo = new EndpointInfo(p); endPoints.Add(p, eiInfo); } eiInfo.AddEndpoint(isClosed); }
/// <summary> /// Helper method to convert an <see cref="EndpointInfo"/> instance /// to an <see cref="EndpointData"/> instance. /// </summary> /// <param name="info">The full data instance.</param> /// <returns>The converted data.</returns> public static EndpointData ToEndpointData(this EndpointInfo info) { return(new EndpointData() { Uuid = info?.Uuid, Link = info?.Link, Name = info?.Name, Room = info?.RoomId, Tags = info?.Tags }); }
private static TCPEndpointInfo getTCPEndpointInfo(EndpointInfo info) { for (; info != null; info = info.Underlying) { if (info is TCPEndpointInfo) { return(info as TCPEndpointInfo); } } return(null); }
public Device DeviceForMqttClient(MqttClient client) { Device dev = new Device(); dev.DeviceName = client.ClientId; EndpointInfo info = new EndpointInfo(); //info.Hostname = client.clientHostname; dev.EndpInfo = info; return(dev); }
/// <summary> /// Add an endpoint to the map, creating an entry for it if none exists. /// </summary> /// <param name="endPoints"></param> /// <param name="p"></param> /// <param name="isClosed"></param> private static void AddEndpoint(IDictionary <Coordinate, EndpointInfo> endPoints, Coordinate p, bool isClosed) { EndpointInfo eiInfo; if (!endPoints.TryGetValue(p, out eiInfo)) { eiInfo = new EndpointInfo(p); endPoints.Add(p, eiInfo); } eiInfo.AddEndpoint(isClosed); }
protected IPEndpointInfo(EndpointInfo underlying, int timeout, bool compress, string host, int port, string sourceAddress) : base(underlying, timeout, compress) { Host = host; Port = port; SourceAddress = sourceAddress; }
public ValueTask <MigrationCheckResult> AbleToMigrate(EndpointInfo endpoint) { EndpointWasVerified = true; var problems = problemsToReturn ?? new List <string>(); var result = new MigrationCheckResult { Problems = problems }; return(new ValueTask <MigrationCheckResult>(result)); }
protected UDPEndpointInfo(EndpointInfo underlying, int timeout, bool compress, string host, int port, string sourceAddress, string mcastInterface, int mcastTtl) : base(underlying, timeout, compress, host, port, sourceAddress) { this.mcastInterface = mcastInterface; this.mcastTtl = mcastTtl; }
public void PickEndpoint_FirstWithoutEndpoints_Works() { // Arrange var loadBalancer = Create <LoadBalancer>(); var endpoints = new EndpointInfo[0]; var options = new BackendConfig.BackendLoadBalancingOptions(BackendConfig.BackendLoadBalancingOptions.LoadBalancingMode.First); // Act var result = loadBalancer.PickEndpoint(endpoints, endpoints, in options); // Assert result.Should().BeNull(); }
internal override void OnAddedEndpointInfo(EndpointInfo info) { _outputHelper.WriteLine($"Added endpoint info to collection: {info.DebuggerDisplay}"); lock (_addedEndpointInfoSources) { foreach (var source in _addedEndpointInfoSources) { source.TrySetResult(info); } _addedEndpointInfoSources.Clear(); } }
public static Device GetFakeAlarmDevice() { Device fakeDevice = new Device(); DeviceCredentials fakeCredentials = new DeviceCredentials(); fakeCredentials.Fake(); fakeDevice.Credentials = fakeCredentials; EndpointInfo fakeEndpointInfo = new EndpointInfo(); fakeEndpointInfo.Fake(); fakeDevice.EndpInfo = fakeEndpointInfo; fakeDevice.Fake(); return(fakeDevice);; }
public bool EndpointRemove(EndpointInfo endp) { try { iotSharedEntityContext <EndpointInfo> propCont = new iotSharedEntityContext <EndpointInfo>(); propCont.Delete(endp); return(true); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(false); } }
public void PickEndpoint_UnsupportedMode_Throws() { // Arrange var loadBalancer = Create <LoadBalancer>(); var endpoints = new EndpointInfo[0]; var options = new BackendConfig.BackendLoadBalancingOptions((BackendConfig.BackendLoadBalancingOptions.LoadBalancingMode)(-1)); // Act Action action = () => loadBalancer.PickEndpoint(endpoints, endpoints, in options); // Assert action.Should().ThrowExactly <ReverseProxyException>() .Which.Message.Should().Be("Load balancing mode '-1' is not supported."); }
/************************ CUSTOM CROSS QUERY ********************/ public Device DeviceWithEndpoint(EndpointInfo endp) { try { iotContext cont = new iotContext(); Device stored = cont.Devices.Where(d => d.EndpInfo.Hostname.Equals(endp.Hostname) && d.EndpInfo.Port == endp.Port).FirstOrDefault(); return(stored); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(new Device()); } }
protected override void DrawEndpointHeader(EndpointInfo docEntry) { if (docEntry.Deprecated) { _document.H1().Bold().Deleted().SetText($"{docEntry.HttpMethod} {docEntry.EndpointPath}"); _document.P().Bold().Deleted().SetText(docEntry.Summary); _document.P().Bold().SetText("Deprecated"); } else { _document.H1().Bold().SetText($"{docEntry.HttpMethod} {docEntry.EndpointPath}"); _document.P().Bold().SetText(docEntry.Summary); } }
private void RefreshMetadataAndContentUrl() { try { if (File.Exists(CacheFilePath) && (DateTime.Now - File.GetLastWriteTime(CacheFilePath)) < KEEP_CACHE_FILE_TIME) { m_endPointInfo = JsonConvert.DeserializeObject<EndpointInfo>(File.ReadAllText(CacheFilePath)); return; } } catch { } m_endPointInfo = m_oauth.GetJSONData<EndpointInfo>(CLOUDRIVE_MASTER_URL); try { if (m_endPointInfo.CustomerExists && m_endPointInfo.ContentUrl != null && m_endPointInfo.MetadataUrl != null) File.WriteAllText(CacheFilePath, JsonConvert.SerializeObject(m_endPointInfo)); } catch { } }
public void SendNotification( IUser sender, EndpointInfo recipientInfo, string objectUrl, string summaryView, string documentType, string verb, string changeData, int maxRetries, TimeSpan transportErrorDelay) { HttpWebClient webClient = new HttpWebClient(); Action retry = delegate() { if (maxRetries > 0) ThreadPool.QueueUserWorkItem(delegate(object state) { Thread.Sleep(transportErrorDelay); SendNotification( sender, recipientInfo, objectUrl, summaryView, documentType, verb, changeData, maxRetries - 1, transportErrorDelay); }); }; webClient.BeginPost( recipientInfo.Endpoint, delegate(HttpResponseHandler response) { string responseString = response.AsString(); if (response.StatusCode == System.Net.HttpStatusCode.OK) // success! { } else if (response.StatusCode == System.Net.HttpStatusCode.Accepted) // errors log.Warn("Errors occured when sending a notification: " + responseString); else if (response.StatusCode == System.Net.HttpStatusCode.PreconditionFailed && "senderToken" == responseString) { SendNotification( sender, true, recipientInfo.RecipientIdentities, objectUrl, summaryView, documentType, verb, changeData, maxRetries, transportErrorDelay); } else retry(); }, delegate(Exception e) { }, new KeyValuePair<string, string>("senderToken", recipientInfo.SenderToken), new KeyValuePair<string, string>("recipients", JsonWriter.Serialize(recipientInfo.RecipientIdentities)), new KeyValuePair<string, string>("objectUrl", objectUrl), new KeyValuePair<string, string>("summaryView", summaryView), new KeyValuePair<string, string>("documentType", documentType), new KeyValuePair<string, string>("verb", verb), new KeyValuePair<string, string>("changeData", changeData), GenerateSecurityTimestamp()); }
/// <summary> /// Continues to get more information about recipients after all information about endpoints is loaded /// </summary> /// <param name="sender"></param> /// <param name="recipientIdentities"></param> /// <param name="loadedEndpoints"></param> /// <param name="callback"></param> private void GetRecipientInfos( IUserOrGroup sender, bool forceRefresh, HashSet<string> recipientIdentities, LockFreeQueue<Endpoints> loadedEndpoints, ParticleEndpoint particleEndpoint, Action<EndpointInfo> callback, Action<IEnumerable<string>> errorCallback, Action<Exception> exceptionCallback) { try { // All of the unique particle endpoints, with the recipients at each Dictionary<string, List<string>> recipientsAtEndpoints = new Dictionary<string, List<string>>(); Dictionary<string, string> establishTrustEndpoints = new Dictionary<string, string>(); Dictionary<string, string> requestedEndpoints = new Dictionary<string, string>(); Endpoints particleEndpoints; while (loadedEndpoints.Dequeue(out particleEndpoints)) { string endpoint; if (particleEndpoints.TryGetEndpoint(particleEndpoint, out endpoint)) { List<string> users; if (recipientsAtEndpoints.TryGetValue(particleEndpoints[ParticleEndpoint.ReceiveNotification], out users)) users.Add(particleEndpoints.OpenIdOrWebFinger); else { users = new List<string>(); users.Add(particleEndpoints.OpenIdOrWebFinger); recipientsAtEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = users; establishTrustEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = particleEndpoints[ParticleEndpoint.EstablishTrust]; requestedEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = particleEndpoints[particleEndpoint]; } } } if (!forceRefresh) { // Load for situations where trust is already established // copy is to avoid locked the database this.persistedUserManagerData.Read(userManagerData => { var recipientUser = userManagerData.GetUser(sender.Id); foreach (var recipientAndToken in recipientUser.receiveNotificationEndpointsBySenderToken.Where( r => recipientsAtEndpoints.ContainsKey(r.Value))) { var receiveNotificationEndpoint = recipientAndToken.Value; var senderToken = recipientAndToken.Key; string endpoint; if (requestedEndpoints.TryGetValue(receiveNotificationEndpoint, out endpoint)) { var recipientInfo = new EndpointInfo() { RecipientIdentities = recipientsAtEndpoints[receiveNotificationEndpoint], Endpoint = endpoint, SenderToken = senderToken }; recipientsAtEndpoints.Remove(receiveNotificationEndpoint); callback(recipientInfo); } } }); } // For situations where trust isn't established, establish trust and then use the callback foreach (KeyValuePair<string, List<string>> endpointAndRecipients in recipientsAtEndpoints) GetRecipientInfos( sender, endpointAndRecipients.Key, establishTrustEndpoints[endpointAndRecipients.Key], endpointAndRecipients.Value, requestedEndpoints[endpointAndRecipients.Key], callback, errorCallback); } catch (Exception e) { exceptionCallback(e); } }
/// <summary> /// Add an endpoint to the map, creating an entry for it if none exists. /// </summary> /// <param name="endPoints"></param> /// <param name="p"></param> /// <param name="isClosed"></param> private static void AddEndpoint(IDictionary<Coordinate, EndpointInfo> endPoints, Coordinate p, bool isClosed) { EndpointInfo eiInfo; if (!endPoints.TryGetValue(p, out eiInfo)) { eiInfo = new EndpointInfo(p); endPoints.Add(p, eiInfo); } eiInfo.AddEndpoint(isClosed); }
/// <summary> /// Establishes trust as part of GetRecipientInfos when trust isn't established /// </summary> /// <param name="sender"></param> /// <param name="receiveNotificationEndpoint"></param> /// <param name="recipients"></param> /// <param name="callback"></param> private void GetRecipientInfos( IUserOrGroup sender, string receiveNotificationEndpoint, string establishTrustEndpoint, List<string> recipients, string requestedEndpoint, Action<EndpointInfo> callback, Action<IEnumerable<string>> errorCallback) { this.BeginEstablishTrust(sender, receiveNotificationEndpoint, establishTrustEndpoint, delegate(string senderToken) { var recipientInfo = new EndpointInfo() { RecipientIdentities = recipients, Endpoint = requestedEndpoint, SenderToken = senderToken }; callback(recipientInfo); }, delegate(Exception e) { log.Error( string.Format("Could not establish trust between {0} and {1}", sender.Name, StringGenerator.GenerateCommaSeperatedList(recipients)), e); errorCallback(recipients); }); }