protected void Record(Action<ISession> action)
 {
     using (var recorder = new SqlCommandRecorder())
     {
         InNewSession(action);
         var recording = recorder.GetRecording();
         Console.WriteLine(string.Join(Environment.NewLine, recording.Commands.Select(x => x.ToString())));
         Recording = recording;
     }
 }
Example #2
0
        public async Task StartRecording(Recording recording)
        {
            GuardFromCallingWhenDisposed();
            if (_device.IsRecording)
                throw new InvalidOperationException("Cannot start a recording when already recording.");

            var stream = await _streamManager.GetOrCreateStreamAsync(recording.Id);
            await _device.StartRecordingAsync(stream);
            _eventAggregator.Publish(new RecordingStarted(recording.Name));
        }
 internal static RecordingEntity ConvertToEntity(Recording recordingToConvert)
 {
     return new RecordingEntity()
       {
     FromProfileId = recordingToConvert.FromProfileId,
     ToProfileId = recordingToConvert.ToProfileId,
     Url = recordingToConvert.Url,
     PartitionKey = recordingToConvert.ToProfileId.ToString(),
     RowKey = Guid.NewGuid().ToString()
       };
 }
        public Recording Create(Recording item)
        {
            var entity = RecordingToEntityMapper.ConvertToEntity(item);

              TableOperation insertOperation = TableOperation.Insert(entity);
              var result = recordingsTable.Execute(insertOperation);

              RecordingEntity entityResult = (RecordingEntity)result.Result;

              return RecordingToEntityMapper.ConvertFromEntity(entityResult);
        }
Example #5
0
 /// <summary>
 /// Copies the data in oldRecoding to a new instance of the <see cref="Recording"/> class.
 /// </summary>
 /// <param name='oldRecording'>
 /// Recording to be copied
 /// </param>
 public Recording( Recording oldRecording )
 {
     if ( oldRecording != null )
     {
         frameRate = oldRecording.frameRate;
         frames = new List<RecordingFrame>( oldRecording.frames );
     }
     else
     {
         frameRate = 60;
         frames = new List<RecordingFrame>();
     }
 }
 public void RecordingRepositoryTestMethod()
 {
     RecordingRepository _rpo = new RecordingRepository();
       IConsumerBinding _nb = _rpo.GetConsumerBinding(String.Empty, DataRepository.name, new UATypeInfo(BuiltInType.String));
       Assert.IsNotNull(_nb);
       Assert.IsNotNull(_nb.Encoding);
       _nb.Converter = new DateFormatter();
       Assert.AreEqual<BuiltInType>(BuiltInType.String, _nb.Encoding.BuiltInType);
       DateTime _dt = new DateTime(2008, 2, 5);
       Recording _testValue = new Recording("Chris Sells", "Chris Sells Live", _dt);
       _nb.Assign2Repository(_testValue);
       Assert.AreEqual<string>(_dt.ToString(CultureInfo.InvariantCulture), _rpo.Buffer);
 }
        public static void ShowRecordingActionsPopup(this Screen @this, Recording recording)
        {
            var settings = new Dictionary<string, object>();
            var view = @this.GetView() as UIElement;
            if (view == null)
                return;

            var point = view.TransformToVisual(null).Transform(new Point());
            settings.Add("VerticalOffset", point.Y);
            var vm = IoC.Get<RecordingActionsViewModel>();
            vm.SetRecording(recording);
            @this.Deactivated += (s, e) => vm.ClosePopup();
            var windowManager = IoC.Get<IWindowManager>();
            windowManager.ShowPopup(vm, settings: settings);
        }
 public async Task<SaveRecordingResult> SaveAsync(Recording recording)
 {
     try
     {
         _context.Recordings.InsertOnSubmit(recording);
         _context.SubmitChanges();
         _cache.Add(recording);
         _eventAggregator.Publish(new RecordingCreated(recording));
         return SaveRecordingResult.Success;
     }
     catch
     {
         return SaveRecordingResult.UndefinedFailure;
     }
 }
Example #9
0
    public void OnClickRecord()
    {
        GameObject instrumentPool = GameObject.Find("Active Instrument Pool");
        Object[] instruments = instrumentPool.GetComponentsInChildren<InstrumentBehaviour>(false);
        foreach(InstrumentBehaviour instrument in instruments)
        {

            Debug.Log("create recording");
            Recording rec = new Recording(instrument);

            rec.playStart= 10;
            rec.playEnd = 20;
            rec.volume = 1.0f;

            this.recordings.Add(rec);
        }
    }
        public bool Delete(Recording item)
        {
            //Azure storage will throw a StorageException --- 404 --- if it cannot find the entity to delete.

              var entity = RecordingToEntityMapper.ConvertToEntity(item);

              entity.ETag = "*";

              TableOperation deleteOperation = TableOperation.Delete(entity);

              try
              {
            var result = recordingsTable.Execute(deleteOperation);

            return true;
              }
              catch (StorageException)
              {
            return false;
              }
        }
        public void ShouldSaveAndReloadWithIdenticalValues()
        {
            var expected = new Recording(PointInTime.FromMicroseconds(10), PointInTime.FromMicroseconds(20));

            using (var repo = new ProjectRepository())
            {
                using (var transaction = new TransactionScope())
                {
                    repo.Recordings.SaveOrUpdate(expected);
                    transaction.Complete();
                }

                repo.Session.Clear();

                Recording actual;
                using (var transaction = new TransactionScope())
                {
                    actual = repo.Recordings.TryGet(expected.Id);
                }
                Assert.That(actual.Id, Is.EqualTo(expected.Id));
                Assert.That(actual.Start, Is.EqualTo(expected.Start));
                Assert.That(actual.End, Is.EqualTo(expected.End));
            }
        }
		/// <summary>
		/// Clears out whatever recording is playing and sets the new one
		/// </summary>
		public void setRecordingToPlayback(Recording recording){

			if (recording == null) {
				return;
			}

			clearCurrentLoadedRecording ();

			currentLoadedRecording = recording;

		}
Example #13
0
        private async Task TestScaleSetOperationsInternal(string vmSize     = null, bool hasManagedDisks  = false, bool useVmssExtension = true,
                                                          bool hasDiffDisks = false, IList <string> zones = null, int?osDiskSizeInGB     = null, bool isPpgScenario = false, bool?enableUltraSSD = false,
                                                          Action <VirtualMachineScaleSet> vmScaleSetCustomizer = null, Action <VirtualMachineScaleSet> vmScaleSetValidator = null, string diskEncryptionSetId = null)
        {
            ImageReference imageRef = await GetPlatformVMImage(useWindowsImage : true);

            // Create resource group
            var    rgName             = Recording.GenerateAssetName(TestPrefix);
            var    vmssName           = Recording.GenerateAssetName("vmss");
            string storageAccountName = Recording.GenerateAssetName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;

            VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
            {
                Extensions = new List <VirtualMachineScaleSetExtension>()
                {
                    GetTestVMSSVMExtension(),
                }
            };
            var storageAccountOutput = await CreateStorageAccount(rgName, storageAccountName);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, "VMScaleSetDoesNotExist"));

            string ppgId   = null;
            string ppgName = null;

            if (isPpgScenario)
            {
                ppgName = Recording.GenerateAssetName("ppgtest");
                ppgId   = await CreateProximityPlacementGroup(rgName, ppgName);
            }

            var getTwoVirtualMachineScaleSet = await CreateVMScaleSet_NoAsyncTracking(
                rgName,
                vmssName,
                storageAccountOutput,
                imageRef,
                useVmssExtension?extensionProfile : null,
                (vmScaleSet) =>
            {
                vmScaleSet.Overprovision = true;
                if (!String.IsNullOrEmpty(vmSize))
                {
                    vmScaleSet.Sku.Name = vmSize;
                }
                vmScaleSetCustomizer?.Invoke(vmScaleSet);
            },
                createWithManagedDisks : hasManagedDisks,
                hasDiffDisks : hasDiffDisks,
                zones : zones,
                osDiskSizeInGB : osDiskSizeInGB,
                ppgId : ppgId,
                enableUltraSSD : enableUltraSSD,
                diskEncryptionSetId : diskEncryptionSetId);

            VirtualMachineScaleSet getResponse = getTwoVirtualMachineScaleSet.Item1;

            inputVMScaleSet = getTwoVirtualMachineScaleSet.Item2;
            if (diskEncryptionSetId != null)
            {
                Assert.True(getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null");
                Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
                            "OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");

                Assert.AreEqual(1, getResponse.VirtualMachineProfile.StorageProfile.DataDisks.Count);
                Assert.True(getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null");
                Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
                            "DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
            }

            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks, ppgId: ppgId);

            var getInstanceViewResponse = await VirtualMachineScaleSetsOperations.GetInstanceViewAsync(rgName, vmssName);

            Assert.NotNull(getInstanceViewResponse);
            ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse);

            if (isPpgScenario)
            {
                ProximityPlacementGroup outProximityPlacementGroup = await ProximityPlacementGroupsOperations.GetAsync(rgName, ppgName);

                Assert.AreEqual(1, outProximityPlacementGroup.VirtualMachineScaleSets.Count);
                string expectedVmssReferenceId = Helpers.GetVMScaleSetReferenceId(m_subId, rgName, vmssName);
                Assert.AreEqual(expectedVmssReferenceId.ToLower(), outProximityPlacementGroup.VirtualMachineScaleSets.First().Id.ToLower());
            }

            var listResponse = await(VirtualMachineScaleSetsOperations.ListAsync(rgName)).ToEnumerableAsync();

            ValidateVMScaleSet(inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks);

            var listSkusResponse = await(VirtualMachineScaleSetsOperations.ListSkusAsync(rgName, vmssName)).ToEnumerableAsync();

            Assert.NotNull(listSkusResponse);
            Assert.False(listSkusResponse.Count() == 0);

            if (zones != null)
            {
                var query           = "properties/latestModelApplied eq true";
                var listVMsResponse = await(VirtualMachineScaleSetVMsOperations.ListAsync(rgName, vmssName, query)).ToEnumerableAsync();
                Assert.False(listVMsResponse == null, "VMScaleSetVMs not returned");
                Assert.True(listVMsResponse.Count() == inputVMScaleSet.Sku.Capacity);

                foreach (var vmScaleSetVM in listVMsResponse)
                {
                    string instanceId    = vmScaleSetVM.InstanceId;
                    var    getVMResponse = await VirtualMachineScaleSetVMsOperations.GetAsync(rgName, vmssName, instanceId);

                    ValidateVMScaleSetVM(inputVMScaleSet, instanceId, getVMResponse, hasManagedDisks);
                }
            }

            vmScaleSetValidator?.Invoke(getResponse);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, vmssName));
        }
        public async Task GetSecretVersionsNonExisting()
        {
            List <SecretProperties> allSecrets = await Client.GetPropertiesOfSecretVersionsAsync(Recording.GenerateId()).ToEnumerableAsync();

            Assert.AreEqual(0, allSecrets.Count);
        }
Example #15
0
 public SettingsPanel()
 {
     InitializeComponent();
     _sampleRecording = Utility.CreateSampleRecording();
 }
Example #16
0
        public async Task StartRecognizeCustomFormsWithoutLabelsCanParseMultipageFormWithBlankPage(bool useStream)
        {
            var client  = CreateFormRecognizerClient();
            var options = new RecognizeCustomFormsOptions()
            {
                IncludeFieldElements = true
            };
            RecognizeCustomFormsOperation operation;

            await using var trainedModel = await CreateDisposableTrainedModelAsync(useTrainingLabels : false);

            if (useStream)
            {
                using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceMultipageBlank);
                using (Recording.DisableRequestBodyRecording())
                {
                    operation = await client.StartRecognizeCustomFormsAsync(trainedModel.ModelId, stream, options);
                }
            }
            else
            {
                var uri = FormRecognizerTestEnvironment.CreateUri(TestFile.InvoiceMultipageBlank);
                operation = await client.StartRecognizeCustomFormsFromUriAsync(trainedModel.ModelId, uri, options);
            }

            RecognizedFormCollection recognizedForms = await operation.WaitForCompletionAsync();

            Assert.AreEqual(3, recognizedForms.Count);

            for (int formIndex = 0; formIndex < recognizedForms.Count; formIndex++)
            {
                var recognizedForm     = recognizedForms[formIndex];
                var expectedPageNumber = formIndex + 1;

                ValidateModelWithNoLabelsForm(
                    recognizedForm,
                    trainedModel.ModelId,
                    includeFieldElements: true,
                    expectedFirstPageNumber: expectedPageNumber,
                    expectedLastPageNumber: expectedPageNumber);

                // Basic sanity test to make sure pages are ordered correctly.

                if (formIndex == 0 || formIndex == 2)
                {
                    var expectedValueData = formIndex == 0 ? "300.00" : "3000.00";

                    FormField fieldInPage = recognizedForm.Fields.Values.Where(field => field.LabelData.Text.Contains("Subtotal:")).FirstOrDefault();
                    Assert.IsNotNull(fieldInPage);
                    Assert.IsNotNull(fieldInPage.ValueData);
                    Assert.AreEqual(expectedValueData, fieldInPage.ValueData.Text);
                }
            }

            var blankForm = recognizedForms[1];

            Assert.AreEqual(0, blankForm.Fields.Count);

            var blankPage = blankForm.Pages.Single();

            Assert.AreEqual(0, blankPage.Lines.Count);
            Assert.AreEqual(0, blankPage.Tables.Count);
        }
Example #17
0
        public async Task ViewNsgRuleApiTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("azsmnet");

            string location = "westus2";
            await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location));

            string virtualMachineName       = Recording.GenerateAssetName("azsmnet");
            string networkInterfaceName     = Recording.GenerateAssetName("azsmnet");
            string networkSecurityGroupName = virtualMachineName + "-nsg";

            //Deploy VM with template
            await CreateVm(
                resourcesClient : ResourceManagementClient,
                resourceGroupName : resourceGroupName,
                location : location,
                virtualMachineName : virtualMachineName,
                storageAccountName : Recording.GenerateAssetName("azsmnet"),
                networkInterfaceName : networkInterfaceName,
                networkSecurityGroupName : networkSecurityGroupName,
                diagnosticsStorageAccountName : Recording.GenerateAssetName("azsmnet"),
                deploymentName : Recording.GenerateAssetName("azsmnet"),
                adminPassword : Recording.GenerateAlphaNumericId("AzureSDKNetworkTest#")
                );

            //TODO:There is no need to perform a separate create NetworkWatchers operation
            //Create network Watcher
            //string networkWatcherName = Recording.GenerateAssetName("azsmnet");
            //NetworkWatcher properties = new NetworkWatcher { Location = location };
            //Response<NetworkWatcher> createNetworkWatcher = await NetworkManagementClient.NetworkWatchers.CreateOrUpdateAsync(resourceGroupName, networkWatcherName, properties);

            Response <VirtualMachine> getVm = await ComputeManagementClient.VirtualMachines.GetAsync(resourceGroupName, virtualMachineName);

            string localIPAddress = NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, networkInterfaceName).Result.Value.IpConfigurations.FirstOrDefault().PrivateIPAddress;

            string securityRule1 = Recording.GenerateAssetName("azsmnet");

            // Add a security rule
            SecurityRule SecurityRule = new SecurityRule()
            {
                Name        = securityRule1,
                Access      = SecurityRuleAccess.Deny,
                Description = "Test outbound security rule",
                DestinationAddressPrefix = "*",
                DestinationPortRange     = "80",
                Direction           = SecurityRuleDirection.Outbound,
                Priority            = 501,
                Protocol            = SecurityRuleProtocol.Tcp,
                SourceAddressPrefix = "*",
                SourcePortRange     = "*",
            };

            Response <NetworkSecurityGroup> nsg = await NetworkManagementClient.NetworkSecurityGroups.GetAsync(resourceGroupName, networkSecurityGroupName);

            nsg.Value.SecurityRules.Add(SecurityRule);
            NetworkSecurityGroupsCreateOrUpdateOperation createOrUpdateOperation = await NetworkManagementClient.NetworkSecurityGroups.StartCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, nsg);

            Response <NetworkSecurityGroup> networkSecurityGroup = await WaitForCompletionAsync(createOrUpdateOperation);

            //Get view security group rules
            SecurityGroupViewParameters sgvProperties = new SecurityGroupViewParameters(getVm.Value.Id);
            NetworkWatchersGetVMSecurityRulesOperation viewNSGRulesOperation = await NetworkManagementClient.NetworkWatchers.StartGetVMSecurityRulesAsync("NetworkWatcherRG", "NetworkWatcher_westus2", sgvProperties);

            Response <SecurityGroupViewResult> viewNSGRules = await WaitForCompletionAsync(viewNSGRulesOperation);

            //Verify effective security rule defined earlier
            IEnumerable <EffectiveNetworkSecurityRule> getEffectiveSecurityRule = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.EffectiveSecurityRules.Where(x => x.Name == "UserRule_" + securityRule1);

            Assert.AreEqual("Tcp", getEffectiveSecurityRule.FirstOrDefault().Protocol);
            Assert.AreEqual(501, getEffectiveSecurityRule.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getEffectiveSecurityRule.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getEffectiveSecurityRule.FirstOrDefault().Direction);
            Assert.AreEqual("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("80-80", getEffectiveSecurityRule.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("0.0.0.0/0", getEffectiveSecurityRule.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("0-65535", getEffectiveSecurityRule.FirstOrDefault().SourcePortRange);

            //Verify 6 default rules
            IEnumerable <SecurityRule> getDefaultSecurityRule1 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetInBound");

            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().Protocol);
            Assert.AreEqual(65000, getDefaultSecurityRule1.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule1.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule1.FirstOrDefault().Direction);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule1.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule1.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule2 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowAzureLoadBalancerInBound");

            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().Protocol);
            Assert.AreEqual(65001, getDefaultSecurityRule2.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule2.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule2.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("AzureLoadBalancer", getDefaultSecurityRule2.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule2.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule3 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllInBound");

            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().Protocol);
            Assert.AreEqual(65500, getDefaultSecurityRule3.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getDefaultSecurityRule3.FirstOrDefault().Access);
            Assert.AreEqual("Inbound", getDefaultSecurityRule3.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule3.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule4 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowVnetOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().Protocol);
            Assert.AreEqual(65000, getDefaultSecurityRule4.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule4.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule4.FirstOrDefault().Direction);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("VirtualNetwork", getDefaultSecurityRule4.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule4.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule5 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "AllowInternetOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().Protocol);
            Assert.AreEqual(65001, getDefaultSecurityRule5.FirstOrDefault().Priority);
            Assert.AreEqual("Allow", getDefaultSecurityRule5.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule5.FirstOrDefault().Direction);
            Assert.AreEqual("Internet", getDefaultSecurityRule5.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule5.FirstOrDefault().SourcePortRange);

            IEnumerable <SecurityRule> getDefaultSecurityRule6 = viewNSGRules.Value.NetworkInterfaces.FirstOrDefault().SecurityRuleAssociations.DefaultSecurityRules.Where(x => x.Name == "DenyAllOutBound");

            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().Protocol);
            Assert.AreEqual(65500, getDefaultSecurityRule6.FirstOrDefault().Priority);
            Assert.AreEqual("Deny", getDefaultSecurityRule6.FirstOrDefault().Access);
            Assert.AreEqual("Outbound", getDefaultSecurityRule6.FirstOrDefault().Direction);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().DestinationAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().DestinationPortRange);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().SourceAddressPrefix);
            Assert.AreEqual("*", getDefaultSecurityRule6.FirstOrDefault().SourcePortRange);
        }
Example #18
0
        public async Task EntityMergeDoesPartialPropertyUpdates()
        {
            string tableName = $"testtable{Recording.GenerateId()}";

            const string rowKeyValue       = "1";
            const string propertyName      = "SomeStringProperty";
            const string mergepropertyName = "MergedProperty";
            const string originalValue     = "This is the original";
            const string mergeValue        = "This was merged!";
            const string mergeUpdatedValue = "merged value was updated!";
            var          entity            = new Dictionary <string, object>
            {
                { "PartitionKey", PartitionKeyValue },
                { "RowKey", rowKeyValue },
                { propertyName, originalValue }
            };
            var partialEntity = new Dictionary <string, object>
            {
                { "PartitionKey", PartitionKeyValue },
                { "RowKey", rowKeyValue },
                { mergepropertyName, mergeValue }
            };


            // Create the new entity.

            await client.UpsertEntityAsync(entity, UpdateMode.Replace).ConfigureAwait(false);

            // Fetch the created entity from the service.

            var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

            // Verify that the merge property does not yet exist yet and that the original property does exist.

            Assert.That(originalEntity.TryGetValue(mergepropertyName, out var _), Is.False);
            Assert.That(originalEntity[propertyName], Is.EqualTo(originalValue));

            await client.UpsertEntityAsync(partialEntity, UpdateMode.Merge).ConfigureAwait(false);

            // Fetch the updated entity from the service.

            var mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

            // Verify that the merge property does not yet exist yet and that the original property does exist.

            Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeValue));
            Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));

            // Update just the merged value.

            partialEntity[mergepropertyName] = mergeUpdatedValue;
            await client.UpsertEntityAsync(partialEntity, UpdateMode.Merge).ConfigureAwait(false);

            // Fetch the updated entity from the service.

            mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

            // Verify that the merge property does not yet exist yet and that the original property does exist.

            Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeUpdatedValue));
            Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));
        }
Example #19
0
        public void ValidateSasCredentials()
        {
            // Create a SharedKeyCredential that we can use to sign the SAS token

            var credential = new TableSharedKeyCredential(TestEnvironment.AccountName, TestEnvironment.PrimaryStorageAccountKey);

            // Build a shared access signature with only Read permissions.

            TableSasBuilder sas   = client.GetSasBuilder(TableSasPermissions.Read, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
            string          token = sas.Sign(credential);

            // Build a SAS URI
            UriBuilder sasUri = new UriBuilder(TestEnvironment.StorageUri)
            {
                Query = token
            };

            // Create the TableServiceClient using the SAS URI.

            var sasAuthedService = InstrumentClient(new TableServiceClient(sasUri.Uri, Recording.InstrumentClientOptions(new TableClientOptions())));
            var sasTableclient   = sasAuthedService.GetTableClient(tableName);

            // Validate that we are able to query the table from the service.

            Assert.That(async() => await sasTableclient.QueryAsync().ToEnumerableAsync().ConfigureAwait(false), Throws.Nothing);

            // Validate that we are not able to upsert an entity to the table.

            Assert.That(async() => await sasTableclient.UpsertEntityAsync(CreateTableEntities("partition", 1).First(), UpdateMode.Replace), Throws.InstanceOf <RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.Forbidden));
        }
Example #20
0
        public void CheckRecording()
        {
            var tempoMap = TempoMap.Default;

            var stopAfter  = TimeSpan.FromSeconds(1);
            var stopPeriod = TimeSpan.FromSeconds(2);

            var eventsToSend = new[]
            {
                new EventToSend(new NoteOnEvent(), TimeSpan.Zero),
                new EventToSend(new NoteOffEvent(), TimeSpan.FromMilliseconds(500)),
                new EventToSend(new TimingClockEvent(), TimeSpan.FromSeconds(5))
            };

            var sentEvents     = new List <SentEvent>();
            var receivedEvents = new List <ReceivedEvent>();
            var stopwatch      = new Stopwatch();

            var expectedTimes         = new List <TimeSpan>();
            var expectedRecordedTimes = new List <TimeSpan>();
            var currentTime           = TimeSpan.Zero;

            foreach (var eventToSend in eventsToSend)
            {
                currentTime += eventToSend.Delay;
                expectedTimes.Add(currentTime);
                expectedRecordedTimes.Add(currentTime > stopAfter ? currentTime - stopPeriod : currentTime);
            }

            using (var outputDevice = OutputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
            {
                SendReceiveUtilities.WarmUpDevice(outputDevice);
                outputDevice.EventSent += (_, e) => sentEvents.Add(new SentEvent(e.Event, stopwatch.Elapsed));

                using (var inputDevice = InputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
                {
                    inputDevice.StartEventsListening();
                    inputDevice.EventReceived += (_, e) => receivedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));

                    using (var recording = new Recording(tempoMap, inputDevice))
                    {
                        var sendingThread = new Thread(() =>
                        {
                            SendReceiveUtilities.SendEvents(eventsToSend, outputDevice);
                        });

                        stopwatch.Start();
                        recording.Start();
                        sendingThread.Start();
                        Thread.Sleep(stopAfter);

                        recording.Stop();
                        Thread.Sleep(stopPeriod);

                        recording.Start();

                        var timeout           = expectedTimes.Last() + SendReceiveUtilities.MaximumEventSendReceiveDelay;
                        var areEventsReceived = SpinWait.SpinUntil(() => receivedEvents.Count == expectedTimes.Count, timeout);
                        Assert.IsTrue(areEventsReceived, $"Events are not received for timeout {timeout}.");

                        CompareSentReceivedEvents(sentEvents, receivedEvents, expectedTimes);

                        var recordedEvents = recording.GetEvents();
                        CheckRecordedEvents(recordedEvents, expectedRecordedTimes, tempoMap);
                    }
                }
            }
        }
Example #21
0
        public async Task DeleteConnectionMonitorTest()
        {
            string resourceGroupName = Recording.GenerateAssetName("azsmnet");

            string location      = "westus2";
            var    resourceGroup = await CreateResourceGroup(resourceGroupName, location);

            string virtualMachineName       = Recording.GenerateAssetName("azsmnet");
            string networkInterfaceName     = Recording.GenerateAssetName("azsmnet");
            string networkSecurityGroupName = virtualMachineName + "-nsg";

            //Deploy VM with a template
            var vm = await CreateWindowsVM(virtualMachineName, networkInterfaceName, location, resourceGroup);

            //Deploy networkWatcherAgent on VM
            await deployWindowsNetworkAgent(virtualMachineName, location, resourceGroup);

            //TODO:There is no need to perform a separate create NetworkWatchers operation
            //Create network Watcher
            //string networkWatcherName = Recording.GenerateAssetName("azsmnet");
            //NetworkWatcherResource properties = new NetworkWatcherResource { Location = location };
            //await networkWatcherCollection.CreateOrUpdateAsync(true, "NetworkWatcherRG", "NetworkWatcher_westus2", properties);

            string connectionMonitorName1 = Recording.GenerateAssetName("azsmnet");
            string connectionMonitorName2 = Recording.GenerateAssetName("azsmnet");
            var    cm = new ConnectionMonitorCreateOrUpdateContent
            {
                Location    = location,
                Source      = new ConnectionMonitorSource(vm.Id),
                Destination = new ConnectionMonitorDestination
                {
                    Address = "bing.com",
                    Port    = 80
                },
                MonitoringIntervalInSeconds = 30,
                AutoStart = false
            };

            var connectionMonitor1Operation = await ConnectionMonitors.CreateOrUpdateAsync(WaitUntil.Completed, connectionMonitorName1, cm);

            await connectionMonitor1Operation.WaitForCompletionAsync();;
            var connectionMonitor2Operation = await ConnectionMonitors.CreateOrUpdateAsync(WaitUntil.Completed, connectionMonitorName2, cm);

            var connectionMonitor2 = (await connectionMonitor2Operation.WaitForCompletionAsync()).Value;

            AsyncPageable <ConnectionMonitorResource> getConnectionMonitors1AP = ConnectionMonitors.GetAllAsync();
            Task <List <ConnectionMonitorResource> >  getConnectionMonitors1   = getConnectionMonitors1AP.ToEnumerableAsync();

            Assert.AreEqual(2, getConnectionMonitors1.Result.Count);

            var operation = await connectionMonitor2.DeleteAsync(WaitUntil.Completed);

            await operation.WaitForCompletionResponseAsync();

            // TODO: restore to use Delete of the specific resource collection: ADO 5998
            //Operation connectionMonitorsDeleteOperation = await ConnectionMonitors.Get(connectionMonitorName2).Value.DeleteAsync(true);
            //await connectionMonitorsDeleteOperation.WaitForCompletionAsync();;
            AsyncPageable <ConnectionMonitorResource> getConnectionMonitors2 = ConnectionMonitors.GetAllAsync();

            Has.One.EqualTo(getConnectionMonitors2);
        }
 private void Start()
 {
     trainingAudio    = GetComponent <AudioSource>(); // may need to be more specific
     recordingToTrain = null;
 }
Example #23
0
    public void OnRecord()
    {
        if (!this.audioSource.isPlaying)
            return;

        if (this.isRecording)
        {
            this.rec.playEnd = this.audioSource.time;
            this.isRecording = false;
            this.hasRecording = true;
        }

        else {

            this.rec = new Recording(this);
            this.rec.playStart = this.audioSource.time;
            this.rec.volume = this.audioSource.volume;

            this.isRecording = true;
        }
    }
 public RecordingTests()
 {
     this.recording = TestHelper.GetJson <Recording>("recording-get.json");
 }
Example #25
0
        //[Trait("Name", "TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest")]
        public async Task TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest()
        {
            EnsureClientsInitialized(LocationEastUs2);

            ImageReference imageRef = await GetPlatformVMImage(useWindowsImage : true);

            // Create resource group
            var    rgName             = Recording.GenerateAssetName(TestPrefix);
            var    vmssName           = Recording.GenerateAssetName("vmss");
            string storageAccountName = Recording.GenerateAssetName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;
            var storageAccountOutput = await CreateStorageAccount(rgName, storageAccountName);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, "VMScaleSetDoesNotExist"));

            var getTwoVirtualMachineScaleSet = await CreateVMScaleSet_NoAsyncTracking(
                rgName,
                vmssName,
                storageAccountOutput,
                imageRef,
                null,
                (vmScaleSet) =>
            {
                vmScaleSet.Overprovision = false;
            },
                createWithManagedDisks : true,
                createWithPublicIpAddress : false,
                createWithHealthProbe : true);

            VirtualMachineScaleSet getResponse = getTwoVirtualMachineScaleSet.Item1;

            inputVMScaleSet = getTwoVirtualMachineScaleSet.Item2;
            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);

            // Set Automatic Repairs to true
            inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy()
            {
                Enabled = true
            };
            await UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);

            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);

            Assert.NotNull(getResponse.AutomaticRepairsPolicy);
            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);

            // Update Automatic Repairs default values
            inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy()
            {
                Enabled = true,

                GracePeriod = "PT35M"
            };
            await UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);

            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);

            Assert.NotNull(getResponse.AutomaticRepairsPolicy);
            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);

            // Set automatic repairs to null
            inputVMScaleSet.AutomaticRepairsPolicy = null;
            await UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);

            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);

            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
            Assert.NotNull(getResponse.AutomaticRepairsPolicy);
            Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == true);

            Assert.AreEqual("PT35M", getResponse.AutomaticRepairsPolicy.GracePeriod);

            // Disable Automatic Repairs
            inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy()
            {
                Enabled = false
            };
            await UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);

            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmssName);

            Assert.NotNull(getResponse.AutomaticRepairsPolicy);
            Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == false);
        }
Example #26
0
        public async Task AddTag()
        {
            ResourceGroup rg = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).CreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            var aset = await CreateGenericAvailabilitySetAsync(rg.Id);

            Assert.AreEqual(0, aset.Data.Tags.Count);

            aset = await aset.AddTagAsync("key", "value");

            Assert.IsTrue(aset.Data.Tags.ContainsKey("key"));
            Assert.AreEqual("value", aset.Data.Tags["key"]);
        }
Example #27
0
    /// <summary>
    /// Play the specified recording, from optional specified time
    /// </summary>
    /// <param name='recording'>
    /// Recording.
    /// </param>
    /// <param name='startRecordingFromTime'>
    /// OPTIONAL: Time to start recording at
    /// </param>
    public void Play( Recording recording, float startRecordingFromTime = 0 )
    {
        currentRecording = new Recording( recording );
        currentFrame = recording.GetClosestFrame ( startRecordingFromTime );

        thisFrameInputs.Clear ();
        lastFrameInputs.Clear ();

        _mode = InputVCRMode.Playback;
        playbackTime = startRecordingFromTime;
    }
Example #28
0
        public async Task Get()
        {
            ResourceGroup rg = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).CreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            var aset = await CreateGenericAvailabilitySetAsync(rg.Id);

            GenericResource aset2 = await aset.GetAsync();

            AssertAreEqual(aset, aset2);
        }
 public void Create(Recording recording)
 {
     _context.Recordings.Add(recording);
     _context.SaveChanges();
 }
Example #30
0
        public async Task RemoveTag()
        {
            ResourceGroup rg = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).CreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            var aset = await CreateGenericAvailabilitySetAsync(rg.Id);

            Dictionary <string, string> tags = new Dictionary <string, string>();

            tags.Add("key", "value");
            aset = await aset.SetTagsAsync(tags);

            aset = await aset.RemoveTagAsync("key");

            Assert.IsFalse(aset.Data.Tags.ContainsKey("key"));
            Assert.AreEqual(0, aset.Data.Tags.Count);
        }
        public async Task TestVMScaleSetPatchOperations()
        {
            EnsureClientsInitialized(DefaultLocation);

            ImageReference imageRef = await GetPlatformVMImage(useWindowsImage : true);

            // Create resource group
            var    rgName             = Recording.GenerateAssetName(TestPrefix);
            var    vmssName           = Recording.GenerateAssetName("vmss");
            string storageAccountName = Recording.GenerateAssetName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;
            var storageAccountOutput = await CreateStorageAccount(rgName, storageAccountName);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, "VMScaleSetDoesNotExist"));

            var getTwoVirtualMachineScaleSet = await CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef);

            VirtualMachineScaleSet vmScaleSet = getTwoVirtualMachineScaleSet.Response;

            inputVMScaleSet = getTwoVirtualMachineScaleSet.Input;
            var getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmScaleSet.Name);

            ValidateVMScaleSet(inputVMScaleSet, getResponse);

            // Adding an extension to the VMScaleSet. We will use Patch to update this.
            VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
            {
                Extensions =
                {
                    GetTestVMSSVMExtension(),
                }
            };

            VirtualMachineScaleSetUpdate patchVMScaleSet = new VirtualMachineScaleSetUpdate()
            {
                VirtualMachineProfile = new VirtualMachineScaleSetUpdateVMProfile()
                {
                    ExtensionProfile = extensionProfile,
                },
            };

            await PatchVMScaleSet(rgName, vmssName, patchVMScaleSet);

            // Update the inputVMScaleSet and then compare it with response to verify the result.
            inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile;
            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmScaleSet.Name);

            ValidateVMScaleSet(inputVMScaleSet, getResponse);

            // Scaling the VMScaleSet now to 3 instances
            VirtualMachineScaleSetUpdate patchVMScaleSet2 = new VirtualMachineScaleSetUpdate()
            {
                Sku = new Sku()
                {
                    Capacity = 3,
                },
            };

            await PatchVMScaleSet(rgName, vmssName, patchVMScaleSet2);

            // Validate that ScaleSet Scaled to 3 instances
            inputVMScaleSet.Sku.Capacity = 3;
            getResponse = await VirtualMachineScaleSetsOperations.GetAsync(rgName, vmScaleSet.Name);

            ValidateVMScaleSet(inputVMScaleSet, getResponse);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, vmScaleSet.Name));
        }
Example #32
0
        public async Task StartUpdate()
        {
            var rgOp = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).StartCreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            ResourceGroup rg = await rgOp.WaitForCompletionAsync();

            var createOp = await StartCreateGenericAvailabilitySetAsync(rg.Id);

            GenericResource aset = await createOp.WaitForCompletionAsync();

            var data = ConstructGenericAvailabilitySet();

            data.Tags.Add("key", "value");
            var updateOp = await aset.StartUpdateAsync(data);

            aset = await updateOp.WaitForCompletionAsync();

            Assert.IsTrue(aset.Data.Tags.ContainsKey("key"));
            Assert.AreEqual("value", aset.Data.Tags["key"]);

            Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                var updateOp = await aset.StartUpdateAsync(null);
                _            = await updateOp.WaitForCompletionAsync();
            });
        }
 public void GetDeletedSecretNonExisting()
 {
     Assert.ThrowsAsync <RequestFailedException>(() => Client.GetDeletedSecretAsync(Recording.GenerateId()));
 }
Example #34
0
        public async Task Delete()
        {
            ResourceGroup rg = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).CreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            var aset = await CreateGenericAvailabilitySetAsync(rg.Id);

            Assert.DoesNotThrowAsync(async() => await aset.DeleteAsync());

            var fakeId = $"/subscriptions/{TestEnvironment.SubscriptionId}/resourceGroups/foo-1";

            Assert.ThrowsAsync <RequestFailedException>(async() => _ = await CreateGenericAvailabilitySetAsync(fakeId));
        }
Example #35
0
        public async Task CreateGetUpdateDeleteDisasterRecovery()
        {
            _resourceGroup = await CreateResourceGroupAsync();

            //create namespace1
            string namespaceName1 = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces();
            EventHubNamespaceResource   eHNamespace1        = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName1, new EventHubNamespaceData(DefaultLocation))).Value;

            //create namespace2 with a different location
            string namespaceName2 = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceResource eHNamespace2 = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName2, new EventHubNamespaceData(AzureLocation.EastUS))).Value;

            //create authorization rule on namespace1
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            AuthorizationRuleData ruleParameter = new AuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceAuthorizationRuleResource authorizationRule = (await eHNamespace1.GetNamespaceAuthorizationRules().CreateOrUpdateAsync(WaitUntil.Completed, ruleName, ruleParameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, ruleParameter.Rights.Count);

            //create a disaster recovery
            string disasterRecoveryName    = Recording.GenerateAssetName("disasterrecovery");
            DisasterRecoveryData parameter = new DisasterRecoveryData()
            {
                PartnerNamespace = eHNamespace2.Id
            };
            DisasterRecoveryResource armDisasterRecovery = (await eHNamespace1.GetDisasterRecoveries().CreateOrUpdateAsync(WaitUntil.Completed, disasterRecoveryName, parameter)).Value;

            Assert.NotNull(armDisasterRecovery);
            Assert.AreEqual(armDisasterRecovery.Id.Name, disasterRecoveryName);
            Assert.AreEqual(armDisasterRecovery.Data.PartnerNamespace, eHNamespace2.Id.ToString());

            //get the disaster recovery - primary
            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(armDisasterRecovery.Data.Role, RoleDisasterRecovery.Primary);

            //get the disaster recovery - secondary
            DisasterRecoveryResource armDisasterRecoverySec = await eHNamespace2.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(armDisasterRecoverySec.Data.Role, RoleDisasterRecovery.Secondary);

            //wait for completion, this may take several minutes in live and record mode
            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            int i = 0;

            while (armDisasterRecovery.Data.ProvisioningState != DisasterRecoveryProvisioningState.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }
            System.Console.WriteLine(i);

            //check name availability
            CheckNameAvailabilityResult nameAvailability = await eHNamespace1.CheckDisasterRecoveryNameAvailabilityAsync(new CheckNameAvailabilityOptions(disasterRecoveryName));

            Assert.IsFalse(nameAvailability.NameAvailable);

            List <DisasterRecoveryAuthorizationRuleResource> rules = await armDisasterRecovery.GetDisasterRecoveryAuthorizationRules().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(rules.Count > 0);

            //get access keys of the authorization rule
            DisasterRecoveryAuthorizationRuleResource rule = rules.First();
            AccessKeys keys = await rule.GetKeysAsync();

            Assert.NotNull(keys);

            //break pairing and wait for completion
            await armDisasterRecovery.BreakPairingAsync();

            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            i = 0;
            while (armDisasterRecovery.Data.ProvisioningState != DisasterRecoveryProvisioningState.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }

            //get all disaster recoveries for a name space
            List <DisasterRecoveryResource> disasterRcoveries = await eHNamespace1.GetDisasterRecoveries().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(disasterRcoveries.Count >= 1);

            //delete disaster recovery;
            await armDisasterRecovery.DeleteAsync(WaitUntil.Completed);
        }
Example #36
0
        public async Task StartDelete()
        {
            var rgOp = await Client.DefaultSubscription.GetResourceGroups().Construct(Location.WestUS2).StartCreateOrUpdateAsync(Recording.GenerateAssetName("testrg"));

            ResourceGroup rg = await rgOp.WaitForCompletionAsync();

            var createOp = await StartCreateGenericAvailabilitySetAsync(rg.Id);

            GenericResource aset = await createOp.WaitForCompletionAsync();

            Assert.DoesNotThrowAsync(async() =>
            {
                var deleteOp = await aset.StartDeleteAsync();
                _            = await deleteOp.WaitForCompletionResponseAsync();
            });

            var fakeId = $"/subscriptions/{TestEnvironment.SubscriptionId}/resourceGroups/foo-1";

            Assert.ThrowsAsync <RequestFailedException>(async() =>
            {
                var createOp = await StartCreateGenericAvailabilitySetAsync(fakeId);
                _            = await createOp.WaitForCompletionAsync();
            });
        }
Example #37
0
        //[Trait("Name", "TestVMScaleSetScenarioOperations_OrchestrationService")]
        public async Task TestVMScaleSetScenarioOperations_OrchestrationService()
        {
            EnsureClientsInitialized(LocationNorthEurope);

            ImageReference imageRef = await GetPlatformVMImage(useWindowsImage : true);

            // Create resource group
            var    rgName             = Recording.GenerateAssetName(TestPrefix);
            var    vmssName           = Recording.GenerateAssetName("vmss");
            string storageAccountName = Recording.GenerateAssetName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;
            var storageAccountOutput = await CreateStorageAccount(rgName, storageAccountName);

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, "VMScaleSetDoesNotExist"));

            AutomaticRepairsPolicy automaticRepairsPolicy = new AutomaticRepairsPolicy()
            {
                Enabled = true
            };
            var getTwoVirtualMachineScaleSet = await CreateVMScaleSet_NoAsyncTracking(
                rgName,
                vmssName,
                storageAccountOutput,
                imageRef,
                null,
                (vmScaleSet) =>
            {
                vmScaleSet.Overprovision = false;
            },
                createWithManagedDisks : true,
                createWithPublicIpAddress : false,
                createWithHealthProbe : true,
                automaticRepairsPolicy : automaticRepairsPolicy);

            VirtualMachineScaleSet getResponse = getTwoVirtualMachineScaleSet.Item1;

            inputVMScaleSet = getTwoVirtualMachineScaleSet.Item2;
            ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
            var getInstanceViewResponse = (await VirtualMachineScaleSetsOperations.GetInstanceViewAsync(rgName, vmssName)).Value;

            Assert.True(getInstanceViewResponse.OrchestrationServices.Count == 1);
            Assert.AreEqual("Running", getInstanceViewResponse.OrchestrationServices[0].ServiceState.ToString());
            Assert.AreEqual("AutomaticRepairs", getInstanceViewResponse.OrchestrationServices[0].ServiceName.ToString());


            ////TODO
            OrchestrationServiceStateInput orchestrationServiceStateInput = new OrchestrationServiceStateInput(new OrchestrationServiceSummary().ServiceName, OrchestrationServiceStateAction.Suspend);

            //OrchestrationServiceStateAction orchestrationServiceStateAction = new OrchestrationServiceStateAction();
            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartSetOrchestrationServiceStateAsync(rgName, vmssName, orchestrationServiceStateInput));

            getInstanceViewResponse = await VirtualMachineScaleSetsOperations.GetInstanceViewAsync(rgName, vmssName);

            Assert.AreEqual(OrchestrationServiceState.Suspended.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState.ToString());

            orchestrationServiceStateInput = new OrchestrationServiceStateInput(new OrchestrationServiceSummary().ServiceName, OrchestrationServiceStateAction.Resume);
            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartSetOrchestrationServiceStateAsync(rgName, vmssName, orchestrationServiceStateInput));

            getInstanceViewResponse = await VirtualMachineScaleSetsOperations.GetInstanceViewAsync(rgName, vmssName);

            Assert.AreEqual(OrchestrationServiceState.Running.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState.ToString());

            await WaitForCompletionAsync(await VirtualMachineScaleSetsOperations.StartDeleteAsync(rgName, vmssName));
        }
 public static void StartPlaybackLevelEnd(Recording rec, bool won)
 {
     playingBack = true;
     current = rec;
     wonLast = won;
     fromMenu = false;
     reloading = true;
     Loading.Load(rec.levelName);
 }
 void LoadRecordingFromInternet(Recording recording)
 {
     GameRecorder.StartPlaybackFromMenu(recording);
 }
    public static void StartRecording()
    {
        if (instance != null)
        {
            current = new Recording();
            current.levelName = Application.loadedLevelName;
            current.fps = fps;
            timeDif = 1.0f / (float)fps;

            recording = true;

            // Start recording coroutine
            instance.StartCoroutine("DoRecord");
        }
    }
 /// <summary>
 /// Gets the title and year from a recording title
 /// Title should be in the form 'title (year)' or 'title [year]'
 /// </summary>
 private void GetTitleAndYear(Recording info, out string title, out string year)
 {
     Match regMatch = Regex.Match(info.Title, @"^(?<title>.+?)(?:\s*[\(\[](?<year>\d{4})[\]\)])?$");
     title = regMatch.Groups["title"].Value;
     year = regMatch.Groups["year"].Value;
 }
 public static void StartPlayback(Recording rec)
 {
     playingBack = true;
     current = rec;
     Playback(current);
 }
 public void SetRecording(Recording recording)
 {
     _recording = recording;
 }
    void Update()
    {
        if (currentRecording != selGridInt)
        {
            currentRecording = selGridInt;
            if (selGridInt < fullFilenames.Count)
                current = Recording.Read(fullFilenames[selGridInt]);
            else
                current = null;
        }

        if (playRecording && current != null)
        {
            // Play back recording
            playRecording = false;
            GameRecorder.StartPlaybackFromMenu(current);
        }
    }
Example #45
0
    /// <summary>
    /// Starts a new recording. If old recording wasn't saved it will be lost forever!
    /// </summary>
    public void NewRecording()
    {
        // start recording live input
        currentRecording = new Recording( recordingFrameRate );
        currentFrame = 0;
        realRecordingTime = 0;

        nextPosSyncTime = -1f;
        nextPropertiesToRecord.Clear ();

        _mode = InputVCRMode.Record;
    }
Example #46
0
 private static bool GetRecording(IProgram program, out Recording recording)
 {
   IRecordingService recordingService = GlobalServiceProvider.Instance.Get<IRecordingService>();
   recording = recordingService.GetActiveRecordingByTitleAndChannel(program.Title, program.ChannelId);
   return recording != null;
 }
        public async Task NamespaceCreateGetUpdateDeleteAuthorizationRule()
        {
            //create namespace
            _resourceGroup = await CreateResourceGroupAsync();

            EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces();
            string namespaceName = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceResource            eventHubNamespace = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName, new EventHubNamespaceData(DefaultLocation))).Value;
            NamespaceAuthorizationRuleCollection ruleCollection    = eventHubNamespace.GetNamespaceAuthorizationRules();

            //create authorization rule
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            AuthorizationRuleData parameter = new AuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceAuthorizationRuleResource authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            //get authorization rule
            authorizationRule = await ruleCollection.GetAsync(ruleName);

            Assert.AreEqual(authorizationRule.Id.Name, ruleName);
            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            //get all authorization rules
            List <NamespaceAuthorizationRuleResource> rules = await ruleCollection.GetAllAsync().ToEnumerableAsync();

            //there should be two authorization rules
            Assert.True(rules.Count > 1);
            bool isContainAuthorizationRuleName = false;
            bool isContainDefaultRuleName       = false;

            foreach (NamespaceAuthorizationRuleResource rule in rules)
            {
                if (rule.Id.Name == ruleName)
                {
                    isContainAuthorizationRuleName = true;
                }
                if (rule.Id.Name == DefaultNamespaceAuthorizationRule)
                {
                    isContainDefaultRuleName = true;
                }
            }
            Assert.True(isContainDefaultRuleName);
            Assert.True(isContainAuthorizationRuleName);

            //update authorization rule
            parameter.Rights.Add(AccessRights.Manage);
            authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value;
            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            //delete authorization rule
            await authorizationRule.DeleteAsync(WaitUntil.Completed);

            //validate if deleted
            Assert.IsFalse(await ruleCollection.ExistsAsync(ruleName));
            rules = await ruleCollection.GetAllAsync().ToEnumerableAsync();

            Assert.True(rules.Count == 1);
            Assert.AreEqual(rules[0].Id.Name, DefaultNamespaceAuthorizationRule);
        }
        public async Task TrainingOps(bool labeled)
        {
            var client           = CreateInstrumentedFormTrainingClient();
            var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl);
            TrainingOperation operation;

            // TODO: sanitize body and enable body recording here.
            using (Recording.DisableRequestBodyRecording())
            {
                operation = await client.StartTrainingAsync(trainingFilesUri, labeled);
            }

            await operation.WaitForCompletionAsync();

            Assert.IsTrue(operation.HasValue);

            CustomFormModel trainedModel = operation.Value;

            CustomFormModel resultModel = await client.GetCustomModelAsync(trainedModel.ModelId);

            Assert.AreEqual(trainedModel.ModelId, resultModel.ModelId);
            Assert.AreEqual(trainedModel.RequestedOn, resultModel.RequestedOn);
            Assert.AreEqual(trainedModel.CompletedOn, resultModel.CompletedOn);
            Assert.AreEqual(CustomFormModelStatus.Ready, resultModel.Status);
            Assert.AreEqual(trainedModel.Status, resultModel.Status);
            Assert.AreEqual(trainedModel.Errors.Count, resultModel.Errors.Count);

            for (int i = 0; i < resultModel.TrainingDocuments.Count; i++)
            {
                var tm = trainedModel.TrainingDocuments[i];
                var rm = resultModel.TrainingDocuments[i];

                Assert.AreEqual(tm.DocumentName, rm.DocumentName);
                Assert.AreEqual(tm.PageCount, rm.PageCount);
                Assert.AreEqual(TrainingStatus.Succeeded, rm.Status);
                Assert.AreEqual(tm.Status, rm.Status);
                Assert.AreEqual(tm.Errors.Count, rm.Errors.Count);
            }

            for (int i = 0; i < resultModel.Submodels.Count; i++)
            {
                Assert.AreEqual(trainedModel.Submodels[i].FormType, resultModel.Submodels[i].FormType);

                foreach (var fields in resultModel.Submodels[i].Fields)
                {
                    Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Name, fields.Value.Name);
                    if (labeled)
                    {
                        Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Accuracy, fields.Value.Accuracy);
                    }
                    else
                    {
                        Assert.AreEqual(trainedModel.Submodels[i].Fields[fields.Key].Label, fields.Value.Label);
                    }
                }
            }

            CustomFormModelInfo modelInfo = client.GetCustomModelsAsync().ToEnumerableAsync().Result.FirstOrDefault();

            Assert.IsNotNull(modelInfo.ModelId);
            Assert.IsNotNull(modelInfo.RequestedOn);
            Assert.IsNotNull(modelInfo.CompletedOn);
            Assert.IsNotNull(modelInfo.Status);

            AccountProperties accountP = await client.GetAccountPropertiesAsync();

            Assert.IsNotNull(accountP.CustomModelCount);
            Assert.IsNotNull(accountP.CustomModelLimit);

            await client.DeleteModelAsync(trainedModel.ModelId);

            Assert.ThrowsAsync <RequestFailedException>(() => client.GetCustomModelAsync(trainedModel.ModelId));
        }
 public static void StartPlaybackTutorial(Recording rec)
 {
     instance.time = 0.0f;
     StopPlayback();
     StartPlayback(rec);
 }
        public async Task SetGetNetworkRuleSets()
        {
            //create namespace
            _resourceGroup = await CreateResourceGroupAsync();

            EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces();
            string namespaceName = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceResource eventHubNamespace = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName, new EventHubNamespaceData(DefaultLocation))).Value;

            //prepare vnet
            string vnetName   = Recording.GenerateAssetName("sdktestvnet");
            var    parameters = new VirtualNetworkData
            {
                Subnets =
                {
                    new SubnetData
                    {
                        Name             = "default1",
                        AddressPrefix    = "10.0.0.0/24",
                        ServiceEndpoints ={ new ServiceEndpointPropertiesFormat                        {
                          Service = "Microsoft.EventHub"
                      } }
                    },
                    new SubnetData
                    {
                        Name             = "default2",
                        AddressPrefix    = "10.0.1.0/24",
                        ServiceEndpoints ={ new ServiceEndpointPropertiesFormat                        {
                          Service = "Microsoft.EventHub"
                      } }
                    },
                    new SubnetData
                    {
                        Name             = "default3",
                        AddressPrefix    = "10.0.2.0/24",
                        ServiceEndpoints ={ new ServiceEndpointPropertiesFormat                        {
                          Service = "Microsoft.EventHub"
                      } }
                    }
                },
                Location = "eastus2"
            };

            parameters.AddressPrefixes.Add("10.0.0.0/16");
            VirtualNetworkResource virtualNetwork = (await _resourceGroup.GetVirtualNetworks().CreateOrUpdateAsync(WaitUntil.Completed, vnetName, parameters)).Value;

            //set network rule set
            string             subscriptionId = DefaultSubscription.Id.ToString();
            ResourceIdentifier subnetId1      = new ResourceIdentifier(subscriptionId + "/resourcegroups/" + _resourceGroup.Id.Name + "/providers/Microsoft.Network/virtualNetworks/" + vnetName + "/subnets/default1");
            ResourceIdentifier subnetId2      = new ResourceIdentifier(subscriptionId + "/resourcegroups/" + _resourceGroup.Id.Name + "/providers/Microsoft.Network/virtualNetworks/" + vnetName + "/subnets/default2");
            ResourceIdentifier subnetId3      = new ResourceIdentifier(subscriptionId + "/resourcegroups/" + _resourceGroup.Id.Name + "/providers/Microsoft.Network/virtualNetworks/" + vnetName + "/subnets/default3");
            NetworkRuleSetData parameter      = new NetworkRuleSetData()
            {
                DefaultAction       = DefaultAction.Deny,
                VirtualNetworkRules =
                {
                    new NetworkRuleSetVirtualNetworkRules()
                    {
                        Subnet = new WritableSubResource()
                        {
                            Id = subnetId1
                        }
                    },
                    new NetworkRuleSetVirtualNetworkRules()
                    {
                        Subnet = new WritableSubResource()
                        {
                            Id = subnetId2
                        }
                    },
                    new NetworkRuleSetVirtualNetworkRules()
                    {
                        Subnet = new WritableSubResource()
                        {
                            Id = subnetId3
                        }
                    }
                },
                IPRules =
                {
                    new NetworkRuleSetIPRules()
                    {
                        IPMask = "1.1.1.1", Action = "Allow"
                    },
                    new NetworkRuleSetIPRules()
                    {
                        IPMask = "1.1.1.2", Action = "Allow"
                    },
                    new NetworkRuleSetIPRules()
                    {
                        IPMask = "1.1.1.3", Action = "Allow"
                    },
                    new NetworkRuleSetIPRules()
                    {
                        IPMask = "1.1.1.4", Action = "Allow"
                    },
                    new NetworkRuleSetIPRules()
                    {
                        IPMask = "1.1.1.5", Action = "Allow"
                    }
                }
            };
            await eventHubNamespace.GetNetworkRuleSet().CreateOrUpdateAsync(WaitUntil.Completed, parameter);

            //get the network rule set
            NetworkRuleSetResource networkRuleSet = await eventHubNamespace.GetNetworkRuleSet().GetAsync();

            Assert.NotNull(networkRuleSet);
            Assert.NotNull(networkRuleSet.Data.IPRules);
            Assert.NotNull(networkRuleSet.Data.VirtualNetworkRules);
            Assert.AreEqual(networkRuleSet.Data.VirtualNetworkRules.Count, 3);
            Assert.AreEqual(networkRuleSet.Data.IPRules.Count, 5);

            //delete virtual network
            await virtualNetwork.DeleteAsync(WaitUntil.Completed);
        }
 private static void Playback(Recording rec)
 {
     playingBack = true;
     playback = true;
     played = true;
 }
Example #52
0
 public static RecordingAddRequestBuilder Add(Recording recording)
 {
     return(new RecordingAddRequestBuilder(recording));
 }
 public static void StartPlaybackFromMenu(Recording rec)
 {
     playingBack = true;
     current = rec;
     wonLast = false;
     fromMenu = true;
     reloading = true;
     standalone = true;
     Loading.Load(rec.levelName);
 }
Example #54
0
 public void Update(ushort nextState)
 {
     Recording.Record(CurrentState, nextState, 1);
     CurrentState = nextState;
 }
Example #55
0
    public static Recording Read1(BinaryReader reader)
    {
        // Create a recording
        Recording rec = new Recording();

        // Read the flagged value
        rec.flagged = reader.ReadBoolean();

        // Read the fps
        rec.fps = reader.ReadInt32();

        // Read the score.
        rec.score.Read(reader);

        // Read the level name
        rec.levelName = reader.ReadString();

        // Read all the states.
        int stateCount = reader.ReadInt32();
        for (int i = 0; i < stateCount; ++i)
        {
            State state = new State();
            state.Read(reader);
            rec.states.Add(state);
        }

        return rec;
    }
        public async Task CreateOrUpdate()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string            rgName = Recording.GenerateAssetName("testRg-1-");
            ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2);
            var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(true, rgName, rgData);

            ResourceGroup             rg              = lro.Value;
            string                    appDefName      = Recording.GenerateAssetName("appDef-C-");
            ApplicationDefinitionData appDefData      = CreateApplicationDefinitionData(appDefName);
            ApplicationDefinition     appDef          = (await rg.GetApplicationDefinitions().CreateOrUpdateAsync(true, appDefName, appDefData)).Value;
            string                    appName         = Recording.GenerateAssetName("application-C-");
            ApplicationData           applicationData = CreateApplicationData(appDef.Id, subscription.Id + Recording.GenerateAssetName("/resourceGroups/managed-1-"), Recording.GenerateAssetName("s1"));
            Application               application     = (await rg.GetApplications().CreateOrUpdateAsync(true, appName, applicationData)).Value;

            Assert.AreEqual(appName, application.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetApplications().CreateOrUpdateAsync(true, null, applicationData));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetApplications().CreateOrUpdateAsync(true, appName, null));
        }
 public async Task<StorageFile> GetStorageFileAsync(Recording recording)
 {
     return await GetRecordingFileAsync(recording.Id);
 }
        public async Task ListBySubscription()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string            rgName = Recording.GenerateAssetName("testRg-3-");
            ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2);
            var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(true, rgName, rgData);

            ResourceGroup             rg              = lro.Value;
            string                    appDefName      = Recording.GenerateAssetName("appDef-L-");
            ApplicationDefinitionData appDefData      = CreateApplicationDefinitionData(appDefName);
            ApplicationDefinition     appDef          = (await rg.GetApplicationDefinitions().CreateOrUpdateAsync(true, appDefName, appDefData)).Value;
            string                    appName         = Recording.GenerateAssetName("application-L-");
            ApplicationData           applicationData = CreateApplicationData(appDef.Id, subscription.Id + Recording.GenerateAssetName("/resourceGroups/managed-3-"), Recording.GenerateAssetName("s3"));

            _ = await rg.GetApplications().CreateOrUpdateAsync(true, appName, applicationData);

            int count = 0;

            await foreach (var tempApplication in subscription.GetApplicationsAsync())
            {
                if (tempApplication.Data.ApplicationDefinitionId == appDef.Id)
                {
                    count++;
                }
            }
            Assert.AreEqual(count, 1);
        }
 private static void SaveToFile(List<Vector3> imagePoints, List<Vector3> worldPoints, string fileName)
 {
     var recording = new Recording(imagePoints, worldPoints, (double)Screen.width, (double)Screen.height);
     recording.SaveToFile(fileName);
 }
Example #60
0
        public async Task TimeSeriesInsightsInstances_Lifecycle()
        {
            // Arrange
            TimeSeriesInsightsClient client = GetClient();
            int numOfIdProperties           = 3;
            int numOfInstancesToSetup       = 2;
            var timeSeriesInstances         = new List <TimeSeriesInstance>();

            for (int i = 0; i < numOfInstancesToSetup; i++)
            {
                TimeSeriesId id = await GetUniqueTimeSeriesInstanceIdAsync(client, numOfIdProperties)
                                  .ConfigureAwait(false);

                timeSeriesInstances.Add(new TimeSeriesInstance(id, DefaultType));
            }

            IEnumerable <TimeSeriesId> timeSeriesInstancesIds = timeSeriesInstances.Select((instance) => instance.TimeSeriesId);

            // Act and assert
            try
            {
                // Create TSI instances
                Response <InstancesOperationError[]> createInstancesResult = await client
                                                                             .CreateOrReplaceTimeSeriesInstancesAsync(timeSeriesInstances)
                                                                             .ConfigureAwait(false);

                // Assert that the result error array does not contain any object that is set
                createInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult == null);

                // This retry logic was added as the TSI instance are not immediately available after creation
                await TestRetryHelper.RetryAsync <Response <InstancesOperationResult[]> >(async() =>
                {
                    // Get the created instances by Ids
                    Response <InstancesOperationResult[]> getInstancesByIdsResult = await client
                                                                                    .GetInstancesAsync(timeSeriesInstancesIds)
                                                                                    .ConfigureAwait(false);

                    getInstancesByIdsResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByIdsResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToArray().Length.Should().Be(numOfIdProperties);
                        instanceResult.Instance.TypeId.Should().Be(DefaultType);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    return(null);
                }, MaxNumberOfRetries, s_retryDelay);

                // Update the instances by adding names to them
                var tsiInstanceNamePrefix = "instance";
                timeSeriesInstances.ForEach((timeSeriesInstance) =>
                                            timeSeriesInstance.Name = Recording.GenerateAlphaNumericId(tsiInstanceNamePrefix));

                Response <InstancesOperationResult[]> replaceInstancesResult = await client
                                                                               .ReplaceTimeSeriesInstancesAsync(timeSeriesInstances)
                                                                               .ConfigureAwait(false);

                replaceInstancesResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                replaceInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult.Error == null);

                // This retry logic was added as the TSI instance are not immediately available after creation
                await TestRetryHelper.RetryAsync <Response <InstancesOperationResult[]> >(async() =>
                {
                    // Get instances by name
                    Response <InstancesOperationResult[]> getInstancesByNameResult = await client
                                                                                     .GetInstancesAsync(timeSeriesInstances.Select((instance) => instance.Name))
                                                                                     .ConfigureAwait(false);

                    getInstancesByNameResult.Value.Length.Should().Be(timeSeriesInstances.Count);
                    foreach (InstancesOperationResult instanceResult in getInstancesByNameResult.Value)
                    {
                        instanceResult.Instance.Should().NotBeNull();
                        instanceResult.Error.Should().BeNull();
                        instanceResult.Instance.TimeSeriesId.ToArray().Length.Should().Be(numOfIdProperties);
                        instanceResult.Instance.TypeId.Should().Be(DefaultType);
                        instanceResult.Instance.HierarchyIds.Count.Should().Be(0);
                        instanceResult.Instance.InstanceFields.Count.Should().Be(0);
                    }

                    return(null);
                }, MaxNumberOfRetries, s_retryDelay);

                // Get all Time Series instances in the environment
                AsyncPageable <TimeSeriesInstance> getAllInstancesResponse = client.GetInstancesAsync();

                int numOfInstances = 0;
                await foreach (TimeSeriesInstance tsiInstance in getAllInstancesResponse)
                {
                    numOfInstances++;
                    tsiInstance.Should().NotBeNull();
                }
                numOfInstances.Should().BeGreaterOrEqualTo(numOfInstancesToSetup);

                // Get search suggestions for the first instance
                var    timeSeriesIdToSuggest = (TimeSeriesId)timeSeriesInstances.First().TimeSeriesId;
                string suggestionString      = string.Join(string.Empty, timeSeriesIdToSuggest.ToArray()).Substring(0, 3);
                Response <SearchSuggestion[]> searchSuggestionResponse = await TestRetryHelper.RetryAsync(async() =>
                {
                    Response <SearchSuggestion[]> searchSuggestions = await client
                                                                      .GetSearchSuggestionsAsync(suggestionString)
                                                                      .ConfigureAwait(false);

                    if (searchSuggestions.Value.Length == 0)
                    {
                        throw new Exception($"Unable to find a search suggestion for string {suggestionString}.");
                    }

                    return(searchSuggestions);
                }, MaxNumberOfRetries, s_retryDelay);

                searchSuggestionResponse.Value.Length.Should().Be(1);
            }
            finally
            {
                // clean up
                try
                {
                    Response <InstancesOperationError[]> deleteInstancesResponse = await client
                                                                                   .DeleteInstancesAsync(timeSeriesInstancesIds)
                                                                                   .ConfigureAwait(false);

                    // Assert that the response array does not have any error object set
                    deleteInstancesResponse.Value.Should().OnlyContain((errorResult) => errorResult == null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Test clean up failed: {ex.Message}");
                    throw;
                }
            }
        }