예제 #1
0
        /// <summary>
        /// Search for templates in the PnP Templates Gallery
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="platforms"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        public ProvisioningTemplateInformation[] SearchProvisioningTemplates(string searchText, TargetPlatform platforms, TargetScope scope)
        {
            ProvisioningTemplateInformation[] result = null;

            String targetPlatforms = platforms.ToString();
            String targetScopes    = scope.ToString();

            // Search via HTTP REST
            var jsonSearchResult = HttpHelper.MakeGetRequestForString(
                $"{this._templatesGalleryBaseUrl}api/SearchTemplates?searchText={HttpUtility.UrlEncode(searchText)}&platforms={targetPlatforms}&scope={targetScopes}");

            // If we have any result
            if (!String.IsNullOrEmpty(jsonSearchResult))
            {
                // Convert from JSON to a typed array
                var searchResultItems = JsonConvert.DeserializeObject <PnPTemplatesGalleryResultItem[]>(jsonSearchResult);

                result = (from r in searchResultItems
                          select new ProvisioningTemplateInformation
                {
                    DisplayName = r.Title,
                    Description = r.Abstract,
                    TemplateFileUri = r.TemplatePnPUrl,
                    TemplateImageUrl = r.ImageUrl,
                    Scope = r.Scopes,
                    Platforms = r.Platforms,
                }).ToArray();
            }

            return(result);
        }
예제 #2
0
        internal static IEnumerable <ProvisioningTemplateInformation> SearchTemplates(string searchKey, TargetPlatform targetPlatforms, TargetScope targetScopes)
        {
            var targetPlatformsString = targetPlatforms.ToString();
            var targetScopesString    = targetScopes.ToString();

            searchKey = searchKey != null?System.Web.HttpUtility.UrlEncode(searchKey) : "";

            var jsonSearchResult =
                HttpHelper.MakeGetRequestForString(
                    $"{BaseTemplateGalleryUrl}/api/SearchTemplates?searchText={searchKey}&Platform={System.Web.HttpUtility.UrlEncode(targetPlatformsString)}&Scope={System.Web.HttpUtility.UrlEncode(targetScopesString)}");

            if (!string.IsNullOrEmpty(jsonSearchResult))
            {
                // Convert from JSON to a typed array
                var searchResultItems =
                    JsonConvert.DeserializeObject <PnPTemplatesGalleryResultItem[]>(jsonSearchResult);

                var result = (from r in searchResultItems
                              select new ProvisioningTemplateInformation
                {
                    Id = r.Id,
                    DisplayName = r.Title,
                    Description = r.Abstract,
                    TemplateFileUri = r.TemplatePnPUrl,
                    TemplateImageUrl = r.ImageUrl,
                    Scope = r.Scopes,
                    Platforms = r.Platforms,
                }).ToArray();
                return(result);
            }
            return(null);
        }
        private List <ProvisioningTemplateInformation> SearchProvisioningTemplatesInternal(string searchText, TargetPlatform platforms, TargetScope scope, String cacheKey)
        {
            List <ProvisioningTemplateInformation> result = new List <ProvisioningTemplateInformation>();

            // Connect to the target Templates Site Collection
            using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(TemplatesSiteUrl))
            {
                // Get a reference to the target library
                Web web = context.Web;

                String platformsCAMLFilter = null;

                // Build the target Platforms filter
                if (platforms != TargetPlatform.None && platforms != TargetPlatform.All)
                {
                    if ((platforms & TargetPlatform.SharePointOnline) == TargetPlatform.SharePointOnline)
                    {
                        platformsCAMLFilter = @"<Eq>
                                                    <FieldRef Name='PnPProvisioningTemplatePlatform' />
                                                    <Value Type='MultiChoice'>SharePoint Online</Value>
                                                </Eq>";
                    }
                    if ((platforms & TargetPlatform.SharePoint2016) == TargetPlatform.SharePoint2016)
                    {
                        if (!String.IsNullOrEmpty(platformsCAMLFilter))
                        {
                            platformsCAMLFilter = @"<Or>" +
                                                  platformsCAMLFilter + @"
                                                        <Eq>
                                                            <FieldRef Name='PnPProvisioningTemplatePlatform' />
                                                            <Value Type='MultiChoice'>SharePoint 2016</Value>
                                                        </Eq>
                                                    </Or>";
                        }
                        else
                        {
                            platformsCAMLFilter = @"<Eq>
                                                    <FieldRef Name='PnPProvisioningTemplatePlatform' />
                                                    <Value Type='MultiChoice'>SharePoint 2016</Value>
                                                </Eq>";
                        }
                    }
                    if ((platforms & TargetPlatform.SharePoint2013) == TargetPlatform.SharePoint2013)
                    {
                        if (!String.IsNullOrEmpty(platformsCAMLFilter))
                        {
                            platformsCAMLFilter = @"<Or>" +
                                                  platformsCAMLFilter + @"
                                                        <Eq>
                                                            <FieldRef Name='PnPProvisioningTemplatePlatform' />
                                                            <Value Type='MultiChoice'>SharePoint 2013</Value>
                                                        </Eq>
                                                    </Or>";
                        }
                        else
                        {
                            platformsCAMLFilter = @"<Eq>
                                                    <FieldRef Name='PnPProvisioningTemplatePlatform' />
                                                    <Value Type='MultiChoice'>SharePoint 2013</Value>
                                                </Eq>";
                        }
                    }

                    try
                    {
                        List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningTemplates);

                        // Get only Provisioning Templates documents with the specified Scope
                        CamlQuery query = new CamlQuery();
                        query.ViewXml =
                            @"<View>
                        <Query>
                            <Where>" +
                            (!String.IsNullOrEmpty(platformsCAMLFilter) ? " < And>" : String.Empty) + @"
                                    <And>
                                        <Eq>
                                            <FieldRef Name='PnPProvisioningTemplateScope' />
                                            <Value Type='Choice'>" + scope.ToString() + @"</Value>
                                        </Eq>
                                        <Eq>
                                            <FieldRef Name='ContentType' />
                                            <Value Type=''Computed''>PnPProvisioningTemplate</Value>
                                        </Eq>
                                    </And>" + platformsCAMLFilter +
                            (!String.IsNullOrEmpty(platformsCAMLFilter) ? "</And>" : String.Empty) + @"                                
                            </Where>
                        </Query>
                        <ViewFields>
                            <FieldRef Name='Title' />
                            <FieldRef Name='PnPProvisioningTemplateScope' />
                            <FieldRef Name='PnPProvisioningTemplatePlatform' />
                            <FieldRef Name='PnPProvisioningTemplateSourceUrl' />
                        </ViewFields>
                    </View>";

                        ListItemCollection items = list.GetItems(query);
                        context.Load(items,
                                     includes => includes.Include(i => i.File,
                                                                  i => i[PnPPartnerPackConstants.PnPProvisioningTemplateScope],
                                                                  i => i[PnPPartnerPackConstants.PnPProvisioningTemplatePlatform],
                                                                  i => i[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]));
                        context.ExecuteQueryRetry();

                        web.EnsureProperty(w => w.Url);

                        // Configure the SharePoint Connector
                        var sharepointConnector = new SharePointConnector(context, web.Url,
                                                                          PnPPartnerPackConstants.PnPProvisioningTemplates);

                        foreach (ListItem item in items)
                        {
                            // Get the template file name and server relative URL
                            item.File.EnsureProperties(f => f.Name, f => f.ServerRelativeUrl);

                            TemplateProviderBase provider = null;

                            // If the target is a .PNP Open XML template
                            if (item.File.Name.ToLower().EndsWith(".pnp"))
                            {
                                // Configure the Open XML provider for SharePoint
                                provider =
                                    new XMLOpenXMLTemplateProvider(
                                        new OpenXMLConnector(item.File.Name, sharepointConnector));
                            }
                            else
                            {
                                // Otherwise use the .XML template provider for SharePoint
                                provider =
                                    new XMLSharePointTemplateProvider(context, web.Url,
                                                                      PnPPartnerPackConstants.PnPProvisioningTemplates);
                            }

                            // Determine the name of the XML file inside the PNP Open XML file, if any
                            var xmlTemplateFile = item.File.Name.ToLower().Replace(".pnp", ".xml");

                            // Get the template
                            ProvisioningTemplate template = provider.GetTemplate(xmlTemplateFile);

                            // Prepare the resulting item
                            var templateInformation = new ProvisioningTemplateInformation
                            {
                                // Scope = (TargetScope)Enum.Parse(typeof(TargetScope), (String)item[PnPPartnerPackConstants.PnPProvisioningTemplateScope], true),
                                TemplateSourceUrl = item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] != null ? ((FieldUrlValue)item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]).Url : null,
                                TemplateFileUri   = String.Format("{0}/{1}/{2}", web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates, item.File.Name),
                                TemplateImageUrl  = template.ImagePreviewUrl,
                                DisplayName       = template.DisplayName,
                                Description       = template.Description,
                            };

                            #region Determine Scope

                            String targetScope;
                            if (template.Properties.TryGetValue(PnPPartnerPackConstants.TEMPLATE_SCOPE, out targetScope))
                            {
                                if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_PARTIAL, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Scope = TargetScope.Partial;
                                }
                                else if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_WEB, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Scope = TargetScope.Web;
                                }
                                else if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_SITE, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Scope = TargetScope.Site;
                                }
                            }

                            #endregion

                            #region Determine target Platforms

                            String spoPlatform, sp2016Platform, sp2013Platform;
                            if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SPO, out spoPlatform))
                            {
                                if (spoPlatform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Platforms |= TargetPlatform.SharePointOnline;
                                }
                            }
                            if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SP2016, out sp2016Platform))
                            {
                                if (sp2016Platform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Platforms |= TargetPlatform.SharePoint2016;
                                }
                            }
                            if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SP2013, out sp2013Platform))
                            {
                                if (sp2013Platform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    templateInformation.Platforms |= TargetPlatform.SharePoint2013;
                                }
                            }

                            #endregion

                            // If we don't have a search text
                            // or we have a search text and it is contained either
                            // in the DisplayName or in the Description of the template
                            if ((!String.IsNullOrEmpty(searchText) &&
                                 ((!String.IsNullOrEmpty(template.DisplayName) && template.DisplayName.ToLower().Contains(searchText.ToLower())) ||
                                  (!String.IsNullOrEmpty(template.Description) && template.Description.ToLower().Contains(searchText.ToLower())))) ||
                                String.IsNullOrEmpty(searchText))
                            {
                                // Add the template to the result
                                result.Add(templateInformation);
                            }
                        }
                    }
                    catch (ServerException)
                    {
                        // In case of any issue, ignore the failing templates
                    }
                }
            }

            CacheItemPolicy policy = new CacheItemPolicy
            {
                Priority           = CacheItemPriority.Default,
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30), // Cache results for 30 minutes
                RemovedCallback    = (args) =>
                {
                    if (args.RemovedReason == CacheEntryRemovedReason.Expired)
                    {
                        var removedKey   = args.CacheItem.Key;
                        var searchInputs = JsonConvert.DeserializeObject <SharePointSearchCacheKey>(removedKey);

                        var newItem = SearchProvisioningTemplatesInternal(
                            searchInputs.SearchText,
                            searchInputs.Platforms,
                            searchInputs.Scope,
                            removedKey);
                    }
                },
            };

            Cache.Set(cacheKey, result, policy);

            return(result);
        }
        public ProvisioningTemplateInformation[] GetLocalProvisioningTemplates(string siteUrl, TargetScope scope)
        {
            List <ProvisioningTemplateInformation> result =
                new List <ProvisioningTemplateInformation>();

            // Retrieve the Root Site Collection URL
            siteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(siteUrl);

            // Connect to the Infrastructural Site Collection
            using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
            {
                // Get a reference to the target library
                Web web = context.Web;

                try
                {
                    List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningTemplates);

                    // Get only Provisioning Templates documents with the specified Scope
                    CamlQuery query = new CamlQuery();
                    query.ViewXml =
                        @"<View>
                        <Query>
                            <Where>
                                <And>
                                    <Eq>
                                        <FieldRef Name='PnPProvisioningTemplateScope' />
                                        <Value Type='Choice'>" + scope.ToString() + @"</Value>
                                    </Eq>
                                    <Eq>
                                        <FieldRef Name='ContentType' />
                                        <Value Type=''Computed''>PnPProvisioningTemplate</Value>
                                    </Eq>
                                </And>
                            </Where>
                        </Query>
                        <ViewFields>
                            <FieldRef Name='Title' />
                            <FieldRef Name='PnPProvisioningTemplateScope' />
                            <FieldRef Name='PnPProvisioningTemplateSourceUrl' />
                        </ViewFields>
                    </View>";

                    ListItemCollection items = list.GetItems(query);
                    context.Load(items,
                                 includes => includes.Include(i => i.File,
                                                              i => i[PnPPartnerPackConstants.PnPProvisioningTemplateScope],
                                                              i => i[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]));
                    context.ExecuteQueryRetry();

                    web.EnsureProperty(w => w.Url);

                    foreach (ListItem item in items)
                    {
                        // Configure the XML file system provider
                        XMLTemplateProvider provider =
                            new XMLSharePointTemplateProvider(context, web.Url,
                                                              PnPPartnerPackConstants.PnPProvisioningTemplates);

                        item.File.EnsureProperties(f => f.Name, f => f.ServerRelativeUrl);

                        ProvisioningTemplate template = provider.GetTemplate(item.File.Name);

                        result.Add(new ProvisioningTemplateInformation
                        {
                            Scope             = (TargetScope)Enum.Parse(typeof(TargetScope), (String)item[PnPPartnerPackConstants.PnPProvisioningTemplateScope], true),
                            TemplateSourceUrl = item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] != null ? ((FieldUrlValue)item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]).Url : null,
                            TemplateFileUri   = String.Format("{0}/{1}/{2}", web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates, item.File.Name),
                            TemplateImageUrl  = template.ImagePreviewUrl,
                            DisplayName       = template.DisplayName,
                            Description       = template.Description,
                        });
                    }
                }
                catch (ServerException)
                {
                    // In case of any issue, ignore the local templates
                }
            }

            return(result.ToArray());
        }
예제 #5
0
        internal static IEnumerable<ProvisioningTemplateInformation> SearchTemplates(string searchKey, TargetPlatform targetPlatforms, TargetScope targetScopes)
        {
            var targetPlatformsString = targetPlatforms.ToString();
            var targetScopesString = targetScopes.ToString();
            searchKey = searchKey != null ? System.Web.HttpUtility.UrlEncode(searchKey) : "";
            var jsonSearchResult =
                HttpHelper.MakeGetRequestForString(
                    $"{BaseTemplateGalleryUrl}/api/SearchTemplates?searchText={searchKey}&Platform={System.Web.HttpUtility.UrlEncode(targetPlatformsString)}&Scope={System.Web.HttpUtility.UrlEncode(targetScopesString)}");

            if (!string.IsNullOrEmpty(jsonSearchResult))
            {
                // Convert from JSON to a typed array
                var searchResultItems =
                    JsonConvert.DeserializeObject<PnPTemplatesGalleryResultItem[]>(jsonSearchResult);

                var result = (from r in searchResultItems
                              select new ProvisioningTemplateInformation
                              {
                                  Id = r.Id,
                                  DisplayName = r.Title,
                                  Description = r.Abstract,
                                  TemplateFileUri = r.TemplatePnPUrl,
                                  TemplateImageUrl = r.ImageUrl,
                                  Scope = r.Scopes,
                                  Platforms = r.Platforms,
                              }).ToArray();
                return result;
            }
            return null;
        }
예제 #6
0
        private async Task RunAnalyzer(TargetScope targetScope)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var dte2    = (DTE2)Package.GetGlobalService(typeof(SDTE));
            var project = dte2.ActiveDocument?.ProjectItem?.ContainingProject;

            if (project == null)
            {
                return;
            }

            var propertyProvider = CreateProjectPropertyProvider(project, OptionsProvider);
            await propertyProvider.LoadProperties();

            _outputLogger.ActivateWindow();
            string    publishPath = null;
            JitTarget jitTarget;

            if (targetScope.RequiresBuild)
            {
                try
                {
                    if (!propertyProvider.IsOptimized)
                    {
                        await ShowError(
                            "The current build configuration does not have the \"Optimize code\" flag set and is therefore not suitable for analysing the JIT compiler.\r\n\r\nPlease enable the the \"Optimize code\" flag (under Project Properties -> Build) or switch to a non-debug configuration (e.g. 'Release') before running the Inlining Analyzer.");

                        return;
                    }
                }
                catch (Exception)
                {
                }

                _outputLogger.WriteText("Building " + project.Name + "...");

                string configurationName = project.ConfigurationManager.ActiveConfiguration.ConfigurationName;
                dte2.Solution.SolutionBuild.BuildProject(configurationName, project.UniqueName, true);
                if (dte2.Solution.SolutionBuild.LastBuildInfo != 0)
                {
                    _outputLogger.WriteText("Build failed.");
                    return;
                }

                _outputLogger.ActivateWindow();

                jitTarget = new JitTarget(DetermineTargetPlatform(propertyProvider), propertyProvider.TargetRuntime, OptionsProvider.NetCoreVersion);

                if (ProjectPublisher.IsPublishingNecessary(propertyProvider))
                {
                    var publisher = new ProjectPublisher(jitTarget, configurationName, propertyProvider, _outputLogger);
                    if (!await Task.Run(() => publisher.Publish()))
                    {
                        return;
                    }
                    publishPath = publisher.PublishPath;
                }
            }
            else
            {
                // TODO: read target platform from assembly file
                jitTarget = new JitTarget(DetermineTargetPlatform(propertyProvider), OptionsProvider.PreferredRuntime, OptionsProvider.NetCoreVersion);
            }
            string assemblyFile = GetAssemblyPath(propertyProvider, publishPath, targetScope);

            if (assemblyFile == null)
            {
                return;
            }

            _statusBarLogger.SetText("Running Inlining Analyzer on " + project.Name);
            _statusBarLogger.StartProgressAnimation();

            _outputLogger.WriteText("");
            _outputLogger.WriteText("Starting Inlining Analyzer...");
            if (!string.IsNullOrEmpty(propertyProvider.TargetFramework))
            {
                _outputLogger.WriteText("TargetFramework: " + propertyProvider.TargetFramework);
            }
            _outputLogger.WriteText("Assembly: " + assemblyFile);
            _outputLogger.WriteText("Runtime: " + jitTarget.Runtime);
            _outputLogger.WriteText("Platform: " + jitTarget.Platform);
            if (jitTarget.Runtime == TargetRuntime.NetCore)
            {
                _outputLogger.WriteText(".NET Core Version: " + (jitTarget.HasSpecificNetCoreVersion ? jitTarget.NetCoreVersion : "Latest"));
            }
            _outputLogger.WriteText(targetScope.ToString());
            _outputLogger.WriteText("");

            try
            {
                var runner = new JitRunner(assemblyFile, jitTarget, targetScope, _outputLogger, new JitHostPathResolver());
                AnalyzerModel.CallGraph = await Task.Run(() => runner.Run());

                _outputLogger.WriteText("Finished Inlining Analyzer");
            }
            catch (JitCompilerException jitException)
            {
                await ShowError(jitException.Message);
            }
            catch (Exception ex)
            {
                _outputLogger.WriteText(ex.ToString());
                await ShowError("Jit Compilation failed with errors. Check the Inlining Analyzer Output Window for details.");
            }
            finally
            {
                if (publishPath != null)
                {
                    try
                    {
                        Directory.Delete(publishPath, true);
                    }
                    catch (Exception) { }
                }
            }
            _statusBarLogger.StopProgressAnimation();
            _statusBarLogger.Clear();
        }