Example #1
0
        public void FiltersGalleryTemplates()
        {
            string             filterString = FilterString.Generate <ItemListFilter>(f => f.Publisher == "Microsoft");
            ItemListParameters actual       = new ItemListParameters();

            galleryClientMock.Setup(f => f.Items.ListAsync(It.IsAny <ItemListParameters>(), new CancellationToken()))
            .Returns(Task.Factory.StartNew(() => new ItemListResult
            {
                Items = new List <GalleryItem>()
                {
                    new GalleryItem()
                    {
                        Name      = "Template1",
                        Publisher = "Microsoft"
                    },
                    new GalleryItem()
                    {
                        Name      = "Template2",
                        Publisher = "Microsoft"
                    }
                }
            }))
            .Callback((ItemListParameters p, CancellationToken c) => actual = p);

            FilterGalleryTemplatesOptions options = new FilterGalleryTemplatesOptions()
            {
                Publisher = "Microsoft"
            };

            List <PSGalleryItem> result = galleryTemplatesClient.FilterGalleryTemplates(options);

            Assert.Equal(2, result.Count);
            Assert.True(result.All(g => g.Publisher == "Microsoft"));
            Assert.Equal(filterString, actual.Filter);
        }
Example #2
0
        public void FiltersGalleryTemplatesUsingComplexQuery()
        {
            string             filterString = "Publisher eq 'Microsoft' and CategoryIds/any(c: c eq 'awesome')";
            ItemListParameters actual       = new ItemListParameters();

            galleryClientMock.Setup(f => f.Items.ListAsync(It.IsAny <ItemListParameters>(), new CancellationToken()))
            .Returns(Task.Factory.StartNew(() => new ItemListResult
            {
                Items = new List <GalleryItem>()
                {
                    new GalleryItem()
                    {
                        Name      = "Template1",
                        Publisher = "Microsoft"
                    },
                    new GalleryItem()
                    {
                        Name      = "Template2",
                        Publisher = "Microsoft"
                    }
                }
            }))
            .Callback((ItemListParameters p, CancellationToken c) => actual = p);

            FilterGalleryTemplatesOptions options = new FilterGalleryTemplatesOptions()
            {
                Publisher = "Microsoft",
                Category  = "awesome"
            };

            List <PSGalleryItem> result = galleryTemplatesClient.FilterGalleryTemplates(options);

            Assert.Equal(2, result.Count);
            Assert.Equal(filterString, actual.Filter);
        }
Example #3
0
        /// <summary>
        /// Filters gallery templates based on the passed options.
        /// </summary>
        /// <param name="options">The filter options</param>
        /// <returns>The filtered list</returns>
        public virtual List <PSGalleryItem> FilterGalleryTemplates(FilterGalleryTemplatesOptions options)
        {
            List <string>      filterStrings = new List <string>();
            ItemListParameters parameters    = null;
            List <GalleryItem> result        = new List <GalleryItem>();

            if (!string.IsNullOrEmpty(options.Identity))
            {
                result.Add(GalleryClient.Items.Get(options.Identity).Item);
            }
            else
            {
                result.AddRange(QueryGalleryTemplates(options, filterStrings, parameters));
            }

            if (!options.AllVersions && result.Count > 1)
            {
                // Take only the most recent version
                GalleryItem mostRecentTemplate = MostRecentTemplate(result);
                if (mostRecentTemplate != null)
                {
                    return(new List <PSGalleryItem>()
                    {
                        mostRecentTemplate.ToPSGalleryItem()
                    });
                }
            }

            return(result.Select(i => i.ToPSGalleryItem()).ToList());
        }
Example #4
0
 /// <summary>
 /// Gets collection of gallery items.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the Microsoft.Azure.Gallery.IItemOperations.
 /// </param>
 /// <param name='parameters'>
 /// Optional. Query parameters. If null is passed returns all gallery
 /// items.
 /// </param>
 /// <returns>
 /// List of gallery items.
 /// </returns>
 public static ItemListResult List(this IItemOperations operations, ItemListParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IItemOperations)s).ListAsync(parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Example #5
0
        /// <summary>
        /// Filters gallery templates based on the passed options.
        /// </summary>
        /// <param name="options">The filter options</param>
        /// <returns>The filtered list</returns>
        public virtual List <PSGalleryItem> FilterGalleryTemplates(FilterGalleryTemplatesOptions options)
        {
            List <string>      filterStrings = new List <string>();
            ItemListParameters parameters    = null;
            List <GalleryItem> result        = new List <GalleryItem>();

            if (!string.IsNullOrEmpty(options.Identity))
            {
                result.Add(GalleryClient.Items.Get(options.Identity).Item);
            }
            else
            {
                result.AddRange(QueryGalleryTemplates(options, filterStrings, parameters));
            }

            if (!options.AllVersions && result.Count > 1)
            {
                if (!string.IsNullOrEmpty(options.Publisher) && string.IsNullOrEmpty(options.ApplicationName) && string.IsNullOrEmpty(options.Identity))
                {
                    // we return a list of the most recent templates, for each name.
                    List <GalleryItem>   latest        = new List <GalleryItem>();
                    IEnumerable <string> distinctNames = result.Select(g => g.Name).Distinct();
                    foreach (var name in distinctNames)
                    {
                        List <GalleryItem> galleryItems   = result.Where(x => x.Name.Equals(name)).ToList();
                        GalleryItem        recentTemplate = this.MostRecentTemplate(galleryItems);
                        if (recentTemplate != null)
                        {
                            latest.Add(recentTemplate);
                        }
                    }

                    return(latest.Select(i => i.ToPSGalleryItem()).ToList());
                }

                // Take only the most recent version
                GalleryItem mostRecentTemplate = MostRecentTemplate(result);
                if (mostRecentTemplate != null)
                {
                    return(new List <PSGalleryItem>()
                    {
                        mostRecentTemplate.ToPSGalleryItem()
                    });
                }
            }

            return(result.Select(i => i.ToPSGalleryItem()).ToList());
        }
        /// <summary>
        /// Filters gallery templates based on the passed options.
        /// </summary>
        /// <param name="options">The filter options</param>
        /// <returns>The filtered list</returns>
        public virtual List <PSGalleryItem> FilterGalleryTemplates(FilterGalleryTemplatesOptions options)
        {
            List <string>      filterStrings = new List <string>();
            ItemListParameters parameters    = null;
            List <GalleryItem> result        = new List <GalleryItem>();

            if (!string.IsNullOrEmpty(options.Identity))
            {
                result.Add(GalleryClient.Items.Get(options.Identity).Item);
            }
            else
            {
                result.AddRange(QueryGalleryTemplates(options, filterStrings, parameters));
            }

            return(result.Select(i => i.ToPSGalleryItem()).ToList());
        }
Example #7
0
        public MovieSpotlightViewModel(Task<MoviesView> moviesViewTask, IImageManager imageManager, INavigator navigator, IApiClient apiClient, IServerEvents serverEvents,
                                       IPlaybackManager playbackManager, ISessionManager sessionManager, ILogManager logManager)
        {
            _imageManager = imageManager;
            _navigator = navigator;
            _apiClient = apiClient;
            _serverEvents = serverEvents;
            _playbackManager = playbackManager;
            _sessionManager = sessionManager;
            _logger = logManager.GetLogger("Movies Spotlight");
            SpotlightHeight = HomeViewModel.TileHeight*2 + HomeViewModel.TileMargin*2;
            SpotlightWidth = 16*(SpotlightHeight/9) + 100;
            _miniSpotlightWidth = HomeViewModel.TileWidth + (HomeViewModel.TileMargin/4) - 1;

            LowerSpotlightWidth = SpotlightWidth/2 - HomeViewModel.TileMargin;
            LowerSpotlightHeight = HomeViewModel.TileHeight;

            BrowseMoviesCommand = new RelayCommand(arg => {
                var itemParams = new ItemListParameters { 
                    Items = GetMovies(),
                    Title = "Browse Movies"
                };

                navigator.Navigate(Go.To.ItemList(itemParams));

                //await navigator.Navigate(Go.To.Item(await _apiClient.GetPersonAsync("Chris Pine", sessionManager.CurrentUser.Id)));
            });

            SpotlightViewModel = new ItemSpotlightViewModel(imageManager, apiClient) {
                ImageType = ImageType.Backdrop,
                ItemSelectedAction = i => navigator.Navigate(Go.To.Item(i))
            };

            AllMoviesImagesViewModel = new ImageSlideshowViewModel(imageManager, Enumerable.Empty<string>()) {
                ImageStretch = Stretch.UniformToFill
            };

            MiniSpotlightItems = new RangeObservableCollection<ItemTileViewModel> {
                CreateMiniSpotlightItem(),
                CreateMiniSpotlightItem(),
                CreateMiniSpotlightItem(),
            };

            LoadViewModels(moviesViewTask);
        }
Example #8
0
        public void FiltersGalleryTemplatesLatestVersion()
        {
            string             filterString = FilterString.Generate <ItemListFilter>(f => f.Publisher == "Microsoft");
            ItemListParameters actual       = new ItemListParameters();

            galleryClientMock.Setup(f => f.Items.ListAsync(It.IsAny <ItemListParameters>(), new CancellationToken()))
            .Returns(Task.Factory.StartNew(() => new ItemListResult
            {
                Items = new List <GalleryItem>()
                {
                    new GalleryItem()
                    {
                        Name      = "Template0",
                        Publisher = "Microsoft",
                        Version   = "0.0.0.0"
                    },
                    new GalleryItem()
                    {
                        Name      = "Template0",
                        Publisher = "Microsoft",
                        Version   = "0.0.0.1"
                    },
                    new GalleryItem()
                    {
                        Name      = "Template0",
                        Publisher = "Microsoft",
                        Version   = "0.0.0.2"
                    }
                }
            }))
            .Callback((ItemListParameters p, CancellationToken c) => actual = p);

            FilterGalleryTemplatesOptions options = new FilterGalleryTemplatesOptions()
            {
                ApplicationName = "Template0"
            };

            List <PSGalleryItem> result = galleryTemplatesClient.FilterGalleryTemplates(options);

            Assert.Equal(1, result.Count);
            Assert.Equal("Template0", result[0].Name);
            Assert.Equal("0.0.0.2", result[0].Version);
        }
Example #9
0
        private List <GalleryItem> QueryGalleryTemplates(FilterGalleryTemplatesOptions options, List <string> filterStrings, ItemListParameters parameters)
        {
            if (!string.IsNullOrEmpty(options.Publisher))
            {
                filterStrings.Add(FilterString.Generate <ItemListFilter>(f => f.Publisher == options.Publisher));
            }

            if (!string.IsNullOrEmpty(options.Category))
            {
                filterStrings.Add(FilterString.Generate <ItemListFilter>(f => f.CategoryIds.Contains(options.Category)));
            }

            if (filterStrings.Count > 0)
            {
                parameters = new ItemListParameters()
                {
                    Filter = string.Join(" and ", filterStrings)
                };
            }

            List <GalleryItem> galleryItems = GalleryClient.Items.List(parameters).Items.ToList();

            if (!string.IsNullOrEmpty(options.ApplicationName))
            {
                List <GalleryItem> result = new List <GalleryItem>();
                string             wildcardApplicationName = Regex.Escape(options.ApplicationName).Replace(@"\*", ".*").Replace(@"\?", ".");
                Regex regex = new Regex(wildcardApplicationName, RegexOptions.IgnoreCase);
                foreach (var galleryItem in galleryItems)
                {
                    if (regex.IsMatch(galleryItem.Name))
                    {
                        result.Add(galleryItem);
                    }
                }

                return(result);
            }

            return(galleryItems);
        }
        private List <GalleryItem> QueryGalleryTemplates(FilterGalleryTemplatesOptions options, List <string> filterStrings, ItemListParameters parameters)
        {
            if (!string.IsNullOrEmpty(options.Publisher))
            {
                filterStrings.Add(FilterString.Generate <ItemListFilter>(f => f.Publisher == options.Publisher));
            }

            if (!string.IsNullOrEmpty(options.Category))
            {
                filterStrings.Add(FilterString.Generate <ItemListFilter>(f => f.CategoryIds.Contains(options.Category)));
            }

            if (filterStrings.Count > 0)
            {
                parameters = new ItemListParameters()
                {
                    Filter = string.Join(" and ", filterStrings)
                };
            }

            return(GalleryClient.Items.List(parameters).Items.ToList());
        }
Example #11
0
        /// <summary>
        /// Gets collection of gallery items.
        /// </summary>
        /// <param name='parameters'>
        /// Optional. Query parameters. If null is passed returns all gallery
        /// items.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of gallery items.
        /// </returns>
        public async Task <ItemListResult> ListAsync(ItemListParameters parameters, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url          = "/Microsoft.Gallery/galleryitems?";
            bool   appendFilter = true;

            if (parameters != null && parameters.Filter != null)
            {
                appendFilter = false;
                url          = url + "$filter=" + Uri.EscapeDataString(parameters.Filter != null ? parameters.Filter.Trim() : "");
            }
            if (parameters != null && parameters.Top != null)
            {
                url = url + "&$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString());
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ItemListResult result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new ItemListResult();
                    JToken responseDoc = null;
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        responseDoc = JToken.Parse(responseContent);
                    }

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        JToken itemsArray = responseDoc;
                        if (itemsArray != null && itemsArray.Type != JTokenType.Null)
                        {
                            result.Items = new List <GalleryItem>();
                            foreach (JToken itemsValue in ((JArray)itemsArray))
                            {
                                GalleryItem galleryItemInstance = new GalleryItem();
                                result.Items.Add(galleryItemInstance);

                                JToken identityValue = itemsValue["identity"];
                                if (identityValue != null && identityValue.Type != JTokenType.Null)
                                {
                                    string identityInstance = ((string)identityValue);
                                    galleryItemInstance.Identity = identityInstance;
                                }

                                JToken itemNameValue = itemsValue["itemName"];
                                if (itemNameValue != null && itemNameValue.Type != JTokenType.Null)
                                {
                                    string itemNameInstance = ((string)itemNameValue);
                                    galleryItemInstance.Name = itemNameInstance;
                                }

                                JToken itemDisplayNameValue = itemsValue["itemDisplayName"];
                                if (itemDisplayNameValue != null && itemDisplayNameValue.Type != JTokenType.Null)
                                {
                                    string itemDisplayNameInstance = ((string)itemDisplayNameValue);
                                    galleryItemInstance.DisplayName = itemDisplayNameInstance;
                                }

                                JToken publisherValue = itemsValue["publisher"];
                                if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                {
                                    string publisherInstance = ((string)publisherValue);
                                    galleryItemInstance.Publisher = publisherInstance;
                                }

                                JToken publisherDisplayNameValue = itemsValue["publisherDisplayName"];
                                if (publisherDisplayNameValue != null && publisherDisplayNameValue.Type != JTokenType.Null)
                                {
                                    string publisherDisplayNameInstance = ((string)publisherDisplayNameValue);
                                    galleryItemInstance.PublisherDisplayName = publisherDisplayNameInstance;
                                }

                                JToken versionValue = itemsValue["version"];
                                if (versionValue != null && versionValue.Type != JTokenType.Null)
                                {
                                    string versionInstance = ((string)versionValue);
                                    galleryItemInstance.Version = versionInstance;
                                }

                                JToken summaryValue = itemsValue["summary"];
                                if (summaryValue != null && summaryValue.Type != JTokenType.Null)
                                {
                                    string summaryInstance = ((string)summaryValue);
                                    galleryItemInstance.Summary = summaryInstance;
                                }

                                JToken descriptionValue = itemsValue["description"];
                                if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                {
                                    string descriptionInstance = ((string)descriptionValue);
                                    galleryItemInstance.Description = descriptionInstance;
                                }

                                JToken resourceGroupNameValue = itemsValue["resourceGroupName"];
                                if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null)
                                {
                                    string resourceGroupNameInstance = ((string)resourceGroupNameValue);
                                    galleryItemInstance.ResourceGroupName = resourceGroupNameInstance;
                                }

                                JToken definitionTemplatesValue = itemsValue["definitionTemplates"];
                                if (definitionTemplatesValue != null && definitionTemplatesValue.Type != JTokenType.Null)
                                {
                                    DefinitionTemplates definitionTemplatesInstance = new DefinitionTemplates();
                                    galleryItemInstance.DefinitionTemplates = definitionTemplatesInstance;

                                    JToken uiDefinitionFileUrlValue = definitionTemplatesValue["uiDefinitionFileUrl"];
                                    if (uiDefinitionFileUrlValue != null && uiDefinitionFileUrlValue.Type != JTokenType.Null)
                                    {
                                        string uiDefinitionFileUrlInstance = ((string)uiDefinitionFileUrlValue);
                                        definitionTemplatesInstance.UiDefinitionFileUrl = uiDefinitionFileUrlInstance;
                                    }

                                    JToken defaultDeploymentTemplateIdValue = definitionTemplatesValue["defaultDeploymentTemplateId"];
                                    if (defaultDeploymentTemplateIdValue != null && defaultDeploymentTemplateIdValue.Type != JTokenType.Null)
                                    {
                                        string defaultDeploymentTemplateIdInstance = ((string)defaultDeploymentTemplateIdValue);
                                        definitionTemplatesInstance.DefaultDeploymentTemplateId = defaultDeploymentTemplateIdInstance;
                                    }

                                    JToken deploymentTemplateFileUrlsSequenceElement = ((JToken)definitionTemplatesValue["deploymentTemplateFileUrls"]);
                                    if (deploymentTemplateFileUrlsSequenceElement != null && deploymentTemplateFileUrlsSequenceElement.Type != JTokenType.Null)
                                    {
                                        definitionTemplatesInstance.DeploymentTemplateFileUrls = new Dictionary <string, string>();
                                        foreach (JProperty property in deploymentTemplateFileUrlsSequenceElement)
                                        {
                                            string deploymentTemplateFileUrlsKey   = ((string)property.Name);
                                            string deploymentTemplateFileUrlsValue = ((string)property.Value);
                                            definitionTemplatesInstance.DeploymentTemplateFileUrls.Add(deploymentTemplateFileUrlsKey, deploymentTemplateFileUrlsValue);
                                        }
                                    }
                                }

                                JToken categoryIdsArray = itemsValue["categoryIds"];
                                if (categoryIdsArray != null && categoryIdsArray.Type != JTokenType.Null)
                                {
                                    galleryItemInstance.CategoryIds = new List <string>();
                                    foreach (JToken categoryIdsValue in ((JArray)categoryIdsArray))
                                    {
                                        galleryItemInstance.CategoryIds.Add(((string)categoryIdsValue));
                                    }
                                }

                                JToken screenshotUrlsArray = itemsValue["screenshotUrls"];
                                if (screenshotUrlsArray != null && screenshotUrlsArray.Type != JTokenType.Null)
                                {
                                    galleryItemInstance.ScreenshotUrls = new List <string>();
                                    foreach (JToken screenshotUrlsValue in ((JArray)screenshotUrlsArray))
                                    {
                                        galleryItemInstance.ScreenshotUrls.Add(((string)screenshotUrlsValue));
                                    }
                                }

                                JToken iconFileUrlsSequenceElement = ((JToken)itemsValue["iconFileUrls"]);
                                if (iconFileUrlsSequenceElement != null && iconFileUrlsSequenceElement.Type != JTokenType.Null)
                                {
                                    galleryItemInstance.IconFileUrls = new Dictionary <string, string>();
                                    foreach (JProperty property2 in iconFileUrlsSequenceElement)
                                    {
                                        string iconFileUrlsKey   = ((string)property2.Name);
                                        string iconFileUrlsValue = ((string)property2.Value);
                                        galleryItemInstance.IconFileUrls.Add(iconFileUrlsKey, iconFileUrlsValue);
                                    }
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Example #12
0
 /// <summary>
 /// Gets collection of gallery items.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the Microsoft.Azure.Gallery.IItemOperations.
 /// </param>
 /// <param name='parameters'>
 /// Optional. Query parameters. If null is passed returns all gallery
 /// items.
 /// </param>
 /// <returns>
 /// List of gallery items.
 /// </returns>
 public static Task <ItemListResult> ListAsync(this IItemOperations operations, ItemListParameters parameters)
 {
     return(operations.ListAsync(parameters, CancellationToken.None));
 }