Esempio n. 1
0
        public async Task RemoteApplicationGroupList0AG()
        {
            string hostPoolName = "testRemoteApplicationGroupList0AGHP";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();

            AsyncPageable <VirtualApplicationGroupResource> agListPaged = agCollection.GetAllAsync();

            List <VirtualApplicationGroupResource> agList = await agListPaged.ToEnumerableAsync <VirtualApplicationGroupResource>();

            Assert.AreEqual(0, agList.Count);

            await opHostPoolCreate.Value.DeleteAsync(WaitUntil.Completed);
        }
Esempio n. 2
0
        async Task LoadRg(string subcriptionId)
        {
            try
            {
                if (subcriptionId.IsNullOrEmptyExt())
                {
                    return;
                }

                ClearSelection();

                var rgs = await ResourceGroupervice.GetResourceGroups(subcriptionId);

                if (rgs != null)
                {
                    ResourceGroups.AddRange(rgs.Select(a => a.Name));
                    StateHasChanged();
                }
            }
            catch (Exception ex)
            {
                Logger.LogErrorCsro(ex);
                await CsroDialogService.ShowError("Error", $"Detail error: {ex.Message}");
            }
        }
Esempio n. 3
0
        public async Task MainTest()
        {
            string rgName   = SdkContext.RandomResourceName("rgRSMA", 24);
            string diskName = SdkContext.RandomResourceName("disk", 24);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            var disk = new Disks(credentials, subscriptionId);

            disk.Create(diskName, rgName, this.region, 50);

            var resources = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resources), 1);

            disk.Del(diskName, rgName);

            var resourcesAfterDel = await oResourceGroups.GetResources(rgName);

            Assert.LessOrEqual(Formatter.CountPageable(resourcesAfterDel), 0);

            oResourceGroups.Del(rgName);
        }
Esempio n. 4
0
        public async Task MainTest()
        {
            string rgName           = SdkContext.RandomResourceName("rgRSMA", 24);
            string publicIPAddrName = SdkContext.RandomResourceName("pubIP", 24);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            var publicIPAddr = new PublicIPAddresses(credentials, subscriptionId);

            publicIPAddr.Create(publicIPAddrName, rgName, this.region);

            var resources = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resources), 1);

            publicIPAddr.Del(publicIPAddrName, rgName);

            var resourcesAfterDel = await oResourceGroups.GetResources(rgName);

            // there is this thing called, smartDetectorAlertRules/Failure Anomalies
            Assert.LessOrEqual(Formatter.CountPageable(resourcesAfterDel), 1);

            oResourceGroups.Del(rgName);
        }
        public async Task MainTest()
        {
            string rgName             = SdkContext.RandomResourceName("rgRSMA", 24);
            string virtualNetworkName = SdkContext.RandomResourceName("vnet", 24);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            var virtualNetwork = new VirtualNetworks(credentials, subscriptionId);
            await virtualNetwork.Create(virtualNetworkName, rgName, new List <string>() {
                "10.0.0.0/28"
            }, new List <string>() { "1.1.1.1", "1.1.2.4" });

            var resources = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resources), 1);

            await virtualNetwork.Del(virtualNetworkName, rgName);

            var resourcesAfterDel = await oResourceGroups.GetResources(rgName);

            Assert.LessOrEqual(Formatter.CountPageable(resourcesAfterDel), 0);

            oResourceGroups.Del(rgName);
        }
        public async Task MainTest()
        {
            string rgName = SdkContext.RandomResourceName("rgRSMA", 24);
            string networkInterfaceName = SdkContext.RandomResourceName("netinf", 24);
            string ipLabel = SdkContext.RandomResourceName("rgRSMA", 12);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            var networkInferface = new NetworkInterfaces(credentials, subscriptionId);

            networkInferface.Create(networkInterfaceName, rgName, this.region, "10.0.0.0/28", "test");

            var resources = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resources), 2);

            await networkInferface.Del(networkInterfaceName, rgName, true);

            Thread.Sleep(20000);

            var resourcesAfterDel = await oResourceGroups.GetResources(rgName);

            // there is this thing called, smartDetectorAlertRules/Failure Anomalies
            Assert.LessOrEqual(Formatter.CountPageable(resourcesAfterDel), 1);

            oResourceGroups.Del(rgName);
        }
        public async Task MainTest()
        {
            string rgName  = SdkContext.RandomResourceName("rgRSMA", 24);
            string vmName  = SdkContext.RandomResourceName("rgRSMA", 24);
            string ipLabel = SdkContext.RandomResourceName("rgRSMA", 12);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            var vm = new VirtualMachines(credentials, subscriptionId);

            vm.CreateWindowsVM(vmName, rgName, this.region, "10.0.0.0/28", ipLabel, KnownWindowsVirtualMachineImage.WindowsServer2008R2_SP1, "adminUser", "Password@123", VirtualMachineSizeTypes.StandardA0);

            var resources = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resources), 5);

            await vm.Del(vmName, rgName, true);

            var resourcesAfterDel = await oResourceGroups.GetResources(rgName);

            Assert.AreEqual(Formatter.CountPageable(resourcesAfterDel), 0);

            oResourceGroups.Del(rgName);
        }
Esempio n. 8
0
        public async Task RemoteApplicationGroupList(
            int numberOfApplicationGroups)
        {
            string        hostPoolName             = "RemoteApplicationGroupListHP";
            string        applicationGroupName     = "RemoteApplicationGroupListAG";
            List <string> applicationGroupNameList = new List <string>();

            for (int i = 0; i < numberOfApplicationGroups; i++)
            {
                applicationGroupNameList.Add($"{applicationGroupName}{i}");
            }

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();
            VirtualApplicationGroupData       agData       = new VirtualApplicationGroupData(
                DefaultLocation, opHostPoolCreate.Value.Data.Id, ApplicationGroupType.RemoteApp);

            List <Task <ArmOperation <VirtualApplicationGroupResource> > > createTaskList = new List <Task <ArmOperation <VirtualApplicationGroupResource> > >();

            for (int i = 0; i < numberOfApplicationGroups; i++)
            {
                createTaskList.Add(agCollection.CreateOrUpdateAsync(
                                       WaitUntil.Started,
                                       applicationGroupNameList[i],
                                       agData));
            }

            if (createTaskList.Count > 0)
            {
                Task.WaitAll(createTaskList.ToArray());
            }

            AsyncPageable <VirtualApplicationGroupResource> agListPaged = agCollection.GetAllAsync();

            IAsyncEnumerable <Page <VirtualApplicationGroupResource> > f = agListPaged.AsPages();

            var pageEnumerator = f.GetAsyncEnumerator();

            await pageEnumerator.MoveNextAsync();

            Assert.IsNull(pageEnumerator.Current.ContinuationToken);
            Assert.AreEqual(numberOfApplicationGroups, pageEnumerator.Current.Values.Count);
        }
Esempio n. 9
0
        public async Task <CreateResourceGroupCommandResponse> Handle(CreateResourceGroupCommand request, CancellationToken cancellationToken)
        {
            CreateResourceGroupCommandResponse response = new CreateResourceGroupCommandResponse()
            {
                IsSuccessful = false
            };
            ResourceGroups _resourceGroup = new ResourceGroups();

            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //List<Languages> _languages = _ResourceGroupRepository.GetAllLanguages();
                _resourceGroup.IsPublished = true;
                _resourceGroup.Position    = request.Position;
                _resourceGroup.CreatedBy   = "";
                _resourceGroup.CreatedDate = DateTime.Now;
                _resourceGroup.UpdatedBy   = "";
                _resourceGroup.UpdatedDate = DateTime.Now;
                foreach (var langName in request.languageName)
                {
                    var resourceGroupContent = new ResourceGroupContents();
                    resourceGroupContent.GroupName  = langName.Name.Trim();
                    resourceGroupContent.LanguageId = langName.LanguageId;
                    _resourceGroup.ResourceGroupContents.Add(resourceGroupContent);
                }
                _ResourceGroupRepository.Add(_resourceGroup);
                await _ResourceGroupRepository.UnitOfWork
                .SaveEntitiesAsync();

                response.IsSuccessful = true;
                scope.Complete();
            }
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                foreach (var contnet in _resourceGroup.ResourceGroupContents)
                {
                    var eventSourcing = new ResourceGroupCommandEvent()
                    {
                        EventType              = ServiceBusEventType.Create,
                        Discriminator          = Constants.ResourceGroupsDiscriminator,
                        ResourceGroupId        = _resourceGroup.ResourceGroupId,
                        IsPublished            = _resourceGroup.IsPublished,
                        CreatedBy              = _resourceGroup.CreatedBy,
                        CreatedDate            = _resourceGroup.CreatedDate,
                        UpdatedBy              = _resourceGroup.UpdatedBy,
                        UpdatedDate            = _resourceGroup.UpdatedDate,
                        Position               = _resourceGroup.Position,
                        ResourceGroupContentId = contnet.ResourceGroupContentId,
                        LanguageId             = contnet.LanguageId,
                        GroupName              = contnet.GroupName,
                        PartitionKey           = ""
                    };
                    await _Eventcontext.PublishThroughEventBusAsync(eventSourcing);
                }
                scope.Complete();
            }
            return(response);
        }
Esempio n. 10
0
 private void ClearSelection()
 {
     ResourceGroups?.Clear();
     Vms?.Clear();
     Model.ResorceGroup = null;
     Model.VmName       = null;
     Model.VmState      = null;
     StateHasChanged();
 }
Esempio n. 11
0
        public async Task RemoteApplicationGroupList1AG()
        {
            string hostPoolName         = "testRemoteApplicationGroupList1AGHP";
            string applicationGroupName = "testRemoteApplicationGroupList1AGAG";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();
            VirtualApplicationGroupData       agData       = new VirtualApplicationGroupData(DefaultLocation, opHostPoolCreate.Value.Data.Id, ApplicationGroupType.RemoteApp);

            ArmOperation <VirtualApplicationGroupResource> op = await agCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                applicationGroupName,
                agData);

            AsyncPageable <VirtualApplicationGroupResource> agListPaged = agCollection.GetAllAsync();

            IAsyncEnumerable <Page <VirtualApplicationGroupResource> > f = agListPaged.AsPages();

            var pageEnumerator = f.GetAsyncEnumerator();

            var b = await pageEnumerator.MoveNextAsync();

            Assert.IsTrue(b);

            Assert.AreEqual(1, pageEnumerator.Current.Values.Count);

            Assert.AreEqual(null, pageEnumerator.Current.ContinuationToken);

            await pageEnumerator.Current.Values[0].DeleteAsync(WaitUntil.Completed);

            await opHostPoolCreate.Value.DeleteAsync(WaitUntil.Completed);
        }
Esempio n. 12
0
        public async Task End2EndTest()
        {
            string rgName          = SdkContext.RandomResourceName("rgRSMA", 24);
            string blobAccountName = SdkContext.RandomResourceName("rgRSMA", 24);

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);
            Assert.True(oResourceGroups.IsExist(rgName));

            StorageBlobs oStorageBlobs = new StorageBlobs(credentials, subscriptionId, rgName);

            oStorageBlobs.Create(blobAccountName, this.region);

            var resources = await oResourceGroups.GetResources(rgName);

            int count = 0;

            foreach (var resource in resources)
            {
                if (resource.Kind == StorageBlobs.KIND)
                {
                    Assert.True(oStorageBlobs.IsExist(resource.Name));
                }
                else
                {
                    Assert.True(false);
                }
                count++;
            }

            Assert.AreEqual(count, 1);

            oStorageBlobs.Del(blobAccountName);
            Trace.WriteLine("Delete Storage Account");
            Assert.False(oStorageBlobs.IsExist(blobAccountName));

            oResourceGroups.Del(rgName);
            Assert.False(oResourceGroups.IsExist(rgName));
        }
Esempio n. 13
0
        public void SanityTest()
        {
            string rgName          = SdkContext.RandomResourceName("rgRSMA", 24);
            string blobAccountName = SdkContext.RandomResourceName("rgRSMA", 24);
            string containerName   = "dummycontainer";

            ResourceGroups oResourceGroups = new ResourceGroups(this.credentials, this.subscriptionId);

            oResourceGroups.Create(rgName, this.region);

            StorageBlobs oStorageBlobs = new StorageBlobs(credentials, subscriptionId, rgName);

            oStorageBlobs.Create(blobAccountName, this.region);

            Assert.AreEqual(Formatter.CountPageable(oStorageBlobs.GetContainers(blobAccountName)), 0);
            oStorageBlobs.CreateBlobContainer(blobAccountName, containerName);
            Assert.AreEqual(Formatter.CountPageable(oStorageBlobs.GetContainers(blobAccountName)), 1);
            oStorageBlobs.DelBlobContainer(blobAccountName, containerName);
            Assert.AreEqual(Formatter.CountPageable(oStorageBlobs.GetContainers(blobAccountName)), 0);

            // Blob Storage Account shall be deleted once resource group is deleted.
            oResourceGroups.Del(rgName);
        }
Esempio n. 14
0
 protected override void Awake()
 {
     _groups     = new ResourceGroups(this, 1000);
     _loaderPool = new ResourceLoaderPool();
 }
Esempio n. 15
0
        public async Task WebAppSqlConnectionCRUD()
        {
            string resourceGroupName = Recording.GenerateAssetName("SdkRg");
            string webAppName        = Recording.GenerateAssetName("SdkWeb");
            string sqlServerName     = Recording.GenerateAssetName("SdkSql");
            string sqlDatabaseName   = Recording.GenerateAssetName("SdkSql");
            string sqlUserName       = Recording.GenerateAssetName("SdkSql");
            string sqlPassword       = Recording.GenerateAssetName("SdkPa5$");
            string linkerName        = Recording.GenerateAssetName("SdkLinker");

            // create resource group
            await ResourceGroups.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroupName, new Resources.ResourceGroupData(DefaultLocation));

            ResourceGroupResource resourceGroup = await ResourceGroups.GetAsync(resourceGroupName);

            // // create web app
            WebSiteCollection webSites = resourceGroup.GetWebSites();
            await webSites.CreateOrUpdateAsync(WaitUntil.Completed, webAppName, new WebSiteData(DefaultLocation));

            WebSiteResource webapp = await webSites.GetAsync(webAppName);

            // create sql database
            SqlServerCollection sqlServers    = resourceGroup.GetSqlServers();
            SqlServerData       sqlServerData = new SqlServerData(DefaultLocation)
            {
                AdministratorLogin         = sqlUserName,
                AdministratorLoginPassword = sqlPassword,
            };
            await sqlServers.CreateOrUpdateAsync(WaitUntil.Completed, sqlServerName, sqlServerData);

            SqlServerResource sqlServer = await sqlServers.GetAsync(sqlServerName);

            SqlDatabaseCollection sqlDatabases = sqlServer.GetSqlDatabases();
            await sqlDatabases.CreateOrUpdateAsync(WaitUntil.Completed, sqlDatabaseName, new SqlDatabaseData(DefaultLocation));

            SqlDatabaseResource sqlDatabase = await sqlDatabases.GetAsync(sqlDatabaseName);

            // create service linker
            LinkerResourceCollection linkers = webapp.GetLinkerResources();
            var linkerData = new LinkerResourceData
            {
                TargetService = new Models.AzureResource
                {
                    Id = sqlDatabase.Id,
                },
                AuthInfo = new SecretAuthInfo
                {
                    Name       = sqlUserName,
                    SecretInfo = new ValueSecretInfo
                    {
                        Value = sqlPassword,
                    },
                },
                ClientType = ClientType.Dotnet,
            };
            await linkers.CreateOrUpdateAsync(WaitUntil.Completed, linkerName, linkerData);

            // list service linker
            var linkerResources = await linkers.GetAllAsync().ToEnumerableAsync();

            Assert.AreEqual(1, linkerResources.Count);
            Assert.AreEqual(linkerName, linkerResources[0].Data.Name);

            // get service linker
            LinkerResource linker = await linkers.GetAsync(linkerName);

            Assert.IsTrue(linker.Id.ToString().StartsWith(webapp.Id.ToString(), StringComparison.InvariantCultureIgnoreCase));
            Assert.AreEqual(sqlDatabase.Id.ToString(), (linker.Data.TargetService as AzureResource).Id);
            Assert.AreEqual(AuthType.Secret, linker.Data.AuthInfo.AuthType);

            // get service linker configurations
            SourceConfigurationResult configurations = await linker.GetConfigurationsAsync();

            foreach (var configuration in configurations.Configurations)
            {
                Assert.IsNotNull(configuration.Name);
                Assert.IsNotNull(configuration.Value);
            }

            // delete service linker
            var operation = await linker.DeleteAsync(WaitUntil.Completed);

            Assert.IsTrue(operation.HasCompleted);
        }
Esempio n. 16
0
 public void DeleteResourceGroup(ResourceGroups resourceGroup)
 {
     _context.ResourceGroups.Remove(resourceGroup);
 }
Esempio n. 17
0
 public ResourceGroups UnPublishResourceGroups(ResourceGroups _ResourceGroup)
 {
     return(_context.ResourceGroups.Add(_ResourceGroup).Entity);
 }
Esempio n. 18
0
        public static Dictionary <String, Object> GetHosts(String accessToken, String subscriptionId = null)
        {
            //get the subs
            List <String> subList = new List <string>();

            if (subscriptionId != null)
            {
                subList.Add(subscriptionId);
            }
            else
            {
                Subscriptions subscriptions = ListSubscriptions.GetSubscriptions();
                foreach (var sub in subscriptions.value)
                {
                    if (sub.id.Contains(SubscriptionFilter))
                    {
                        subList.Add(sub.subscriptionId);
                    }
                }
            }

            var ansibleHostList     = new Dictionary <String, Object>();
            var ansibleHostVarsList = new Dictionary <String, Object>();


            accessToken = Adal.AccessToken();
            string authToken = "Bearer" + " " + accessToken;
            var    client    = new WebClient();

            client.Headers.Add("Authorization", authToken);
            client.Headers.Add("Content-Type", "application/json");

            foreach (var subId in subList)
            {
                Uri    resourceGroupsUri = new Uri(String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups?api-version=2015-01-01", subId));
                String text = "";


                text = client.DownloadString(resourceGroupsUri);
                ResourceGroups       rgList = Newtonsoft.Json.JsonConvert.DeserializeObject <ResourceGroups>(text);
                List <ResourceGroup> filteredResourceGroups = new List <ResourceGroup>();
                foreach (var rg in rgList.value)
                {
                    if (ResourceGroupFilter == "*")
                    {
                        filteredResourceGroups.Add(rg);
                    }
                    else if (rg.name.ToLower().Contains(ResourceGroupFilter.ToLower()))
                    {
                        filteredResourceGroups.Add(rg);
                    }
                }


                foreach (ResourceGroup rg in filteredResourceGroups)
                {
                    //get each host
                    String rgId   = rg.id;
                    String rgName = rg.name;

                    //remove Prod/Test/Dev from rg name
                    if (RemoveStageFromRgName)
                    {
                        if (rgName.ToLower().StartsWith("prod."))
                        {
                            rgName = rgName.Remove(0, 5);
                        }
                        else if (rgName.ToLower().StartsWith("test."))
                        {
                            rgName = rgName.Remove(0, 5);
                        }
                        else if (rgName.ToLower().StartsWith("dev."))
                        {
                            rgName = rgName.Remove(0, 4);
                        }

                        else if (rgName.ToLower().StartsWith("uat."))
                        {
                            rgName = rgName.Remove(0, 4);
                        }
                    }


                    if (ResourceGroupCasing != "")
                    {
                        if (ResourceGroupCasing.ToLower() == "lowercase")
                        {
                            rgName = rgName.ToLower();
                        }
                    }



                    String     rgComputeUrl = String.Format("https://management.azure.com{0}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", rgId);
                    String     rgVmsText    = client.DownloadString(rgComputeUrl);
                    ComputeVms rgCompVms    = JsonConvert.DeserializeObject <ComputeVms>(rgVmsText);
                    if (rgCompVms.value.Count != 0)
                    {
                        //resource group has vms. Fill the thing
                        List <Object> hostList = new List <Object>();
                        foreach (var vm in rgCompVms.value)
                        {
                            var  tagDict           = new Dictionary <String, Object>();
                            bool VerifyPoweredOnVM = true;
                            if (ReturnOnlyPoweredOnVms.ToLower() == "true")
                            {
                                VerifyPoweredOnVM = GetVmPowerStatus(accessToken, vm);
                            }

                            var simplifiedNic = GetNicDetails(accessToken, vm);
                            vm.simplifiedNicDetails = simplifiedNic;


                            if (HostCasingSetting == "UpperCase")
                            {
                                vm.name = vm.name.ToUpper();
                            }

                            if (HostCasingSetting == "LowerCase")
                            {
                                vm.name = vm.name.ToLower();
                            }

                            string vmname = vm.name;



                            if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleDomainSuffix")))
                            {
                                vmname = vm.name + "." + vm.tags["AnsibleDomainSuffix"];
                            }
                            else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleDomainSuffix")))
                            {
                                vmname = vm.name + "." + rg.tags["AnsibleDomainSuffix"];
                            }
                            String ansibleReturnType = null;
                            if ((vm.tags != null) && (vm.tags.ContainsKey("AnsibleReturn")))
                            {
                                ansibleReturnType = vm.tags["AnsibleReturn"];
                            }
                            else if ((rg.tags != null) && (rg.tags.ContainsKey("AnsibleReturn")))
                            {
                                ansibleReturnType = rg.tags["AnsibleReturn"];
                            }

                            //add location thing if specified
                            if (LocationTag != "" && LocationTagName != "")
                            {
                                String Location = LocationTag.Replace("%location%", vm.location);
                                tagDict.Add(LocationTagName, Location);
                            }

                            //If ansiblereturn is set, figure out what to return
                            if (ansibleReturnType != null)
                            {
                                if ((ansibleReturnType.ToLower() == "privateipaddress") && (vm.simplifiedNicDetails.InternalIpAddress != null))
                                {
                                    vmname = vm.simplifiedNicDetails.InternalIpAddress;
                                }
                                else if ((ansibleReturnType.ToLower() == "publicipaddress") && (vm.simplifiedNicDetails.PublicIpAddress != null))
                                {
                                    vmname = vm.simplifiedNicDetails.PublicIpAddress;
                                }
                                else if ((ansibleReturnType.ToLower() == "publichostname") && (vm.simplifiedNicDetails.PublicHostName != null))
                                {
                                    vmname = vm.simplifiedNicDetails.PublicHostName;
                                }
                                else if ((ansibleReturnType.ToLower() == "privateipaddress_asansiblehost") && (vm.simplifiedNicDetails.InternalIpAddress != null))
                                {
                                    tagDict.Add("ansible_host", vm.simplifiedNicDetails.InternalIpAddress);
                                }
                                else if ((ansibleReturnType.ToLower() == "publicipaddress_asansiblehost") && (vm.simplifiedNicDetails.PublicIpAddress != null))
                                {
                                    tagDict.Add("ansible_host", vmname = vm.simplifiedNicDetails.PublicIpAddress);
                                }
                                else if ((ansibleReturnType.ToLower() == "publichostname_asansiblehost") && (vm.simplifiedNicDetails.PublicHostName != null))
                                {
                                    tagDict.Add("ansible_host", vmname = vmname = vm.simplifiedNicDetails.PublicHostName);
                                }
                            }

                            //vmname is now either computername, computername+domain, one ip address or public fqdn


                            if (VerifyPoweredOnVM == true)
                            {
                                hostList.Add(vmname);
                                //check if we have hostsvars to add to meta
                                if ((vm.tags != null) && (vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0))
                                {
                                    foreach (var tag in vm.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")))
                                    {
                                        tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value);
                                    }
                                }
                            }

                            if (tagDict.Count > 0)
                            {
                                //add tags if any
                                ansibleHostVarsList.Add(vmname, tagDict);
                            }
                        }
                        //Add the rg to the main obj
                        var rgValueList = new Dictionary <String, Object>();
                        rgValueList.Add("hosts", hostList);

                        //add vars to the main object if they exists
                        if ((rg.tags != null) && (rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")).Count() > 0))
                        {
                            var tagDict = new Dictionary <String, Object>();
                            foreach (var tag in rg.tags.Where(t => t.Key.ToLower().StartsWith("ansible__")))
                            {
                                tagDict.Add(tag.Key.ToLower().Replace("ansible__", ""), tag.Value);
                            }
                            rgValueList.Add("vars", tagDict);
                        }


                        ansibleHostList.Add(rgName, rgValueList);
                    }
                }
            }

            //Add the _meta thing to the result output
            var metaDict = new Dictionary <String, Object>();

            metaDict.Add("hostvars", ansibleHostVarsList);
            ansibleHostList.Add("_meta", metaDict);
            return(ansibleHostList);
        }
Esempio n. 19
0
        public async Task RemoteApplicationCrud()
        {
            string hostPoolName         = "testRemoteApplicationCrudHP";
            string applicationGroupName = "testRemoteApplicationCrudAG";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();
            VirtualApplicationGroupData       agData       = new VirtualApplicationGroupData(DefaultLocation, opHostPoolCreate.Value.Data.Id, ApplicationGroupType.RemoteApp);

            ArmOperation <VirtualApplicationGroupResource> opApplicationGroupCreate = await agCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                applicationGroupName,
                agData);

            Assert.IsNotNull(opApplicationGroupCreate);
            Assert.IsTrue(opApplicationGroupCreate.HasCompleted);
            Assert.AreEqual(opApplicationGroupCreate.Value.Data.Name, applicationGroupName);

            VirtualApplicationGroupResource railApplicationGroup = opApplicationGroupCreate.Value;

            VirtualApplicationCollection railApplications = railApplicationGroup.GetVirtualApplications();

            AsyncPageable <VirtualApplicationResource> applications = railApplications.GetAllAsync();

            Assert.IsNotNull(applications);

            VirtualApplicationData applicationData = new VirtualApplicationData(CommandLineSetting.DoNotAllow);

            applicationData.FilePath     = "c:\\notepad.exe";
            applicationData.IconPath     = "c:\\notepad.exe";
            applicationData.Description  = "Note Pad";
            applicationData.ShowInPortal = true;

            ArmOperation <VirtualApplicationResource> opCreate = await railApplications.CreateOrUpdateAsync(WaitUntil.Completed, "notepad", applicationData);

            Assert.IsNotNull(opCreate);

            Assert.AreEqual("testRemoteApplicationCrudAG/notepad", opCreate.Value.Data.Name);
            Assert.AreEqual("Note Pad", opCreate.Value.Data.Description);

            Response <VirtualApplicationResource> opGet = await railApplications.GetAsync("notepad");

            Assert.IsNotNull(opGet);

            Assert.AreEqual("c:\\notepad.exe", opGet.Value.Data.FilePath);
            Assert.AreEqual("c:\\notepad.exe", opGet.Value.Data.IconPath);
            Assert.AreEqual("Note Pad", opGet.Value.Data.Description);

            applicationData.Description = "NotePad";

            ArmOperation <VirtualApplicationResource> opUpdate = await railApplications.CreateOrUpdateAsync(WaitUntil.Completed, "notepad", applicationData);

            Assert.IsNotNull(opUpdate);

            Assert.AreEqual("testRemoteApplicationCrudAG/notepad", opUpdate.Value.Data.Name);
            Assert.AreEqual("NotePad", opUpdate.Value.Data.Description);

            ArmOperation opDelete = await opUpdate.Value.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(opDelete);

            Assert.AreEqual(200, opDelete.GetRawResponse().Status);

            opDelete = await opUpdate.Value.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(opDelete);

            Assert.AreEqual(204, opDelete.GetRawResponse().Status);

            try
            {
                await railApplications.GetAsync("notepad");
            }
            catch (RequestFailedException ex)
            {
                Assert.AreEqual(404, ex.Status);
            }

            await opApplicationGroupCreate.Value.DeleteAsync(WaitUntil.Completed);

            await opHostPoolCreate.Value.DeleteAsync(WaitUntil.Completed);
        }
Esempio n. 20
0
        /// <summary>
        /// project new state onto the current instance
        /// </summary>
        /// <param name="newState">new intended state</param>
        /// <param name="environments">list of environments to provision to</param>
        public void Update(Tenant newState, IEnumerable <DeploymentEnvironment> environments)
        {
            if (newState == null)
            {
                return;
            }

            Name       = newState.Name;
            TenantSize = newState.TenantSize;

            var newStateForks = newState.SourceRepos.Select(r => new SourceCodeRepository(r.SourceRepositoryName, Code, r.ProjectType, r.Fork)).ToList();

            //update forks and build definitions (1:1) - additions and removals
            newStateForks
            .Except(SourceRepos, ForkEqComparer)
            .ToList()
            .ForEach(f =>
            {
                f.TenantCode = Code;
                SourceRepos.Add(f);
                var bd = new VstsBuildDefinition(f, Code);
                BuildDefinitions.Add(bd);

                //for canary, no PROD env in non prod release pipeline
                var standardPipeline = new VstsReleaseDefinition(bd, Code, TenantSize, false)
                {
                    SkipEnvironments = !f.Fork ? new[] { DeploymentEnvironment.Prod } : new DeploymentEnvironment[] { }
                };
                ReleaseDefinitions.Add(standardPipeline);

                if (f.Fork)
                {
                    return;
                }

                //also initiate ring pipeline (if not fork)
                var ringPipeline = new VstsReleaseDefinition(bd, Code, TenantSize, true);
                ReleaseDefinitions.Add(ringPipeline);
            });

            SourceRepos
            .Except(newStateForks, ForkEqComparer)
            .ToList()
            .ForEach(f =>
            {
                f.State  = EntityStateEnum.ToBeDeleted;
                var bd   = BuildDefinitions.Single(b => Equals(b.SourceCode, f));
                bd.State = EntityStateEnum.ToBeDeleted;
                bd.ReleaseDefinitions.ForEach(d => d.State = EntityStateEnum.ToBeDeleted);
            });

            var environmentList = environments.ToList();

            if (!ResourceGroups.Any())
            {
                foreach (var environmentName in environmentList)
                {
                    // TODO: validate that the list of resource groups and their names
                    ResourceGroups.Add(new ResourceGroup(Code, environmentName, $"checkout-{Code}-{environmentName}"));
                }
            }

            if (!ManagedIdentities.Any())
            {
                foreach (var environmentName in environmentList)
                {
                    // TODO: validate the list of created managed identities and their names
                    ManagedIdentities.Add(new ManagedIdentity
                    {
                        TenantCode        = Code,
                        Environment       = environmentName,
                        IdentityName      = $"{Code}-{environmentName}",
                        ResourceGroupName = $"checkout-{Code}-{environmentName}",
                    });
                }
            }
        }
        public async Task <UpdateArticleCommandResponse> Handle(UpdateArticleCommand request, CancellationToken cancellationToken)
        {
            UpdateArticleCommandResponse response = new UpdateArticleCommandResponse()
            {
                IsSuccessful = false
            };

            try
            {
                Disclaimers     DisclaimersDetails    = new Disclaimers();
                ResourceGroups  ResourceGroupsDetails = new ResourceGroups();
                Provinces       ProvincesDetails      = new Provinces();
                List <TaxTags>  taxTagsDetails        = new List <TaxTags>();
                List <Articles> articlesDetails       = new List <Articles>();
                Articles        _article = _ArticleRepository.getArticleCompleteDataById(new List <int> {
                    request.ArticleID
                })[0];
                var contentToDelete = new List <int>();
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    _article.UpdatedBy        = request.UpdatedBy;
                    _article.UpdatedDate      = DateTime.UtcNow;
                    _article.Author           = request.Author;
                    _article.DisclaimerId     = request.DisclaimerId;
                    _article.ResourceGroupId  = request.ResourceGroupId > 0 ? request.ResourceGroupId : (int?)null;
                    _article.ResourcePosition = request.ResourcePosition > 0 ? request.ResourcePosition : (int?)null;

                    if (request.PublishedDate != null)
                    {
                        _article.PublishedDate = request.PublishedDate.Value;
                    }
                    _article.SubType     = request.SubType;
                    _article.State       = request.State;
                    _article.ProvinceId  = request.ProvinceId;
                    _article.IsPublished = request.IsPublished;//= Action == "Publish";
                    //update article content
                    //delete removed languages, update existing, add new languages
                    foreach (var content in request.ArticleContent)
                    {
                        var artContent =
                            _article.ArticleContents.FirstOrDefault(v => v.LanguageId == content.LanguageId);
                        if (artContent == null)
                        {
                            var newContent = new ArticleContents
                            {
                                Content    = content.Content,
                                LanguageId = content.LanguageId,
                                TeaserText = content.TeaserText,
                                Title      = content.Title
                            };

                            //content.ArticleId = articleobject.ArticleId;
                            _article.ArticleContents.Add(newContent);
                        }
                        else
                        {
                            artContent.Content    = content.Content;
                            artContent.LanguageId = content.LanguageId;
                            artContent.TeaserText = content.TeaserText;
                            artContent.Title      = content.Title;
                            _ArticleRepository.Update <ArticleContents>(artContent);
                        }
                    }
                    var articleContentIds = _article.ArticleContents.Select(c => c.LanguageId).ToList();
                    var articleDtoCids    = request.ArticleContent.Select(c => c.LanguageId).ToList();
                    var removedContents   = articleContentIds.Except(articleDtoCids);
                    _article.ArticleContents.Where(a => removedContents.Contains(a.LanguageId)).ToList().ForEach(removed =>
                    {
                        _ArticleRepository.Delete <ArticleContents>(removed);
                        _article.ArticleContents.Remove(removed);
                        contentToDelete.Add((int)removed.LanguageId);
                    });

                    // Update Related Countries
                    foreach (var country in request.RelatedCountries)
                    {
                        var articleCountry =
                            _article.ArticleRelatedCountries
                            .FirstOrDefault(c => c.CountryId == country);
                        if (articleCountry != null)
                        {
                            continue;
                        }
                        var newCountry = _ArticleRepository.getCountryById(country);
                        _article.ArticleRelatedCountries.Add(new ArticleRelatedCountries {
                            Country = newCountry, CountryId = newCountry.CountryId
                        });
                    }
                    var articleCountries = _article.ArticleRelatedCountries.Select(c => c.CountryId).ToList();
                    var dtoCountries     = request.RelatedCountries;
                    var removedCountries = articleCountries.Except(dtoCountries);
                    _article.ArticleRelatedCountries.Where(a => removedCountries.Contains(a.CountryId))
                    .ToList()
                    .ForEach(removed => { _article.ArticleRelatedCountries.Remove(removed); });

                    // Update Related Country Groups
                    foreach (var countryGroup in request.RelatedCountryGroups)
                    {
                        var articleCountryGroup =
                            _article.ArticleRelatedCountryGroups
                            .FirstOrDefault(c => c.CountryGroupId == countryGroup);
                        if (articleCountryGroup != null)
                        {
                            continue;
                        }
                        var newCountryGroup = _ArticleRepository.getCountryGroupById(countryGroup);
                        _article.ArticleRelatedCountryGroups.Add(new ArticleRelatedCountryGroups {
                            CountryGroup = newCountryGroup, CountryGroupId = newCountryGroup.CountryGroupId
                        });
                    }
                    var articleCountryGroups = _article.ArticleRelatedCountryGroups.Select(c => c.CountryGroupId).ToList();
                    var dtoCountryGroups     = request.RelatedCountryGroups;
                    var removedCountryGroups = articleCountryGroups.Except(dtoCountryGroups);
                    _article.ArticleRelatedCountryGroups.Where(a => removedCountryGroups.Contains(a.CountryGroupId))
                    .ToList()
                    .ForEach(removed => { _article.ArticleRelatedCountryGroups.Remove(removed); });

                    //update related articles
                    if (request.RelatedArticles != null)
                    {
                        var relatedArticles    = _article.RelatedArticlesArticle.Select(c => c.ArticleId).ToList();
                        var dtoRelatedArticles = request.RelatedArticles;

                        var addRelatedArticles = dtoRelatedArticles.Except(relatedArticles);
                        var newRelatedArticles = _ArticleRepository.getArticlesListById(addRelatedArticles.ToList());// context.Articles.Where(a => addRelatedArticles.Contains(a.ArticleId));
                        newRelatedArticles.ForEach(a =>
                        {
                            _article.RelatedArticlesArticle.Add(new RelatedArticles {
                                Article = a, RelatedArticleId = a.ArticleId
                            });
                            //Reverse relation
                            //if (!a.RelatedArticlesArticle.Any(r => r.ArticleId == _article.ArticleId))
                            //{
                            //    a.RelatedArticlesArticle.Add(new RelatedArticles { Article = _article, RelatedArticleId = _article.ArticleId });
                            //}
                        });

                        var removedRelatedArticles = relatedArticles.Except(dtoRelatedArticles);
                        _article.RelatedArticlesArticle.Where(a => removedRelatedArticles.Contains(a.ArticleId))
                        .ToList()
                        .ForEach(removed =>
                        {
                            _article.RelatedArticlesArticle.Remove(removed);
                        });
                    }

                    // update related resources
                    if (request.RelatedResources != null)
                    {
                        foreach (var rResource in request.RelatedResources)
                        {
                            var relatedRes =
                                _article.RelatedResourcesArticle.FirstOrDefault(c => c.RelatedArticleId == rResource);
                            if (relatedRes != null)
                            {
                                continue;
                            }
                            var newRelatedResource = _ArticleRepository.getArticleDataById(rResource);
                            _article.RelatedResourcesArticle.Add(new RelatedResources {
                                Article = newRelatedResource, RelatedArticleId = newRelatedResource.ArticleId
                            });
                        }
                        var relatedResources        = _article.RelatedResourcesArticle.Select(c => c.RelatedArticleId).ToList();
                        var dtoRelatedResources     = request.RelatedResources;
                        var removedRelatedResources = relatedResources.Except(dtoRelatedResources);
                        _article.RelatedResourcesArticle.Where(a => removedRelatedResources.Contains(a.RelatedArticleId))
                        .ToList()
                        .ForEach(removed => { _article.RelatedResourcesArticle.Remove(removed); });
                    }

                    //update related tags
                    if (request.RelatedTaxTags != null)
                    {
                        foreach (var rTag in request.RelatedTaxTags)
                        {
                            var relatedTag =
                                _article.ArticleRelatedTaxTags.FirstOrDefault(c => c.TaxTagId == rTag);
                            if (relatedTag == null)
                            {
                                var newTag = _ArticleRepository.getTaxTagsById(rTag);
                                _article.ArticleRelatedTaxTags.Add(new ArticleRelatedTaxTags {
                                    TaxTag = newTag, TaxTagId = newTag.TaxTagId
                                });
                            }
                        }
                        var relatedTags = _article.ArticleRelatedTaxTags.Select(c => c.TaxTagId).ToList();
                        var dtoTags     = request.RelatedTaxTags;
                        var removedTags = relatedTags.Except(dtoTags);
                        _article.ArticleRelatedTaxTags.Where(a => removedTags.Contains(a.TaxTagId))
                        .ToList()
                        .ForEach(removed => { _article.ArticleRelatedTaxTags.Remove(removed); });
                    }

                    //update related contacts
                    if (request.RelatedContacts != null)
                    {
                        foreach (var dtoContact in request.RelatedContacts)
                        {
                            var relatedContact = _article.ArticleRelatedContacts.FirstOrDefault(c => c.ContactId == dtoContact);
                            if (relatedContact == null)
                            {
                                var newContact = _ArticleRepository.getContactsById(dtoContact);// context.Contacts.FirstOrDefault(c => c.ContactId == dtoContact.ContactId);
                                _article.ArticleRelatedContacts.Add(new ArticleRelatedContacts {
                                    Contact = newContact, ContactId = newContact.ContactId
                                });
                            }
                        }
                        var relatedContacts = _article.ArticleRelatedContacts.Select(c => c.ContactId).ToList();
                        var dtoContacts     = request.RelatedContacts;
                        var removeContacts  = relatedContacts.Except(dtoContacts);
                        _article.ArticleRelatedContacts.Where(a => removeContacts.Contains(a.ContactId))
                        .ToList()
                        .ForEach(removeContact => _article.ArticleRelatedContacts.Remove(removeContact));
                    }

                    //update image
                    _article.ImageId = request.ImageId;
                    //Push logic needs to be implemented
                    int userCount = _ArticleRepository.SendNotificationsForArticle <UpdateArticleCommand>(request);
                    if (userCount > 0)
                    {
                        _article.NotificationSentDate = DateTime.Now;
                    }
                    await _ArticleRepository.UnitOfWork
                    .SaveEntitiesAsync();

                    taxTagsDetails        = _ArticleRepository.getTaxTagsDetailsByIds(_article.ArticleRelatedTaxTags.Select(s => s.TaxTagId).ToList());
                    articlesDetails       = _ArticleRepository.getArticleCompleteDataById(_article.RelatedArticlesArticle.Select(s => s.RelatedArticleId).ToList());
                    ResourceGroupsDetails = _article.ResourceGroupId == null ? null : _ArticleRepository.getResourceGroupById(int.Parse(_article.ResourceGroupId.ToString()));
                    ProvincesDetails      = _article.ProvinceId == null ? null : _ArticleRepository.getProvisionsById(int.Parse(_article.ProvinceId.ToString()));
                    DisclaimersDetails    = _article.DisclaimerId == null ? null : _ArticleRepository.getDisclaimerById(int.Parse(_article.DisclaimerId.ToString()));
                    response.IsSuccessful = true;
                    scope.Complete();
                }
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var articleDocs = _context.GetAll(Constants.ArticlesDiscriminator);
                    foreach (var content in _article.ArticleContents)
                    {
                        foreach (var article in articleDocs.Where(ad => ad.GetPropertyValue <int>("LanguageId") == content.LanguageId))
                        {
                            foreach (var relatedArticles in article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles"))
                            {
                                if (relatedArticles.ArticleId == _article.ArticleId)
                                {
                                    List <RelatedArticlesSchema> relatedArticleSchema = new List <RelatedArticlesSchema>();
                                    relatedArticleSchema = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles");

                                    var index = relatedArticleSchema.IndexOf(relatedArticleSchema.Where(i => i.ArticleId == _article.ArticleId).First());
                                    if (index != -1)
                                    {
                                        relatedArticleSchema[index] = new RelatedArticlesSchema {
                                            ArticleId = _article.ArticleId, Title = content.Title == null ? "" : content.Title, PublishedDate = _article.PublishedDate == null ? "" : _article.PublishedDate.ToString(), CountryId = _article.ArticleRelatedCountries.Select(s => new RelatedEntityId {
                                                IdVal = s.CountryId
                                            }).ToList()
                                        }
                                    }
                                    ;
                                    var eventSourcingRelated = new ArticleCommandEvent()
                                    {
                                        id = article != null?article.GetPropertyValue <Guid>("id") : Guid.NewGuid(),
                                                 EventType             = ServiceBusEventType.Update,
                                                 ArticleId             = article.GetPropertyValue <int>("ArticleId"),
                                                 PublishedDate         = article.GetPropertyValue <string>("PublishedDate"),
                                                 Author                = article.GetPropertyValue <string>("author"),
                                                 ImageId               = article.GetPropertyValue <int>("ImageId"),
                                                 State                 = article.GetPropertyValue <string>("State"),
                                                 Type                  = article.GetPropertyValue <int>("Type"),
                                                 SubType               = article.GetPropertyValue <int>("SubType"),
                                                 ResourcePosition      = article.GetPropertyValue <int>("ResourcePosition"),
                                                 Disclaimer            = article.GetPropertyValue <DisclamersSchema>("Disclaimer"),
                                                 ResourceGroup         = article.GetPropertyValue <ResourceGroupsSchema>("ResourceGroup"),
                                                 IsPublished           = article.GetPropertyValue <bool>("IsPublished"),
                                                 CreatedDate           = article.GetPropertyValue <string>("CreatedDate"),
                                                 CreatedBy             = article.GetPropertyValue <string>("CreatedBy"),
                                                 UpdatedDate           = article.GetPropertyValue <string>("UpdatedDate"),
                                                 UpdatedBy             = article.GetPropertyValue <string>("UpdatedBy"),
                                                 NotificationSentDate  = article.GetPropertyValue <string>("NotificationSentDate"),
                                                 Provinces             = article.GetPropertyValue <ProvinceSchema>("Provisions"),
                                                 ArticleContentId      = article.GetPropertyValue <int>("ArticleContentId"),
                                                 LanguageId            = article.GetPropertyValue <int>("LanguageId"),
                                                 Title                 = article.GetPropertyValue <string>("Title"),
                                                 TitleInEnglishDefault = article.GetPropertyValue <string>("TitleInEnglishDefault"),
                                                 TeaserText            = article.GetPropertyValue <string>("TeaserText"),
                                                 Content               = article.GetPropertyValue <string>("Content"),
                                                 RelatedContacts       = article.GetPropertyValue <List <RelatedEntityId> >("RelatedContacts"),
                                                 RelatedCountries      = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountries"),
                                                 RelatedCountryGroups  = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountryGroups"),
                                                 RelatedTaxTags        = article.GetPropertyValue <List <RelatedTaxTagsSchema> >("RelatedTaxTags"),
                                                 RelatedArticles       = relatedArticleSchema,
                                                 RelatedResources      = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedResources"),
                                                 Discriminator         = article.GetPropertyValue <string>("Discriminator"),
                                                 PartitionKey          = ""
                                    };
                                    await _Eventcontext.PublishThroughEventBusAsync(eventSourcingRelated);
                                }
                            }
                        }
                        var DisclaimerLanguageId    = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37;
                        var ResourceGroupLanguageId = ResourceGroupsDetails.ResourceGroupContents.Where(d => d.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37;
                        var ProvisionsLanguageId    = ProvincesDetails.ProvinceContents.Where(d => d.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37;
                        var doc = articleDocs.FirstOrDefault(d => d.GetPropertyValue <int>("ArticleId") == _article.ArticleId &&
                                                             d.GetPropertyValue <int?>("LanguageId") == content.LanguageId);
                        var eventSourcing = new ArticleCommandEvent()
                        {
                            id = doc != null?doc.GetPropertyValue <Guid>("id") : Guid.NewGuid(),
                                     EventType        = doc != null ? ServiceBusEventType.Update : ServiceBusEventType.Create,
                                     ArticleId        = _article.ArticleId,
                                     PublishedDate    = _article.PublishedDate == null ? "" : _article.PublishedDate.ToString(),
                                     Author           = _article.Author == null ? "" : _article.Author,
                                     ImageId          = _article.ImageId == null ? -1 : _article.ImageId,
                                     State            = _article.State == null ? "" : _article.State,
                                     Type             = _article.Type == null ? -1 : _article.Type,
                                     SubType          = _article.SubType == null ? -1 : _article.SubType,
                                     ResourcePosition = _article.ResourcePosition == null ? -1 : _article.ResourcePosition,
                                     Disclaimer       = new DisclamersSchema
                            {
                                DisclaimerId = int.Parse(_article.DisclaimerId == null?"-1": _article.DisclaimerId.ToString()), ProviderName = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == DisclaimerLanguageId).Select(ds => ds.ProviderName == null ? "" : ds.ProviderName).FirstOrDefault(), ProviderTerms = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == DisclaimerLanguageId).Select(ds => ds.ProviderTerms == null ? "" : ds.ProviderTerms).FirstOrDefault()
                            },
                            ResourceGroup = new ResourceGroupsSchema {
                                ResourceGroupId = int.Parse(_article.ResourceGroupId == null ? "-1" : _article.ResourceGroupId.ToString()), GroupName = ResourceGroupsDetails.ResourceGroupContents.Where(d => d.LanguageId == ResourceGroupLanguageId).Select(ds => ds.GroupName == null ? "" : ds.GroupName).FirstOrDefault(), Position = ResourceGroupsDetails.Position == null ? -1 : ResourceGroupsDetails.Position
                            },
                            IsPublished          = _article.IsPublished == null ? false : _article.IsPublished,
                            CreatedDate          = _article.CreatedDate == null ? "" : _article.CreatedDate.ToString(),
                            CreatedBy            = _article.CreatedBy == null ? "" : _article.CreatedBy,
                            UpdatedDate          = _article.UpdatedDate == null ? "" : _article.UpdatedDate.ToString(),
                            UpdatedBy            = _article.UpdatedBy == null ? "" : _article.UpdatedBy,
                            NotificationSentDate = _article.NotificationSentDate == null ? "" : _article.NotificationSentDate.ToString(),
                            Provinces            = new ProvinceSchema {
                                ProvinceId = int.Parse(_article.ProvinceId.ToString()), DisplayName = ProvincesDetails.ProvinceContents.Where(d => d.LanguageId == ProvisionsLanguageId).Select(ds => ds.DisplayName == null ? "" : ds.DisplayName).FirstOrDefault()
                            },
                            ArticleContentId      = content.ArticleContentId == null ? -1 : content.ArticleContentId,
                            LanguageId            = content.LanguageId == null ? -1 : content.LanguageId,
                            Title                 = content.Title == null ? "" : content.Title,
                            TitleInEnglishDefault = _article.ArticleContents.Where(l => l.LanguageId == 37 && l.ArticleId == content.ArticleId).Select(s => s.Title == null ? "" : s.Title).FirstOrDefault(),
                            TeaserText            = content.TeaserText == null ? "" : content.TeaserText,
                            Content               = content.Content == null ? "" : content.Content,
                            RelatedContacts       = _article.ArticleRelatedContacts.Select(s => new RelatedEntityId {
                                IdVal = s.ContactId
                            }).ToList(),
                            RelatedCountries = _article.ArticleRelatedCountries.Select(s => new RelatedEntityId {
                                IdVal = s.CountryId
                            }).ToList(),
                            RelatedCountryGroups = _article.ArticleRelatedCountryGroups.Select(s => new RelatedEntityId {
                                IdVal = s.CountryGroupId
                            }).ToList(),
                            RelatedTaxTags   = _article.ArticleRelatedTaxTags.Select(s => { var RelatedtaxTagLanguageId = taxTagsDetails.Where(td => td.TaxTagId == s.TaxTagId).FirstOrDefault().TaxTagContents.Where(ttc => ttc.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37; return(new RelatedTaxTagsSchema {
                                    TaxTagId = s.TaxTagId, DisplayName = taxTagsDetails.Where(td => td.TaxTagId == s.TaxTagId).FirstOrDefault().TaxTagContents.Where(ttc => ttc.LanguageId == RelatedtaxTagLanguageId).Select(ttcs => ttcs.DisplayName == null ? "" : ttcs.DisplayName).FirstOrDefault()
                                }); }).ToList(),
                            RelatedArticles  = _article.RelatedArticlesArticle.Select(s => { var RelatedArticleLanguageId = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37; return(new RelatedArticlesSchema {
                                    ArticleId = s.RelatedArticleId, PublishedDate = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).Select(v => v.PublishedDate == null ? "" : v.PublishedDate.ToString()).FirstOrDefault().ToString(), Title = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == RelatedArticleLanguageId).Select(v => v.Title == null ? "" : v.Title).FirstOrDefault().ToString(), CountryId = articlesDetails.Where(ad => ad.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleRelatedCountries.Select(arc => new RelatedEntityId {
                                        IdVal = arc.CountryId
                                    }).ToList()
                                }); }).ToList(),
                            RelatedResources = _article.RelatedResourcesArticle.Select(s => { var RelatedResourceLanguageId = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == content.LanguageId).Count() > 0 ? content.LanguageId : 37; return(new RelatedArticlesSchema {
                                    ArticleId = s.RelatedArticleId, PublishedDate = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).Select(v => v.PublishedDate == null ? "" : v.PublishedDate.ToString()).FirstOrDefault().ToString(), Title = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == RelatedResourceLanguageId).Select(v => v.Title == null ? "" : v.Title).FirstOrDefault().ToString(), CountryId = articlesDetails.Where(ad => ad.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleRelatedCountries.Select(arc => new RelatedEntityId {
                                        IdVal = arc.CountryId
                                    }).ToList()
                                }); }).ToList(),
                            Discriminator    = Constants.ArticlesDiscriminator,
                            PartitionKey     = ""
                        };
                        await _Eventcontext.PublishThroughEventBusAsync(eventSourcing);
                    }
                    foreach (int i in contentToDelete)
                    {
                        foreach (var article in articleDocs.Where(ad => ad.GetPropertyValue <int>("LanguageId") == i))
                        {
                            foreach (var relatedArticles in article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles"))
                            {
                                if (relatedArticles.ArticleId == _article.ArticleId)
                                {
                                    var titleInEnglish = articleDocs.Where(ad => ad.GetPropertyValue <int>("ArticleId") == _article.ArticleId && ad.GetPropertyValue <int>("LanguageId") == 37).Select(ads => ads.GetPropertyValue <string>("Title")).FirstOrDefault();
                                    List <RelatedArticlesSchema> relatedArticleSchema = new List <RelatedArticlesSchema>();
                                    relatedArticleSchema = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles");

                                    var index = relatedArticleSchema.IndexOf(relatedArticleSchema.Where(ras => ras.ArticleId == _article.ArticleId).First());
                                    if (index != -1)
                                    {
                                        if (titleInEnglish == "")
                                        {
                                            relatedArticleSchema.Remove(relatedArticleSchema.Where(ras => ras.ArticleId == _article.ArticleId).First());
                                        }
                                        else
                                        {
                                            relatedArticleSchema[index] = new RelatedArticlesSchema {
                                                ArticleId = _article.ArticleId, Title = (titleInEnglish == null ? "" : titleInEnglish), PublishedDate = _article.PublishedDate == null ? "" : _article.PublishedDate.ToString(), CountryId = _article.ArticleRelatedCountries.Select(s => new RelatedEntityId {
                                                    IdVal = s.CountryId
                                                }).ToList()
                                            }
                                        }
                                    }
                                    ;
                                    var eventSourcingRelated = new ArticleCommandEvent()
                                    {
                                        id = article != null?article.GetPropertyValue <Guid>("id") : Guid.NewGuid(),
                                                 EventType             = ServiceBusEventType.Update,
                                                 ArticleId             = article.GetPropertyValue <int>("ArticleId"),
                                                 PublishedDate         = article.GetPropertyValue <string>("PublishedDate"),
                                                 Author                = article.GetPropertyValue <string>("author"),
                                                 ImageId               = article.GetPropertyValue <int>("ImageId"),
                                                 State                 = article.GetPropertyValue <string>("State"),
                                                 Type                  = article.GetPropertyValue <int>("Type"),
                                                 SubType               = article.GetPropertyValue <int>("SubType"),
                                                 ResourcePosition      = article.GetPropertyValue <int>("ResourcePosition"),
                                                 Disclaimer            = article.GetPropertyValue <DisclamersSchema>("Disclaimer"),
                                                 ResourceGroup         = article.GetPropertyValue <ResourceGroupsSchema>("ResourceGroup"),
                                                 IsPublished           = article.GetPropertyValue <bool>("IsPublished"),
                                                 CreatedDate           = article.GetPropertyValue <string>("CreatedDate"),
                                                 CreatedBy             = article.GetPropertyValue <string>("CreatedBy"),
                                                 UpdatedDate           = article.GetPropertyValue <string>("UpdatedDate"),
                                                 UpdatedBy             = article.GetPropertyValue <string>("UpdatedBy"),
                                                 NotificationSentDate  = article.GetPropertyValue <string>("NotificationSentDate"),
                                                 Provinces             = article.GetPropertyValue <ProvinceSchema>("Provisions"),
                                                 ArticleContentId      = article.GetPropertyValue <int>("ArticleContentId"),
                                                 LanguageId            = article.GetPropertyValue <int>("LanguageId"),
                                                 Title                 = article.GetPropertyValue <string>("Title"),
                                                 TitleInEnglishDefault = article.GetPropertyValue <string>("TitleInEnglishDefault"),
                                                 TeaserText            = article.GetPropertyValue <string>("TeaserText"),
                                                 Content               = article.GetPropertyValue <string>("Content"),
                                                 RelatedContacts       = article.GetPropertyValue <List <RelatedEntityId> >("RelatedContacts"),
                                                 RelatedCountries      = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountries"),
                                                 RelatedCountryGroups  = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountryGroups"),
                                                 RelatedTaxTags        = article.GetPropertyValue <List <RelatedTaxTagsSchema> >("RelatedTaxTags"),
                                                 RelatedArticles       = relatedArticleSchema,
                                                 RelatedResources      = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedResources"),
                                                 Discriminator         = article.GetPropertyValue <string>("Discriminator"),
                                                 PartitionKey          = ""
                                    };
                                    await _Eventcontext.PublishThroughEventBusAsync(eventSourcingRelated);
                                }
                            }
                        }
                        var deleteEvt = new ArticleCommandEvent()
                        {
                            id = articleDocs.FirstOrDefault(d => d.GetPropertyValue <int>("ArticleId") == _article.ArticleId &&
                                                            d.GetPropertyValue <int>("LanguageId") == i).GetPropertyValue <Guid>("id"),
                            EventType     = ServiceBusEventType.Delete,
                            Discriminator = Constants.ArticlesDiscriminator,
                            PartitionKey  = i.ToString()
                        };
                        await _Eventcontext.PublishThroughEventBusAsync(deleteEvt);
                    }
                    scope.Complete();
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.IsSuccessful  = false;
                response.FailureReason = "Technical Error";
                // _logger.LogError(ex, "Error while handling command");
            }
            return(response);
        }
Esempio n. 22
0
        public async Task <ManipulateArticlesCommandResponse> Handle(ManipulateArticlesCommand request, CancellationToken cancellationToken)
        {
            ManipulateArticlesCommandResponse response = new ManipulateArticlesCommandResponse()
            {
                IsSuccessful = false
            };

            Disclaimers     DisclaimersDetails    = new Disclaimers();
            ResourceGroups  ResourceGroupsDetails = new ResourceGroups();
            Provinces       ProvincesDetails      = new Provinces();
            List <TaxTags>  taxTagsDetails        = new List <TaxTags>();
            List <Articles> articlesDetails       = new List <Articles>();
            List <Articles> articles = _ArticleRepository.getArticleCompleteDataById(request.ArticlesIds);

            if (request.ArticlesIds.Count != articles.Count)
            {
                throw new RulesException("Invalid", @"Country not found");
            }
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                if (request.Operation == "Publish")
                {
                    foreach (var article in articles)
                    {
                        article.IsPublished = true;
                        _ArticleRepository.Update <Articles>(article);
                    }
                }
                else if (request.Operation == "UnPublish")
                {
                    foreach (var article in articles)
                    {
                        article.IsPublished = false;
                        _ArticleRepository.Update <Articles>(article);
                    }
                }
                else if (request.Operation == "Delete")
                {
                    foreach (Articles article in articles)
                    {
                        foreach (var content in article.ArticleContents.ToList())
                        {
                            article.ArticleContents.Remove(content);
                            _ArticleRepository.Delete <ArticleContents>(content);
                        }
                        foreach (var country in article.ArticleRelatedCountries.ToList())
                        {
                            article.ArticleRelatedCountries.Remove(country);
                        }
                        foreach (var countryGroup in article.ArticleRelatedCountryGroups.ToList())
                        {
                            article.ArticleRelatedCountryGroups.Remove(countryGroup);
                        }
                        foreach (var taxTag in article.ArticleRelatedTaxTags.ToList())
                        {
                            article.ArticleRelatedTaxTags.Remove(taxTag);
                        }
                        foreach (var relatedArticle in article.RelatedArticlesArticle.ToList())
                        {
                            article.RelatedArticlesArticle.Remove(relatedArticle);
                            //Remove reverse relation
                            // relatedArticle.RelatedArticles.Remove(article);
                        }
                        foreach (var relatedResource in article.RelatedResourcesArticle.ToList())
                        {
                            article.RelatedResourcesArticle.Remove(relatedResource);
                        }
                        foreach (var readArticle in article.UserReadArticles.ToList())
                        {
                            article.UserReadArticles.Remove(readArticle);
                            _ArticleRepository.Delete <UserReadArticles>(readArticle);
                        }
                        foreach (var savedArticle in article.UserSavedArticles.ToList())
                        {
                            article.UserSavedArticles.Remove(savedArticle);
                            _ArticleRepository.Delete <UserSavedArticles>(savedArticle);
                        }
                        foreach (var contact in article.ArticleRelatedContacts.ToList())
                        {
                            article.ArticleRelatedContacts.Remove(contact);
                        }
                        _ArticleRepository.DeleteArticle(article);
                    }
                }
                else
                {
                    throw new RulesException("Operation", @"The Operation " + request.Operation + " is not valied");
                }
                await _ArticleRepository.UnitOfWork
                .SaveEntitiesAsync();

                response.IsSuccessful = true;
                scope.Complete();
            }
            var articleDocs = _context.GetAll(Constants.ArticlesDiscriminator);

            if (request.Operation == "Publish" || request.Operation == "UnPublish")
            {
                foreach (var article in articles)
                {
                    taxTagsDetails        = _ArticleRepository.getTaxTagsDetailsByIds(article.ArticleRelatedTaxTags.Select(s => s.TaxTagId).ToList());
                    articlesDetails       = _ArticleRepository.getArticleCompleteDataById(article.RelatedArticlesArticle.Select(s => s.RelatedArticleId).ToList());
                    ResourceGroupsDetails = article.ResourceGroupId == null ? null : _ArticleRepository.getResourceGroupById(int.Parse(article.ResourceGroupId.ToString()));
                    ProvincesDetails      = article.ProvinceId == null ? null : _ArticleRepository.getProvisionsById(int.Parse(article.ProvinceId.ToString()));
                    DisclaimersDetails    = article.DisclaimerId == null ? null : _ArticleRepository.getDisclaimerById(int.Parse(article.DisclaimerId.ToString()));
                    using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        foreach (var doc in articleDocs.Where(d => d.GetPropertyValue <int>("ArticleId") == article.ArticleId))
                        {
                            var DisclaimerLanguageId    = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37;
                            var ResourceGroupLanguageId = ResourceGroupsDetails.ResourceGroupContents.Where(d => d.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37;
                            var ProvisionsLanguageId    = ProvincesDetails.ProvinceContents.Where(d => d.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37;


                            var eventSourcing = new ArticleCommandEvent()
                            {
                                id = doc != null?doc.GetPropertyValue <Guid>("id") : Guid.NewGuid(),
                                         EventType        = doc != null ? ServiceBusEventType.Update : ServiceBusEventType.Create,
                                         ArticleId        = article.ArticleId,
                                         PublishedDate    = article.PublishedDate == null ? "" : article.PublishedDate.ToString(),
                                         Author           = article.Author == null ? "" : article.Author,
                                         ImageId          = article.ImageId == null ? -1 : article.ImageId,
                                         State            = article.State == null ? "" : article.State,
                                         Type             = article.Type == null ? -1 : article.Type,
                                         SubType          = article.SubType == null ? -1 : article.SubType,
                                         ResourcePosition = article.ResourcePosition == null ? -1 : article.ResourcePosition,
                                         Disclaimer       = new DisclamersSchema
                                {
                                    DisclaimerId = int.Parse(article.DisclaimerId.ToString()), ProviderName = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == DisclaimerLanguageId).Select(ds => ds.ProviderName == null ? "" : ds.ProviderName).FirstOrDefault(), ProviderTerms = DisclaimersDetails.DisclaimerContents.Where(d => d.LanguageId == DisclaimerLanguageId).Select(ds => ds.ProviderTerms == null ? "" : ds.ProviderTerms).FirstOrDefault()
                                },
                                ResourceGroup = new ResourceGroupsSchema {
                                    ResourceGroupId = int.Parse(article.ResourceGroupId.ToString()), GroupName = ResourceGroupsDetails.ResourceGroupContents.Where(d => d.LanguageId == ResourceGroupLanguageId).Select(ds => ds.GroupName == null ? "" : ds.GroupName).FirstOrDefault(), Position = ResourceGroupsDetails.Position == null ? -1 : ResourceGroupsDetails.Position
                                },
                                IsPublished          = request.Operation == "Publish" ? true : false,
                                CreatedDate          = article.CreatedDate == null ? "" : article.CreatedDate.ToString(),
                                CreatedBy            = article.CreatedBy == null ? "" : article.CreatedBy,
                                UpdatedDate          = article.UpdatedDate == null ? "" : article.UpdatedDate.ToString(),
                                UpdatedBy            = article.UpdatedBy == null ? "" : article.UpdatedBy,
                                NotificationSentDate = article.NotificationSentDate == null ? "" : article.NotificationSentDate.ToString(),
                                Provinces            = new ProvinceSchema {
                                    ProvinceId = int.Parse(article.ProvinceId.ToString()), DisplayName = ProvincesDetails.ProvinceContents.Where(d => d.LanguageId == ProvisionsLanguageId).Select(ds => ds.DisplayName == null ? "" : ds.DisplayName).FirstOrDefault()
                                },
                                ArticleContentId      = doc.GetPropertyValue <int>("ArticleContentId") == null ? -1 : doc.GetPropertyValue <int>("ArticleContentId"),
                                LanguageId            = doc.GetPropertyValue <int>("LanguageId") == null ? -1 : doc.GetPropertyValue <int>("LanguageId"),
                                Title                 = doc.GetPropertyValue <string>("Title") == null ? "" : doc.GetPropertyValue <string>("Title"),
                                TitleInEnglishDefault = doc.GetPropertyValue <string>("TitleInEnglishDefault") == null ? "" : doc.GetPropertyValue <string>("TitleInEnglishDefault"),
                                TeaserText            = doc.GetPropertyValue <string>("TeaserText") == null ? "" : doc.GetPropertyValue <string>("TeaserText"),
                                Content               = doc.GetPropertyValue <string>("Content") == null ? "" : doc.GetPropertyValue <string>("Content"),
                                RelatedContacts       = article.ArticleRelatedContacts.Select(s => new RelatedEntityId {
                                    IdVal = s.ContactId
                                }).ToList(),
                                RelatedCountries = article.ArticleRelatedCountries.Select(s => new RelatedEntityId {
                                    IdVal = s.CountryId
                                }).ToList(),
                                RelatedCountryGroups = article.ArticleRelatedCountryGroups.Select(s => new RelatedEntityId {
                                    IdVal = s.CountryGroupId
                                }).ToList(),
                                RelatedTaxTags   = article.ArticleRelatedTaxTags.Select(s => { var RelatedtaxTagLanguageId = taxTagsDetails.Where(td => td.TaxTagId == s.TaxTagId).FirstOrDefault().TaxTagContents.Where(ttc => ttc.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37; return(new RelatedTaxTagsSchema {
                                        TaxTagId = s.TaxTagId, DisplayName = taxTagsDetails.Where(td => td.TaxTagId == s.TaxTagId).FirstOrDefault().TaxTagContents.Where(ttc => ttc.LanguageId == RelatedtaxTagLanguageId).Select(ttcs => ttcs.DisplayName == null ? "" : ttcs.DisplayName).FirstOrDefault()
                                    }); }).ToList(),
                                RelatedArticles  = article.RelatedArticlesArticle.Select(s => { var RelatedArticleLanguageId = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37; return(new RelatedArticlesSchema {
                                        ArticleId = s.RelatedArticleId, PublishedDate = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).Select(v => v.PublishedDate == null ? "" : v.PublishedDate.ToString()).FirstOrDefault().ToString(), Title = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == RelatedArticleLanguageId).Select(v => v.Title == null ? "" : v.Title).FirstOrDefault().ToString(), CountryId = articlesDetails.Where(ad => ad.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleRelatedCountries.Select(arc => new RelatedEntityId {
                                            IdVal = arc.CountryId
                                        }).ToList()
                                    }); }).ToList(),
                                RelatedResources = article.RelatedResourcesArticle.Select(s => { var RelatedResourceLanguageId = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == doc.GetPropertyValue <int>("LanguageId")).Count() > 0 ? doc.GetPropertyValue <int>("LanguageId") : 37; return(new RelatedArticlesSchema {
                                        ArticleId = s.RelatedArticleId, PublishedDate = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).Select(v => v.PublishedDate == null ? "" : v.PublishedDate.ToString()).FirstOrDefault().ToString(), Title = articlesDetails.Where(ra => ra.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleContents.Where(ttc => ttc.LanguageId == RelatedResourceLanguageId).Select(v => v.Title == null ? "" : v.Title).FirstOrDefault().ToString(), CountryId = articlesDetails.Where(ad => ad.ArticleId.Equals(s.RelatedArticleId)).FirstOrDefault().ArticleRelatedCountries.Select(arc => new RelatedEntityId {
                                            IdVal = arc.CountryId
                                        }).ToList()
                                    }); }).ToList(),
                                Discriminator    = Constants.ArticlesDiscriminator,
                                PartitionKey     = ""
                            };
                            await _Eventcontext.PublishThroughEventBusAsync(eventSourcing);
                        }
                        scope.Complete();
                    }
                }
            }
            else if (request.Operation == "Delete")
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    foreach (var item in articles)
                    {
                        foreach (var content in item.ArticleContents)
                        {
                            foreach (var article in articleDocs.Where(ad => ad.GetPropertyValue <int>("LanguageId") == content.LanguageId))
                            {
                                foreach (var relatedArticles in article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles"))
                                {
                                    if (relatedArticles.ArticleId == item.ArticleId)
                                    {
                                        List <RelatedArticlesSchema> relatedArticleSchema = new List <RelatedArticlesSchema>();
                                        relatedArticleSchema = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedArticles");

                                        var index = relatedArticleSchema.IndexOf(relatedArticleSchema.Where(i => i.ArticleId == item.ArticleId).First());
                                        if (index != -1)
                                        {
                                            relatedArticleSchema.Remove(relatedArticleSchema.Where(i => i.ArticleId == item.ArticleId).First());
                                        }
                                        var eventSourcingRelated = new ArticleCommandEvent()
                                        {
                                            id = article != null?article.GetPropertyValue <Guid>("id") : Guid.NewGuid(),
                                                     EventType             = ServiceBusEventType.Update,
                                                     ArticleId             = article.GetPropertyValue <int>("ArticleId"),
                                                     PublishedDate         = article.GetPropertyValue <string>("PublishedDate"),
                                                     Author                = article.GetPropertyValue <string>("author"),
                                                     ImageId               = article.GetPropertyValue <int>("ImageId"),
                                                     State                 = article.GetPropertyValue <string>("State"),
                                                     Type                  = article.GetPropertyValue <int>("Type"),
                                                     SubType               = article.GetPropertyValue <int>("SubType"),
                                                     ResourcePosition      = article.GetPropertyValue <int>("ResourcePosition"),
                                                     Disclaimer            = article.GetPropertyValue <DisclamersSchema>("Disclaimer"),
                                                     ResourceGroup         = article.GetPropertyValue <ResourceGroupsSchema>("ResourceGroup"),
                                                     IsPublished           = article.GetPropertyValue <bool>("IsPublished"),
                                                     CreatedDate           = article.GetPropertyValue <string>("CreatedDate"),
                                                     CreatedBy             = article.GetPropertyValue <string>("CreatedBy"),
                                                     UpdatedDate           = article.GetPropertyValue <string>("UpdatedDate"),
                                                     UpdatedBy             = article.GetPropertyValue <string>("UpdatedBy"),
                                                     NotificationSentDate  = article.GetPropertyValue <string>("NotificationSentDate"),
                                                     Provinces             = article.GetPropertyValue <ProvinceSchema>("Provisions"),
                                                     ArticleContentId      = article.GetPropertyValue <int>("ArticleContentId"),
                                                     LanguageId            = article.GetPropertyValue <int>("LanguageId"),
                                                     Title                 = article.GetPropertyValue <string>("Title"),
                                                     TitleInEnglishDefault = article.GetPropertyValue <string>("TitleInEnglishDefault"),
                                                     TeaserText            = article.GetPropertyValue <string>("TeaserText"),
                                                     Content               = article.GetPropertyValue <string>("Content"),
                                                     RelatedContacts       = article.GetPropertyValue <List <RelatedEntityId> >("RelatedContacts"),
                                                     RelatedCountries      = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountries"),
                                                     RelatedCountryGroups  = article.GetPropertyValue <List <RelatedEntityId> >("RelatedCountryGroups"),
                                                     RelatedTaxTags        = article.GetPropertyValue <List <RelatedTaxTagsSchema> >("RelatedTaxTags"),
                                                     RelatedArticles       = relatedArticleSchema,
                                                     RelatedResources      = article.GetPropertyValue <List <RelatedArticlesSchema> >("RelatedResources"),
                                                     Discriminator         = article.GetPropertyValue <string>("Discriminator"),
                                                     PartitionKey          = ""
                                        };
                                        await _Eventcontext.PublishThroughEventBusAsync(eventSourcingRelated);
                                    }
                                }
                            }
                        }
                        foreach (var doc in articleDocs.Where(d => d.GetPropertyValue <int>("ArticleId") == item.ArticleId))
                        {
                            var articleevent = new ArticleCommandEvent()
                            {
                                id            = doc.GetPropertyValue <Guid>("id"),
                                EventType     = ServiceBusEventType.Delete,
                                Discriminator = Constants.ArticlesDiscriminator,
                                PartitionKey  = doc.GetPropertyValue <int>("LanguageId").ToString()
                            };
                            await _Eventcontext.PublishThroughEventBusAsync(articleevent);
                        }
                    }
                    scope.Complete();
                }
            }

            return(response);
        }
Esempio n. 23
0
        // GET: AppServiceCertificate
        public async Task <ActionResult> Index(string authError)
        {
            AppServiceCertificates appServiceCertificates = new AppServiceCertificates();
            OAuthTokenSet          usertoken = new OAuthTokenSet();

            Models.AzureRMWebCertificates.AzureRMWebCertificatesList azureRMWebCertificatesList = new Models.AzureRMWebCertificates.AzureRMWebCertificatesList();
            Models.AzureRMWebSites.ResourceManagerWebSites           resourceManagerWebSites    = new Models.AzureRMWebSites.ResourceManagerWebSites();
            // Always setup the OAuth /authorize URI to use
            Uri    redirectUri  = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
            string state        = GenerateState(userObjectID, Request.Url.ToString());
            string msoauthUri   = string.Format("{0}/oauth2/authorize?resource={1}&client_id={2}&response_type=code&redirect_uri={3}&state={4}",
                                                Startup.Authority, Url.Encode(Startup.resourceGroupsId), Startup.clientId, Url.Encode(redirectUri.ToString()), state);

            ViewBag.AuthorizationUrl = msoauthUri;

            // If we are loaded and we have no credentials, we will create a UserToken object to store the state that we include
            // in the link we construct to the Authorization endpoint. Once the user completes authorization, the OAuthController
            // will look up the user token that we created and fill it in with the tokens it obtains.
            if (authError != null)
            {
                usertoken.state        = state;
                usertoken.userId       = userObjectID;
                usertoken.resourceName = Startup.resourceGroupsId;
                model.OAuthTokens.Add(usertoken);
                await model.SaveChangesAsync();

                return(View(appServiceCertificates));
            }
            else
            {
                // Check local OAuthDataStore to see if we have previously cached OAuth bearer tokens for this user.
                IEnumerable <OAuthTokenSet> query =
                    from OAuthTokenSet in model.OAuthTokens where OAuthTokenSet.userId == userObjectID && OAuthTokenSet.resourceName == Startup.resourceGroupsId select OAuthTokenSet;

                if (query.GetEnumerator().MoveNext() == false)
                {
                    usertoken.state        = state;
                    usertoken.userId       = userObjectID;
                    usertoken.resourceName = Startup.resourceGroupsId;
                    model.OAuthTokens.Add(usertoken);
                    await model.SaveChangesAsync();

                    authError = "AuthorizationRequired";
                }
                else
                {
                    usertoken = query.First();
                    appServiceCertificates.AccessToken       = usertoken.accessToken;
                    appServiceCertificates.RefreshToken      = usertoken.refreshToken;
                    appServiceCertificates.AccessTokenExpiry = usertoken.accessTokenExpiry;
                    authError = null;


                    string requestUrl = String.Format(
                        CultureInfo.InvariantCulture,
                        Startup.resourceGroupsUrl,
                        HttpUtility.UrlEncode(Startup.subscriptionId));
                    HttpClient         client  = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", usertoken.accessToken);
                    HttpResponseMessage response = await client.SendAsync(request);

                    string responseString = await response.Content.ReadAsStringAsync();

                    ResourceGroups resourceGroups = JsonConvert.DeserializeObject <ResourceGroups>(responseString);
                    foreach (Value v in resourceGroups.value)
                    {
                        requestUrl = String.Format(
                            CultureInfo.InvariantCulture,
                            Startup.resourceManagerWebSitesUrl,
                            HttpUtility.UrlEncode(Startup.subscriptionId),
                            HttpUtility.UrlEncode(v.name));
                        client  = new HttpClient();
                        request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", usertoken.accessToken);
                        response = await client.SendAsync(request);

                        responseString = await response.Content.ReadAsStringAsync();

                        Models.AzureRMWebSites.ResourceManagerWebSiteInfo resourceManagerWebSiteInfo = JsonConvert.DeserializeObject <Models.AzureRMWebSites.ResourceManagerWebSiteInfo>(responseString);
                        resourceManagerWebSites.webSites.Add(resourceManagerWebSiteInfo);
                        AppServiceCertificate appServiceCertificate = new AppServiceCertificate();

                        foreach (Models.AzureRMWebSites.Value wsv in resourceManagerWebSiteInfo.value)
                        {
                            foreach (Models.AzureRMWebSites.Hostnamesslstate sslstate in wsv.properties.hostNameSslStates)
                            {
                                if (sslstate.sslState == 1)
                                {
                                    appServiceCertificate.SiteName = sslstate.name;
                                }
                            }
                        }
                        requestUrl = String.Format(
                            CultureInfo.InvariantCulture,
                            Startup.resourceManagerWebCertificatesUrl,
                            HttpUtility.UrlEncode(Startup.subscriptionId),
                            HttpUtility.UrlEncode(v.name));
                        client  = new HttpClient();
                        request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", usertoken.accessToken);
                        response = await client.SendAsync(request);

                        responseString = await response.Content.ReadAsStringAsync();

                        Models.AzureRMWebCertificates.AzureRMWebCertificates azureRMWebCertificates = JsonConvert.DeserializeObject <Models.AzureRMWebCertificates.AzureRMWebCertificates>(responseString);
                        foreach (Models.AzureRMWebCertificates.Value wsc in azureRMWebCertificates.value)
                        {
                            appServiceCertificate.KeyVaultSecretName    = wsc.properties.keyVaultSecretName;
                            appServiceCertificate.CertificateName       = wsc.properties.subjectName;
                            appServiceCertificate.KeyVaultId            = wsc.properties.keyVaultId;
                            appServiceCertificate.CertificateIssuer     = wsc.properties.issuer;
                            appServiceCertificate.CertificateExpiration = wsc.properties.expirationDate;
                            appServiceCertificate.CertificateThumbprint = wsc.properties.thumbprint;
                            appServiceCertificate.CertificateHostnames  = wsc.properties.hostNames;
                        }
                        appServiceCertificates.appServiceCertificates.Add(appServiceCertificate);
                    }
                }
                return(View(appServiceCertificates));
            }
        }
Esempio n. 24
0
        public async Task RemoteApplicationGroupCrud()
        {
            string hostPoolName         = "testRemoteApplicationGroupCrudHP";
            string applicationGroupName = "testRemoteApplicationGroupCrudAG";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();
            VirtualApplicationGroupData       agData       = new VirtualApplicationGroupData(DefaultLocation, opHostPoolCreate.Value.Data.Id, ApplicationGroupType.RemoteApp);

            ArmOperation <VirtualApplicationGroupResource> op = await agCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                applicationGroupName,
                agData);

            Assert.IsNotNull(op);
            Assert.IsTrue(op.HasCompleted);
            Assert.AreEqual(op.Value.Data.Name, applicationGroupName);

            Response <VirtualApplicationGroupResource> getOp = await agCollection.GetAsync(
                applicationGroupName);

            Assert.AreEqual(applicationGroupName, getOp.Value.Data.Name);

            agData.FriendlyName = "Friendly Name";
            op = await agCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                applicationGroupName,
                agData);

            Assert.IsNotNull(op);
            Assert.IsTrue(op.HasCompleted);
            Assert.AreEqual(op.Value.Data.Name, applicationGroupName);
            Assert.AreEqual(op.Value.Data.FriendlyName, "Friendly Name");

            getOp = await agCollection.GetAsync(
                applicationGroupName);

            VirtualApplicationGroupResource applicationGroup = getOp.Value;
            ArmOperation deleteOp = await applicationGroup.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(200, deleteOp.GetRawResponse().Status);

            deleteOp = await applicationGroup.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(204, deleteOp.GetRawResponse().Status);

            try
            {
                getOp = await agCollection.GetAsync(
                    applicationGroupName);
            }
            catch (RequestFailedException ex)
            {
                Assert.AreEqual(404, ex.Status);
            }

            await opHostPoolCreate.Value.DeleteAsync(WaitUntil.Completed);
        }
Esempio n. 25
0
        public async Task WorkspaceCrud()
        {
            string workspaceName     = "testWorkspaceCrudWS";
            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            VirtualWorkspaceCollection workspaceCollection = rg.GetVirtualWorkspaces();
            VirtualWorkspaceData       workspaceData       = new VirtualWorkspaceData(
                DefaultLocation);

            ArmOperation <VirtualWorkspaceResource> opWorkspaceCreate = await workspaceCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                workspaceName,
                workspaceData);

            Assert.IsNotNull(opWorkspaceCreate);
            Assert.IsTrue(opWorkspaceCreate.HasCompleted);
            Assert.AreEqual(opWorkspaceCreate.Value.Data.Name, workspaceName);

            Response <VirtualWorkspaceResource> getOp = await workspaceCollection.GetAsync(
                workspaceName);

            Assert.AreEqual(workspaceName, getOp.Value.Data.Name);

            workspaceData.FriendlyName = "Friendly Name";
            opWorkspaceCreate          = await workspaceCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                workspaceName,
                workspaceData);

            Assert.IsNotNull(opWorkspaceCreate);
            Assert.IsTrue(opWorkspaceCreate.HasCompleted);
            Assert.AreEqual(opWorkspaceCreate.Value.Data.Name, workspaceName);
            Assert.AreEqual(opWorkspaceCreate.Value.Data.FriendlyName, "Friendly Name");

            getOp = await workspaceCollection.GetAsync(
                workspaceName);

            VirtualWorkspaceResource workspace = getOp.Value;
            ArmOperation             deleteOp  = await workspace.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(200, deleteOp.GetRawResponse().Status);

            deleteOp = await workspace.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(204, deleteOp.GetRawResponse().Status);

            try
            {
                getOp = await workspaceCollection.GetAsync(
                    workspaceName);
            }
            catch (Azure.RequestFailedException ex)
            {
                Assert.AreEqual(404, ex.Status);
            }
        }
Esempio n. 26
0
        public async Task HostPoolCrud(
            int caseNumber,
            HostPoolType hostPoolType,
            LoadBalancerType loadBalancerType,
            LoadBalancerType expectedLoadBalancerType,
            PreferredAppGroupType preferredAppGroupType)
        {
            string hostPoolName = $"testHostPoolCrud{caseNumber}";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                hostPoolType,
                loadBalancerType,
                preferredAppGroupType);

            ArmOperation <HostPoolResource> op = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            Assert.IsNotNull(op);
            Assert.IsTrue(op.HasCompleted);
            Assert.AreEqual(op.Value.Data.Name, hostPoolName);

            Response <HostPoolResource> getOp = await hostPoolCollection.GetAsync(
                hostPoolName);

            Assert.AreEqual(hostPoolName, getOp.Value.Data.Name);
            Assert.AreEqual(hostPoolType, getOp.Value.Data.HostPoolType);
            Assert.AreEqual(expectedLoadBalancerType, getOp.Value.Data.LoadBalancerType);
            Assert.AreEqual(preferredAppGroupType, getOp.Value.Data.PreferredAppGroupType);

            hostPoolData.FriendlyName = "Friendly Name";
            op = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            Assert.IsNotNull(op);
            Assert.IsTrue(op.HasCompleted);
            Assert.AreEqual(op.Value.Data.Name, hostPoolName);
            Assert.AreEqual(op.Value.Data.FriendlyName, "Friendly Name");
            Assert.AreEqual(hostPoolName, getOp.Value.Data.Name);
            Assert.AreEqual(hostPoolType, getOp.Value.Data.HostPoolType);
            Assert.AreEqual(expectedLoadBalancerType, getOp.Value.Data.LoadBalancerType);
            Assert.AreEqual(preferredAppGroupType, getOp.Value.Data.PreferredAppGroupType);

            getOp = await hostPoolCollection.GetAsync(
                hostPoolName);

            HostPoolResource hostPool = getOp.Value;
            ArmOperation     deleteOp = await hostPool.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(200, deleteOp.GetRawResponse().Status);

            deleteOp = await hostPool.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(204, deleteOp.GetRawResponse().Status);

            try
            {
                getOp = await hostPoolCollection.GetAsync(
                    hostPoolName);
            }
            catch (RequestFailedException ex)
            {
                Assert.AreEqual(404, ex.Status);
            }
        }
Esempio n. 27
0
        public async Task WebAppWebPubSubConnectionCRUD()
        {
            string resourceGroupName = Recording.GenerateAssetName("SdkRg");
            string webAppName        = Recording.GenerateAssetName("SdkWeb");
            string webpubsubName     = Recording.GenerateAssetName("SdkWebPubSub");
            string linkerName        = Recording.GenerateAssetName("SdkLinker");

            // create resource group
            await ResourceGroups.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroupName, new Resources.ResourceGroupData(DefaultLocation));

            ResourceGroupResource resourceGroup = await ResourceGroups.GetAsync(resourceGroupName);

            // create web app
            WebSiteCollection webSites = resourceGroup.GetWebSites();
            await webSites.CreateOrUpdateAsync(WaitUntil.Completed, webAppName, new WebSiteData(DefaultLocation));

            WebSiteResource webapp = await webSites.GetAsync(webAppName);

            // create webpubsub
            WebPubSubCollection webPubSubs    = resourceGroup.GetWebPubSubs();
            WebPubSubData       webPubSubData = new WebPubSubData(DefaultLocation)
            {
                Sku = new WebPubSub.Models.WebPubSubSku("Standard_S1"),
                LiveTraceConfiguration = new WebPubSub.Models.LiveTraceConfiguration(),
                NetworkAcls            = new WebPubSub.Models.WebPubSubNetworkAcls
                {
                    PublicNetwork = new WebPubSub.Models.NetworkAcl(),
                },
            };

            webPubSubData.LiveTraceConfiguration.Categories.Clear();
            webPubSubData.NetworkAcls.PublicNetwork.Allow.Clear();
            webPubSubData.NetworkAcls.PublicNetwork.Deny.Clear();
            webPubSubData.ResourceLogCategories.Clear();
            await webPubSubs.CreateOrUpdateAsync(WaitUntil.Completed, webpubsubName, webPubSubData);

            WebPubSubResource webPubSub = await webPubSubs.GetAsync(webpubsubName);

            // create service linker
            LinkerResourceCollection linkers = webapp.GetLinkerResources();
            var linkerData = new LinkerResourceData
            {
                TargetService = new Models.AzureResource
                {
                    Id = webPubSub.Id,
                },
                AuthInfo   = new SecretAuthInfo(),
                ClientType = ClientType.Dotnet,
            };
            await linkers.CreateOrUpdateAsync(WaitUntil.Completed, linkerName, linkerData);

            // list service linker
            var linkerResources = await linkers.GetAllAsync().ToEnumerableAsync();

            Assert.AreEqual(1, linkerResources.Count);
            Assert.AreEqual(linkerName, linkerResources[0].Data.Name);

            // get service linker
            LinkerResource linker = await linkers.GetAsync(linkerName);

            Assert.IsTrue(linker.Id.ToString().StartsWith(webapp.Id.ToString(), StringComparison.InvariantCultureIgnoreCase));
            Assert.AreEqual(webPubSub.Id.ToString(), (linker.Data.TargetService as AzureResource).Id);
            Assert.AreEqual(AuthType.Secret, linker.Data.AuthInfo.AuthType);

            // get service linker configurations
            SourceConfigurationResult configurations = await linker.GetConfigurationsAsync();

            foreach (var configuration in configurations.Configurations)
            {
                Assert.IsNotNull(configuration.Name);
                Assert.IsNotNull(configuration.Value);
            }

            // delete service linker
            var operation = await linker.DeleteAsync(WaitUntil.Completed);

            Assert.IsTrue(operation.HasCompleted);
        }
Esempio n. 28
0
        public ResourceGroups getResourceGroupById(int ResourceGroupId)
        {
            ResourceGroups objContact = _context.ResourceGroups.Include(s => s.ResourceGroupContents).Where(r => r.ResourceGroupId == ResourceGroupId).FirstOrDefault();

            return(objContact);
        }
Esempio n. 29
0
        public async Task DesktopApplicationCrud()
        {
            string hostPoolName         = "testDesktopApplicationCrudHP";
            string applicationGroupName = "testDesktopApplicationCrudAG";

            string resourceGroupName = Recording.GetVariable("DESKTOPVIRTUALIZATION_RESOURCE_GROUP", DefaultResourceGroupName);
            ResourceGroupResource rg = (ResourceGroupResource)await ResourceGroups.GetAsync(resourceGroupName);

            Assert.IsNotNull(rg);
            HostPoolCollection hostPoolCollection = rg.GetHostPools();
            HostPoolData       hostPoolData       = new HostPoolData(
                DefaultLocation,
                HostPoolType.Pooled,
                LoadBalancerType.BreadthFirst,
                PreferredAppGroupType.Desktop);

            ArmOperation <HostPoolResource> opHostPoolCreate = await hostPoolCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                hostPoolName,
                hostPoolData);

            VirtualApplicationGroupCollection agCollection = rg.GetVirtualApplicationGroups();
            VirtualApplicationGroupData       agData       = new VirtualApplicationGroupData(DefaultLocation, opHostPoolCreate.Value.Data.Id, ApplicationGroupType.Desktop);

            ArmOperation <VirtualApplicationGroupResource> opApplicationGroupCreate = await agCollection.CreateOrUpdateAsync(
                WaitUntil.Completed,
                applicationGroupName,
                agData);

            Assert.IsNotNull(opApplicationGroupCreate);
            Assert.IsTrue(opApplicationGroupCreate.HasCompleted);
            Assert.AreEqual(opApplicationGroupCreate.Value.Data.Name, applicationGroupName);

            VirtualApplicationGroupResource desktopApplicationGroup = opApplicationGroupCreate.Value;

            VirtualDesktopCollection desktopCollection = desktopApplicationGroup.GetVirtualDesktops();

            AsyncPageable <VirtualDesktopResource> desktops = desktopCollection.GetAllAsync();

            Assert.IsNotNull(desktops);

            List <VirtualDesktopResource> desktopList = await desktops.ToEnumerableAsync();

            Assert.AreEqual(1, desktopList.Count);

            VirtualDesktopResource desktop = desktopList[0];

            await desktop.UpdateAsync(new VirtualDesktopPatch { Description = "Updated", FriendlyName = "UpdatedFriendlyName" });

            Response <VirtualDesktopResource> updatedDesktop = await desktopCollection.GetAsync(desktop.Id.Name);

            Assert.IsNotNull(updatedDesktop);

            Assert.AreEqual("Updated", updatedDesktop.Value.Data.Description);

            Assert.AreEqual("UpdatedFriendlyName", updatedDesktop.Value.Data.FriendlyName);

            Response <VirtualApplicationGroupResource> getOp = await agCollection.GetAsync(
                applicationGroupName);

            Assert.AreEqual(applicationGroupName, getOp.Value.Data.Name);

            VirtualApplicationGroupResource applicationGroup = getOp.Value;
            ArmOperation deleteOp = await applicationGroup.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(200, deleteOp.GetRawResponse().Status);

            deleteOp = await applicationGroup.DeleteAsync(WaitUntil.Completed);

            Assert.IsNotNull(deleteOp);

            Assert.AreEqual(204, deleteOp.GetRawResponse().Status);

            try
            {
                getOp = await agCollection.GetAsync(
                    applicationGroupName);
            }
            catch (RequestFailedException ex)
            {
                Assert.AreEqual(404, ex.Status);
            }

            await opHostPoolCreate.Value.DeleteAsync(WaitUntil.Completed);
        }
        public async Task WebAppKeyVaultConnectionCRUD()
        {
            string resourceGroupName = Recording.GenerateAssetName("SdkRg");
            string webAppName        = Recording.GenerateAssetName("SdkWeb");
            string vaultName         = Recording.GenerateAssetName("SdkVault");
            string linkerName        = Recording.GenerateAssetName("SdkLinker");

            // create resource group
            await ResourceGroups.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroupName, new Resources.ResourceGroupData(DefaultLocation));

            ResourceGroupResource resourceGroup = await ResourceGroups.GetAsync(resourceGroupName);

            // create web app
            WebSiteCollection webSites = resourceGroup.GetWebSites();
            await webSites.CreateOrUpdateAsync(WaitUntil.Completed, webAppName, new WebSiteData(DefaultLocation));

            WebSiteResource webapp = await webSites.GetAsync(webAppName);

            // create key vault
            VaultCollection vaults          = resourceGroup.GetVaults();
            var             vaultProperties = new VaultProperties(new Guid(TestEnvironment.TenantId), new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard));

            vaultProperties.AccessPolicies.Clear();
            await vaults.CreateOrUpdateAsync(WaitUntil.Completed, vaultName, new VaultCreateOrUpdateContent(DefaultLocation, vaultProperties));

            VaultResource vault = await vaults.GetAsync(vaultName);

            // create service linker
            LinkerResourceCollection linkers = webapp.GetLinkerResources();
            var linkerData = new LinkerResourceData
            {
                TargetService = new Models.AzureResource
                {
                    Id = vault.Id,
                },
                AuthInfo   = new SystemAssignedIdentityAuthInfo(),
                ClientType = ClientType.Dotnet,
            };
            await linkers.CreateOrUpdateAsync(WaitUntil.Completed, linkerName, linkerData);

            // list service linker
            var linkerResources = await linkers.GetAllAsync().ToEnumerableAsync();

            Assert.AreEqual(1, linkerResources.Count);
            Assert.AreEqual(linkerName, linkerResources[0].Data.Name);

            // get service linker
            LinkerResource linker = await linkers.GetAsync(linkerName);

            Assert.IsTrue(linker.Id.ToString().StartsWith(webapp.Id.ToString(), StringComparison.InvariantCultureIgnoreCase));
            Assert.AreEqual(vault.Id.ToString(), (linker.Data.TargetService as AzureResource).Id);
            Assert.AreEqual(AuthType.SystemAssignedIdentity, linker.Data.AuthInfo.AuthType);

            // get service linker configurations
            SourceConfigurationResult configurations = await linker.GetConfigurationsAsync();

            foreach (var configuration in configurations.Configurations)
            {
                Assert.IsNotNull(configuration.Name);
                Assert.IsNotNull(configuration.Value);
            }

            // delete service linker
            var operation = await linker.DeleteAsync(WaitUntil.Completed);

            Assert.IsTrue(operation.HasCompleted);
        }