static void PublishAvailabilityEvent(ServiceEndpoint[] endpoints, Action <Uri, string, string, Uri[]> notification) { Action <ServiceEndpoint> notify = (endpoint) => { if (endpoint is DiscoveryEndpoint || endpoint is ServiceMetadataEndpoint || endpoint.Contract.ContractType == typeof(IMetadataExchange)) { return; } Uri[] scopes = DiscoveryHelper.LookupScopes(endpoint); notification(endpoint.Address.Uri, endpoint.Contract.Name, endpoint.Contract.Namespace, scopes); }; Action publish = () => { try { endpoints.ParallelForEach(notify); } catch { Trace.WriteLine("Could not announce availability of service"); } finally { (notification.Target as ICommunicationObject).Close(); } }; Task.Run(publish); }
public void ImportDiscoveryResultForProfile( int profileID, bool deleteProfileAfterImport, DiscoveryImportManager.CallbackDiscoveryImportFinished callback = null, bool checkLicenseLimits = false, Guid?importID = null) { IList <IDiscoveryPlugin> discoveryPlugins = DiscoveryHelper.GetOrderedDiscoveryPlugins(); SortedDictionary <int, List <IDiscoveryPlugin> > orderedPlugins = DiscoveryPluginHelper.GetOrderedPlugins(discoveryPlugins, (IList <DiscoveryPluginInfo>)DiscoveryHelper.GetDiscoveryPluginInfos()); DiscoveryResultBase result1 = this.FilterIgnoredItems(DiscoveryResultManager.GetDiscoveryResult(profileID, discoveryPlugins)); Guid importId = Guid.NewGuid(); if (importID.HasValue) { importId = importID.Value; } DiscoveryImportManager.CallbackDiscoveryImportFinished callbackAfterImport = callback; if (deleteProfileAfterImport) { callbackAfterImport = (DiscoveryImportManager.CallbackDiscoveryImportFinished)((result, id, status) => { this.DeleteOrionDiscoveryProfile(result.get_ProfileID()); if (callback == null) { return; } callback(result, id, status); }); } DiscoveryImportManager.StartImport(importId, result1, orderedPlugins, checkLicenseLimits, callbackAfterImport); }
public void OnDiscoveryRequest(string contractName, string contractNamespace, Uri[] scopesToMatch) { IDiscoveryCallback callback = OperationContext.Current.GetCallbackChannel <IDiscoveryCallback>(); foreach (ServiceEndpoint endpoint in Endpoints) { if (endpoint.Contract.Name == contractName && endpoint.Contract.Namespace == contractNamespace) { Uri[] scopes = DiscoveryHelper.LookupScopes(endpoint); if (scopesToMatch != null) { bool scopesMatched = true; foreach (Uri scope in scopesToMatch) { if (scopes.Any(uri => uri.AbsoluteUri == scope.AbsoluteUri) == false) { scopesMatched = false; break; } } if (scopesMatched == false) { continue; } } callback.OnDiscoveryResponse(endpoint.Address.Uri, contractName, contractNamespace, scopes); } } }
// Token: 0x06000622 RID: 1570 RVA: 0x00024EF0 File Offset: 0x000230F0 public void ImportDiscoveryResultForProfile(int profileID, bool deleteProfileAfterImport, DiscoveryImportManager.CallbackDiscoveryImportFinished callback = null, bool checkLicenseLimits = false, Guid?importID = null) { IList <IDiscoveryPlugin> orderedDiscoveryPlugins = DiscoveryHelper.GetOrderedDiscoveryPlugins(); SortedDictionary <int, List <IDiscoveryPlugin> > orderedPlugins = DiscoveryPluginHelper.GetOrderedPlugins(orderedDiscoveryPlugins, DiscoveryHelper.GetDiscoveryPluginInfos()); DiscoveryResultBase discoveryResult = DiscoveryResultManager.GetDiscoveryResult(profileID, orderedDiscoveryPlugins); DiscoveryResultBase result2 = this.FilterIgnoredItems(discoveryResult); Guid importId = Guid.NewGuid(); if (importID != null) { importId = importID.Value; } DiscoveryImportManager.CallbackDiscoveryImportFinished callbackAfterImport = callback; if (deleteProfileAfterImport) { callbackAfterImport = delegate(DiscoveryResultBase result, Guid id, StartImportStatus status) { this.DeleteOrionDiscoveryProfile(result.ProfileID); if (callback != null) { callback(result, id, status); } }; } DiscoveryImportManager.StartImport(importId, result2, orderedPlugins, checkLicenseLimits, callbackAfterImport); }
void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ApplicationConfig.RegisterConfig("development"); DiscoveryHelper.RegisterDiscoveryClient(ApplicationConfig.Configuration); }
public void Can_Init_Memento_With_Existing_Params() { var neighbours = DiscoveryHelper.MockNeighbours(); var memento = new HastingsMemento(_peer, neighbours); memento.Peer.Should().Be(_peer); memento.Neighbours.Should().Contain(neighbours); memento.Neighbours.Should().HaveCount(Constants.NumberOfRandomPeers); }
public DiscoveryTestBuilder WithPeerRepository(IPeerRepository peerRepository = default, bool mock = false) { _peerRepository = peerRepository == default(IPeerRepository) && mock == false ? Substitute.For <IPeerRepository>() : peerRepository == null ? _peerRepository = DiscoveryHelper.MockPeerRepository() : _peerRepository = peerRepository; return(this); }
public DiscoveryTestBuilder WithPeerMessageCorrelationManager(IPeerMessageCorrelationManager peerMessageCorrelationManager = default, IReputationManager reputationManager = default, IMemoryCache memoryCache = default, IChangeTokenProvider changeTokenProvider = default) { _peerCorrelationManager = peerMessageCorrelationManager ?? DiscoveryHelper.MockCorrelationManager(_scheduler, reputationManager, memoryCache, changeTokenProvider, _logger); return(this); }
public void Can_Restore_State_From_Memento_And_Assign_New_CorrelationId() { var memento = DiscoveryHelper.MockMemento(); var originator = new HastingsOriginator(memento); originator.RestoreMemento(memento); originator.Peer.Should().Be(memento.Peer); originator.Neighbours.Should().BeEquivalentTo(memento.Neighbours); originator.PnrCorrelationId.Should().NotBe(default);
public DiscoveryTestBuilder WithDns(IDns dnsClient = default, bool mock = false, IPeerSettings peerSettings = default) { _dnsClient = dnsClient == default(IDns) && mock == false ? Substitute.For <IDns>() : DiscoveryHelper.MockDnsClient(_peerSettings = _peerSettings == null && peerSettings == default(IPeerSettings) ? PeerSettingsHelper.TestPeerSettings() : peerSettings); return(this); }
public void Can_Create_Memento_From_Current_State() { var memento = DiscoveryHelper.SubMemento(_peer); var originator = new HastingsOriginator(memento); var stateMemento = originator.CreateMemento(); stateMemento.Peer.Should().Be(_peer); stateMemento.Neighbours .Should() .BeEquivalentTo(memento.Neighbours); }
public void Can_Add_New_Mementos_To_Caretaker() { var careTaker = new HastingsCareTaker(); var stack = new Stack <IHastingsMemento>(); stack.Push(DiscoveryHelper.SubMemento(_ownNode)); var history = DiscoveryHelper.MockMementoHistory(stack); history.ToList().ForEach(m => careTaker.Add(m)); careTaker.HastingMementoList.Should().Contain(history); }
public DiscoveryTestBuilder WithStepProposal(IHastingsOriginator stateCandidate = default, bool mock = false, PeerId peer = default, INeighbours neighbours = default, ICorrelationId expectedPnr = default) { var pnrCorrelationId = expectedPnr ?? CorrelationId.GenerateCorrelationId(); _currentState = mock ? stateCandidate ?? DiscoveryHelper.MockOriginator(peer, neighbours) : stateCandidate ?? DiscoveryHelper.SubOriginator(peer, neighbours, pnrCorrelationId); return(this); }
// Token: 0x060002BE RID: 702 RVA: 0x000111C4 File Offset: 0x0000F3C4 internal static void UpdateRoutine(int profileID) { if (profileID <= 0) { throw new ArgumentException("Invalid ProfileID", "profileID"); } using (LocaleThreadState.EnsurePrimaryLocale()) { try { IEnumerable <IScheduledDiscoveryPlugin> enumerable = DiscoveryHelper.GetOrderedDiscoveryPlugins().OfType <IScheduledDiscoveryPlugin>(); if (enumerable.Count <IScheduledDiscoveryPlugin>() > 0) { DiscoveryResultBase discoveryResult = DiscoveryResultManager.GetDiscoveryResult(profileID, enumerable.Cast <IDiscoveryPlugin>().ToList <IDiscoveryPlugin>()); using (IEnumerator <IScheduledDiscoveryPlugin> enumerator = enumerable.GetEnumerator()) { Action <string, double> < > 9__0; while (enumerator.MoveNext()) { IScheduledDiscoveryPlugin scheduledDiscoveryPlugin = enumerator.Current; DiscoveryResultBase discoveryResultBase = discoveryResult; Action <string, double> action; if ((action = < > 9__0) == null) { action = (< > 9__0 = delegate(string message, double phaseProgress) { if (DiscoveryNetObjectStatusManager.log.IsInfoEnabled) { DiscoveryNetObjectStatusManager.log.InfoFormat("Updating Discovered Net Object Statuses for profile {0}: {1} - {2}", profileID, phaseProgress, message); } }); } scheduledDiscoveryPlugin.UpdateImportStatuses(discoveryResultBase, action); } goto IL_CC; } } if (DiscoveryNetObjectStatusManager.log.IsInfoEnabled) { DiscoveryNetObjectStatusManager.log.InfoFormat("Skipping Discovered Net Object Status update for profile {0}", profileID); } IL_CC :; } catch (Exception ex) { DiscoveryNetObjectStatusManager.log.Error(string.Format("Update Discovered Net Object Statuses for profile {0} failed", profileID), ex); } } }
public void Taking_From_Memento_List_Takes_LIFO() { var careTaker = new HastingsCareTaker(); var stack = new Stack <IHastingsMemento>(); stack.Push(DiscoveryHelper.SubMemento(_ownNode)); var history = DiscoveryHelper.MockMementoHistory(stack); history.ToList().ForEach(m => careTaker.Add(m)); careTaker.Get().Should().Be(history.Last()); careTaker.HastingMementoList.First().Should().Be(history.First()); careTaker.HastingMementoList.Count.Should().Be(history.Count - 1); }
private AgentDeploymentInfo LoadAgentDeploymentInfo(int agentId) { AgentInfo agentInfo1 = new AgentManager(this.AgentInfoDal).GetAgentInfo(agentId); if (agentInfo1 != null) { string[] discoveryPluginIds = DiscoveryHelper.GetAgentDiscoveryPluginIds(); return(AgentDeploymentInfo.Calculate(agentInfo1, (IEnumerable <string>)discoveryPluginIds, (string)null)); } AgentDeploymentInfo agentDeploymentInfo = new AgentDeploymentInfo(); AgentInfo agentInfo2 = new AgentInfo(); agentInfo2.set_AgentId(agentId); agentDeploymentInfo.set_Agent(agentInfo2); agentDeploymentInfo.set_StatusInfo(new AgentDeploymentStatusInfo(agentId, (AgentDeploymentStatus)2, "Agent not found.")); return(agentDeploymentInfo); }
// Token: 0x06000917 RID: 2327 RVA: 0x00041AB0 File Offset: 0x0003FCB0 private AgentDeploymentInfo LoadAgentDeploymentInfo(int agentId) { AgentInfo agentInfo = new AgentManager(this.AgentInfoDal).GetAgentInfo(agentId); if (agentInfo != null) { string[] agentDiscoveryPluginIds = DiscoveryHelper.GetAgentDiscoveryPluginIds(); return(AgentDeploymentInfo.Calculate(agentInfo, agentDiscoveryPluginIds, null)); } return(new AgentDeploymentInfo { Agent = new AgentInfo { AgentId = agentId }, StatusInfo = new AgentDeploymentStatusInfo(agentId, AgentDeploymentStatus.Failed, "Agent not found.") }); }
public DiscoveryTestBuilder WithCurrentStep(IHastingsMemento currentStep = default, bool mock = false, PeerId peer = default, INeighbours neighbours = default) { if (_careTaker == null) { WithCareTaker(); } var memento = mock ? currentStep ?? DiscoveryHelper.MockMemento(peer, neighbours) : currentStep ?? DiscoveryHelper.SubMemento(peer, neighbours); _careTaker.Add(memento); return(this); }
public async Task DiscoverDevices_ForSingleDevice_ShouldOnlyAddDevice() { // Arrange List <DeviceDto> devices = new List <DeviceDto> { new DeviceDto { MetaTags = new List <MetaTagDto>(), Tags = new List <string> (), DisplayName = "Test Device", Id = "Device-Id" } }; string messageId = "MessageId1"; SmartHomeRequest request = BuildRequest(messageId); IDevicesClient devicesClient = new FakeDevicesClient(devices); DiscoveryHelper discoveryHelper = new DiscoveryHelper(devicesClient); // Act DiscoverResponse response = (DiscoverResponse)await discoveryHelper.HandleAlexaRequest(request, null); // Assert Assert.IsNotNull(response, "response nul"); Assert.IsNotNull(response.Event, "Event null"); Assert.IsNotNull(response.Event.Header, "Header null"); Assert.AreEqual("Alexa.Discovery", response.Event.Header.Namespace, "Namespace"); Assert.AreEqual("Discover.Response", response.Event.Header.Name, "Name"); Assert.AreEqual("3", response.Event.Header.PayloadVersion, "PayloadVersion"); Assert.AreEqual(messageId, response.Event.Header.MessageId, "MessageId"); var endpoints = response.Event.Payload.Endpoints; Assert.IsNotNull(endpoints, "response.Event.Payload.Endpoints null"); // Expect 2 sub-devices as only 2 are names. // plus one parent device. Assert.AreEqual(1, endpoints.Count, "response.Event.Payload.Endpoints null"); Assert.AreEqual("Test Device", endpoints[0].FriendlyName, "endpoints[0].FriendlyName"); Assert.AreEqual("Device-Id", endpoints[0].EndpointId, "endpoints[0].EndpointId"); }
internal static void UpdateRoutine(int profileID) { if (profileID <= 0) { throw new ArgumentException("Invalid ProfileID", nameof(profileID)); } using (LocaleThreadState.EnsurePrimaryLocale()) { try { IEnumerable <IScheduledDiscoveryPlugin> source = ((IEnumerable)DiscoveryHelper.GetOrderedDiscoveryPlugins()).OfType <IScheduledDiscoveryPlugin>(); if (source.Count <IScheduledDiscoveryPlugin>() > 0) { DiscoveryResultBase discoveryResult = DiscoveryResultManager.GetDiscoveryResult(profileID, (IList <IDiscoveryPlugin>)((IEnumerable)source).Cast <IDiscoveryPlugin>().ToList <IDiscoveryPlugin>()); using (IEnumerator <IScheduledDiscoveryPlugin> enumerator = source.GetEnumerator()) { while (((IEnumerator)enumerator).MoveNext()) { enumerator.Current.UpdateImportStatuses(discoveryResult, (Action <string, double>)((message, phaseProgress) => { if (!DiscoveryNetObjectStatusManager.log.get_IsInfoEnabled()) { return; } DiscoveryNetObjectStatusManager.log.InfoFormat("Updating Discovered Net Object Statuses for profile {0}: {1} - {2}", (object)profileID, (object)phaseProgress, (object)message); })); } } } else { if (!DiscoveryNetObjectStatusManager.log.get_IsInfoEnabled()) { return; } DiscoveryNetObjectStatusManager.log.InfoFormat("Skipping Discovered Net Object Status update for profile {0}", (object)profileID); } } catch (Exception ex) { DiscoveryNetObjectStatusManager.log.Error((object)string.Format("Update Discovered Net Object Statuses for profile {0} failed", (object)profileID), ex); } } }
void IServiceBusDiscovery.OnDiscoveryRequest(string contractName, string contractNamespace, Uri[] scopesToMatch, Uri responseAddress) { ChannelFactory <IServiceBusDiscoveryCallback> factory = new ChannelFactory <IServiceBusDiscoveryCallback>(DiscoveryResponseBinding, new EndpointAddress(responseAddress)); factory.Endpoint.Behaviors.Add(Credentials); IServiceBusDiscoveryCallback callback = factory.CreateChannel(); foreach (ServiceEndpoint endpoint in Endpoints) { if (endpoint.Contract.Name == contractName && endpoint.Contract.Namespace == contractNamespace) { Uri[] scopes = DiscoveryHelper.LookupScopes(endpoint); if (scopesToMatch != null) { bool scopesMatched = true; foreach (Uri scope in scopesToMatch) { if (scopes.Any(uri => uri.AbsoluteUri == scope.AbsoluteUri) == false) { scopesMatched = false; break; } } if (scopesMatched == false) { continue; } } try { callback.DiscoveryResponse(endpoint.Address.Uri, contractName, contractNamespace, scopes); } catch { callback = factory.CreateChannel(); } } } (callback as ICommunicationObject).Close(); }
private static IEnumerable <EndpointAddress> DiscoverEndpoints() { Log.Default.WriteLine(LogLevels.Debug, "Searching IWCFTetriNET server"); EndpointAddress[] endpointAddresses = DiscoveryHelper.DiscoverAddresses <IWCFTetriNET>(); if (endpointAddresses != null && endpointAddresses.Any()) { foreach (EndpointAddress endpoint in endpointAddresses) { Log.Default.WriteLine(LogLevels.Debug, "{0}:\t{1}", Array.IndexOf(endpointAddresses, endpoint), endpoint.Uri); } Log.Default.WriteLine(LogLevels.Debug, "Selecting first server"); return(endpointAddresses); } else { Log.Default.WriteLine(LogLevels.Debug, "No server found"); return(Enumerable.Empty <EndpointAddress>()); } }
public void Evicted_Known_Ping_Message_Sets_Contacted_Neighbour_As_UnReachable_And_Can_RollBack_State() { var cacheEntriesByRequest = new Dictionary <ByteString, ICacheEntry>(); var seedState = DiscoveryHelper.MockSeedState(_ownNode, _settings); var seedOrigin = HastingsOriginator.Default; seedOrigin.RestoreMemento(seedState); var stateCareTaker = new HastingsCareTaker(); var stateHistory = new Stack <IHastingsMemento>(); stateHistory.Push(seedState); stateHistory = DiscoveryHelper.MockMementoHistory(stateHistory, 5); //this isn't an angry pirate this is just 5 stateHistory.Last().Neighbours.First().StateTypes = NeighbourStateTypes.Responsive; stateHistory.ToList().ForEach(i => stateCareTaker.Add(i)); var stateCandidate = DiscoveryHelper.MockOriginator(default,
// Token: 0x0600061E RID: 1566 RVA: 0x00024C38 File Offset: 0x00022E38 private DiscoveryResultBase FilterItems(DiscoveryResultBase discoveryResult, Func <IDiscoveryPlugin, DiscoveryResultBase, DiscoveryPluginResultBase> filterFunction) { foreach (IDiscoveryPlugin discoveryPlugin in DiscoveryHelper.GetOrderedDiscoveryPlugins()) { DiscoveryPluginResultBase discoveryPluginResultBase = filterFunction(discoveryPlugin, discoveryResult); if (discoveryPluginResultBase != null) { discoveryPluginResultBase.PluginTypeName = discoveryPlugin.GetType().FullName; Type returnedType = discoveryPluginResultBase.GetType(); List <DiscoveryPluginResultBase> list = (from item in discoveryResult.PluginResults where item.GetType() != returnedType select item).ToList <DiscoveryPluginResultBase>(); discoveryResult.PluginResults.Clear(); discoveryResult.PluginResults.Add(discoveryPluginResultBase); foreach (DiscoveryPluginResultBase discoveryPluginResultBase2 in list) { discoveryResult.PluginResults.Add(discoveryPluginResultBase2); } } } return(discoveryResult); }
void PublishAvailabilityEvent(Action <Uri, string, string, Uri[]> notification) { foreach (ServiceEndpoint endpoint in Description.Endpoints) { if (endpoint is DiscoveryEndpoint || endpoint is ServiceMetadataEndpoint) { continue; } Uri[] scopes = DiscoveryHelper.LookupScopes(endpoint); WaitCallback fire = delegate { try { notification(endpoint.Address.Uri, endpoint.Contract.Name, endpoint.Contract.Namespace, scopes); (notification.Target as ICommunicationObject).Close(); } catch {} }; ThreadPool.QueueUserWorkItem(fire); } }
void IServiceBusAnnouncements.OnHello(Uri address, string contractName, string contractNamespace, Uri[] scopes) { AnnouncementEventArgs args = DiscoveryHelper.CreateAnnouncementArgs(address, contractName, contractNamespace, scopes); OnHello(this, args); }
public static string GetDiscoveryTopic <TEntity>(this HassMqttTopicBuilder topicBuilder, string deviceId, string entityId) where TEntity : IHassDiscoveryDocument { // homeassistant/<sensor>/<my_device>/<my_entity>/config return(topicBuilder.GetDiscoveryTopic(DiscoveryHelper.GetDeviceType <TEntity>().AsString(EnumFormat.EnumMemberValue), deviceId, entityId, "config")); }
public FindResponse Find(FindCriteria criteria) { string contractName = criteria.ContractTypeNames[0].Name; string contractNamespace = criteria.ContractTypeNames[0].Namespace; FindResponse response = DiscoveryHelper.CreateFindResponse(); ManualResetEvent handle = new ManualResetEvent(false); Action <Uri, Uri[]> addEndpoint = (address, scopes) => { EndpointDiscoveryMetadata metadata = new EndpointDiscoveryMetadata(); metadata.Address = new EndpointAddress(address); if (scopes != null) { foreach (Uri scope in scopes) { metadata.Scopes.Add(scope); } } response.Endpoints.Add(metadata); if (response.Endpoints.Count >= criteria.MaxResults) { handle.Set(); } }; DiscoveryResponseCallback callback = new DiscoveryResponseCallback(contractName, contractNamespace, addEndpoint); ServiceHost host = new ServiceHost(callback); host.AddServiceEndpoint(typeof(IServiceBusDiscoveryCallback), Endpoint.Binding, ResponseAddress.AbsoluteUri); host.Description.Endpoints[0].Behaviors.Add(new ServiceRegistrySettings(DiscoveryType.Public)); TransportClientEndpointBehavior credentials = Endpoint.Behaviors.Find <TransportClientEndpointBehavior>(); Debug.Assert(credentials != null); host.Description.Endpoints[0].Behaviors.Add(credentials); host.Open(); try { DiscoveryRequest(criteria.ContractTypeNames[0].Name, criteria.ContractTypeNames[0].Namespace, criteria.Scopes.ToArray(), ResponseAddress); bool found = handle.WaitOne(criteria.Duration); if (found == false) { Trace.WriteLine("Could not find endpoints within specified discovery criteria duration"); } } catch {} finally { try { host.Abort(); } catch (ProtocolException) {} } return(response); }
public TestSuiteParameters GetTestSuiteParameters() { TestSuiteParameters parameters = new TestSuiteParameters(); if (Device != null) { parameters.Address = Device.DeviceServiceAddress; //parameters.CameraUUID } if (string.IsNullOrEmpty(parameters.Address)) { Console.WriteLine("Mandatory parameters (Device address) not defined!"); return(null); } Timeouts defTimeouts = new Timeouts(); TestSettings defSettings = new TestSettings(); if (TestParameters != null) { parameters.MessageTimeout = (0 != TestParameters.MessageTimeout) ? TestParameters.MessageTimeout : defTimeouts.Message; parameters.RebootTimeout = (0 != TestParameters.RebootTimeout) ? TestParameters.RebootTimeout : defTimeouts.Reboot; parameters.RecoveryDelay = TestParameters.TimeBetweenRequests; parameters.TimeBetweenTests = TestParameters.TimeBetweenTests; parameters.OperationDelay = (0 != TestParameters.OperationDelay) ? TestParameters.OperationDelay : defSettings.OperationDelay; parameters.UserName = TestParameters.UserName; parameters.Password = TestParameters.Password; parameters.EnvironmentSettings = new EnvironmentSettings(); parameters.EnvironmentSettings.DefaultGateway = TestParameters.DefaultGatewayIpv4; parameters.EnvironmentSettings.DefaultGatewayIpv6 = TestParameters.DefaultGatewayIpv6; parameters.EnvironmentSettings.DnsIpv4 = TestParameters.DnsIpv4; parameters.EnvironmentSettings.DnsIpv6 = TestParameters.DnsIpv6; parameters.EnvironmentSettings.NtpIpv4 = TestParameters.NtpIpv4; parameters.EnvironmentSettings.NtpIpv6 = TestParameters.NtpIpv6; if (!string.IsNullOrEmpty(TestParameters.Address)) { // get all "own" addresses; List <NetworkInterfaceDescription> nics = DiscoveryHelper.GetNetworkInterfaces(); // select required address (compare strings) foreach (NetworkInterfaceDescription nic in nics) { if (nic.IP.ToString() == TestParameters.Address) { parameters.NetworkInterfaceController = nic; break; } } if (parameters.NetworkInterfaceController != null) { // define device IP bool ipv6 = (parameters.NetworkInterfaceController.IP != null) && (parameters.NetworkInterfaceController.IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6); parameters.CameraIP = DiscoveryUtils.GetIP(Device.DeviceIP, ipv6); } } parameters.UseEmbeddedPassword = TestParameters.UseEmbeddedPassword; parameters.Password1 = TestParameters.Password1; parameters.Password2 = TestParameters.Password2; parameters.SecureMethod = !string.IsNullOrEmpty(TestParameters.SecureMethod) ? TestParameters.SecureMethod : defSettings.SecureMethod; parameters.PTZNodeToken = TestParameters.PTZNodeToken; parameters.VideoSourceToken = TestParameters.VideoSourceToken; parameters.EventTopic = TestParameters.EventTopic; parameters.SubscriptionTimeout = (0 != TestParameters.SubscriptionTimeout) ? TestParameters.SubscriptionTimeout : defSettings.SubscriptionTimeout; parameters.TopicNamespaces = TestParameters.TopicNamespaces; parameters.RelayOutputDelayTimeMonostable = (0 != TestParameters.RelayOutputDelayTime) ? TestParameters.RelayOutputDelayTime : defSettings.RelayOutputDelayTimeMonostable; } // return(parameters); }
private async void Button_Click(object sender, RoutedEventArgs e) { Uri authorityUri; Uri sharePointTenantUri; Uri siteCollectionUri; Regex mailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); // Input parameters sanity check if ((String.IsNullOrEmpty(this.Authority.Text) || !Uri.TryCreate(this.Authority.Text, UriKind.Absolute, out authorityUri)) || (String.IsNullOrEmpty(this.SharePointTenantUri.Text) || !Uri.TryCreate(this.SharePointTenantUri.Text, UriKind.Absolute, out sharePointTenantUri)) || (String.IsNullOrEmpty(this.SiteCollectionUri.Text) || !Uri.TryCreate(this.SiteCollectionUri.Text, UriKind.Absolute, out siteCollectionUri)) || (String.IsNullOrEmpty(this.MailAddressTo.Text) || !mailRegex.IsMatch(this.MailAddressTo.Text)) || (String.IsNullOrEmpty(this.FileToUploadPath.Text) || !File.Exists(this.FileToUploadPath.Text))) { MessageBoxResult msgBoxResult = MessageBox.Show("Please fill all the input parameters!"); return; } try { PrintHeader("Authentication Phase"); AuthenticationHelper authenticationHelper = new AuthenticationHelper(); authenticationHelper.EnsureAuthenticationContext(this.Authority.Text); PrintHeader("Discovery API demo"); DiscoveryHelper discoveryHelper = new DiscoveryHelper(authenticationHelper); var t = await discoveryHelper.DiscoverMyFiles(); PrintSubHeader("Current user information"); PrintAttribute("OneDrive URL", t.ServiceEndpointUri); var t3 = await discoveryHelper.DiscoverMail(); PrintAttribute("Mail URL", t3.ServiceEndpointUri); PrintHeader("Files API demo"); // Read all files on your onedrive PrintSubHeader("List TOP 20 files and folders in the OneDrive"); MyFilesHelper myFilesHelper = new MyFilesHelper(authenticationHelper); var allMyFolders = await myFilesHelper.GetMyFolders(); var allMyFiles = await myFilesHelper.GetMyFiles(); foreach (var item in allMyFiles.Take(20)) { PrintAttribute("URL", item.WebUrl); } // Upload a file to the "Shared with everyone" folder PrintSubHeader("Upload a file to OneDrive"); if (allMyFolders.Any()) { await myFilesHelper.UploadFile(this.FileToUploadPath.Text, allMyFolders.First().Id); } else { await myFilesHelper.UploadFile(this.FileToUploadPath.Text); } // Shared with everyone // Iterate over the "Shared with everyone" folder PrintSubHeader("List all files and folders in the Shared with everyone folder"); var myFiles = await myFilesHelper.GetMyFiles(allMyFolders.First().Id); foreach (var item in myFiles) { PrintAttribute("URL", item.WebUrl); } PrintHeader("Mail API demo"); //Get mails PrintSubHeader("Retrieve mails from INBOX"); MailHelper mailHelper = new MailHelper(authenticationHelper); var mails = await mailHelper.GetMessages(); PrintSubHeader(String.Format("Printing TOP 10 mails of {0}", mails.Count())); foreach (var item in mails.Take(10)) { PrintAttribute("From ", String.Format("{0} / {1}", item.From != null ? item.From.EmailAddress.Address : "", item.Subject)); } //Send mail PrintSubHeader("Send a mail"); await mailHelper.SendMail(this.MailAddressTo.Text, "Let's Hack-A-Thon - Office365Api.Demo", "This will be <B>fun...</B>"); //Create message in drafts folder PrintSubHeader("Store a mail in the drafts folder"); await mailHelper.DraftMail(this.MailAddressTo.Text, "Let's Hack-A-Thon - Office365Api.Demo", "This will be fun (in draft folder)..."); PrintHeader("Active Directory API demo"); ActiveDirectoryHelper activeDirectoryHelper = new ActiveDirectoryHelper(authenticationHelper); var allADUsers = await activeDirectoryHelper.GetUsers(); PrintSubHeader(String.Format("Printing TOP 10 users of {0}", allADUsers.Count())); foreach (var user in allADUsers.Take(10)) { PrintAttribute("User", user.UserPrincipalName); } PrintHeader("All done..."); } catch (Exception ex) { string message = ""; if (ex is AggregateException) { message = ex.InnerException.Message; } else { message = ex.Message; } PrintException(message); } }