public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
 {
     _compilation = compilation;
     _scope = scope;
     _name = fullyQualifiedName;
     _index = 0;
 }
 public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
 {
     _compilation = compilation;
     _scope       = scope;
     _name        = fullyQualifiedName;
     _index       = 0;
 }
 public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
 {
     this.compilation = compilation;
     this.scope = scope;
     this.name = fullyQualifiedName;
     this.index = 0;
 }
Example #4
0
        private async void StartForScopeMenuItemCallback(object sender, EventArgs e)
        {
            var dte2    = (DTE2)Package.GetGlobalService(typeof(SDTE));
            var project = dte2.ActiveDocument?.ProjectItem?.ContainingProject;

            if (project == null)
            {
                return;
            }

            var selection  = (TextSelection)dte2.ActiveDocument.Selection;
            var filename   = dte2.ActiveDocument.FullName;
            var documentId = Workspace.CurrentSolution.GetDocumentIdsWithFilePath(filename);

            if (documentId.IsEmpty)
            {
                return;
            }

            var document      = Workspace.CurrentSolution.GetDocument(documentId[0]);
            var semanticModel = await document.GetSemanticModelAsync();

            var syntaxTree = await document.GetSyntaxTreeAsync();

            TargetScope targetScope = TargetScopeResolver.GetTargetScope(semanticModel, syntaxTree, selection.CurrentLine, selection.CurrentColumn);

            if (targetScope == null)
            {
                ShowError("Could not determine selected Scope (Method or Class).");
                return;
            }

            await RunAnalyzer(targetScope);
        }
Example #5
0
 public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
 {
     this.compilation = compilation;
     this.scope       = scope;
     this.name        = fullyQualifiedName;
     this.index       = 0;
 }
Example #6
0
 public JitRunner(string assemblyFile, JitTarget jitTarget, TargetScope targetScope, ILogger outputLogger, IJitHostPathResolver pathResolver, bool recordEventDetails = false)
 {
     _assemblyFile       = assemblyFile;
     _jitTarget          = jitTarget;
     _targetScope        = targetScope;
     _outputLogger       = outputLogger;
     _pathResolver       = pathResolver;
     _recordEventDetails = recordEventDetails;
 }
Example #7
0
        /// <summary>
        /// Converts targets of the given scope into a string value for persisting</summary>
        /// <param name="scope">Target scope</param>
        /// <returns>String representation of targets</returns>
        protected virtual string SerializeTargets(TargetScope scope)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            XmlElement root = xmlDoc.CreateElement("TcpTargets");

            xmlDoc.AppendChild(root);
            try
            {
                foreach (TcpIpTargetInfo target in m_targets)
                {
                    if (target.Scope != scope)
                    {
                        continue;
                    }

                    XmlElement elem = xmlDoc.CreateElement("TcpTarget");
                    elem.SetAttribute("name", target.Name);
                    elem.SetAttribute("platform", target.Platform);
                    elem.SetAttribute("endpoint", target.Endpoint);
                    elem.SetAttribute("protocol", target.Protocol);
                    if (scope != TargetScope.PerApp)
                    {
                        elem.SetAttribute("provider", Id);
                    }
                    if (target.FixedPort > 0)
                    {
                        elem.SetAttribute("fixedport", target.FixedPort.ToString());
                    }

                    root.AppendChild(elem);
                }

                if (xmlDoc.DocumentElement.ChildNodes.Count == 0)
                {
                    xmlDoc.RemoveAll();
                }
            }
            catch
            {
                xmlDoc.RemoveAll();
            }

            return(xmlDoc.InnerXml);
        }
Example #8
0
        /// <summary>
        /// Deserializes target objects from a string value</summary>
        /// <param name="value">String representation of targets</param>
        /// <param name="scope">Target scope</param>
        protected virtual void DeserializeTargets(string value, TargetScope scope)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(value);
            XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("TcpTargets/TcpTarget");

            if (nodes == null || nodes.Count == 0)
            {
                return;
            }

            foreach (XmlElement elem in nodes)
            {
                if (scope != TargetScope.PerApp)
                {
                    var provider = elem.GetAttribute("provider");
                    if (provider != Id)
                    {
                        continue;
                    }
                }
                var tcpTarget = new TcpIpTargetInfo
                {
                    Name     = elem.GetAttribute("name"),
                    Platform = elem.GetAttribute("platform"),
                    Endpoint = elem.GetAttribute("endpoint"),
                    Protocol = elem.GetAttribute("protocol"),
                    Scope    = scope,
                };
                int fixedPort = 0;
                if (int.TryParse(elem.GetAttribute("fixedport"), out fixedPort))
                {
                    tcpTarget.FixedPort = fixedPort;
                }
                m_targets.Add(tcpTarget);
            }

            foreach (var targetConsumer in TargetConsumers)
            {
                targetConsumer.TargetsChanged(this, m_targets);
            }
        }
Example #9
0
        internal static ImmutableArray <ISymbol> ResolveTargetSymbols(
            Compilation compilation,
            string target,
            TargetScope scope
            )
        {
            switch (scope)
            {
            case TargetScope.Namespace:
            case TargetScope.Type:
            case TargetScope.Member:
                return(new TargetSymbolResolver(compilation, scope, target).Resolve(out _));

            case TargetScope.NamespaceAndDescendants:
                return(ResolveTargetSymbols(compilation, target, TargetScope.Namespace));

            default:
                return(ImmutableArray <ISymbol> .Empty);
            }
        }
Example #10
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();
        }
Example #11
0
 public BaseReadingHandler(TargetScope scope)
     : base(scope)
 {
 }
        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());
        }
 public ProvisioningTemplateInformation[] GetGlobalProvisioningTemplates(TargetScope scope)
 {
     return(GetLocalProvisioningTemplates(PnPPartnerPackSettings.InfrastructureSiteUrl, scope));
 }
Example #14
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);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ReadingHandler"/> with the specified scope of
 /// MIDI data to handle.
 /// </summary>
 /// <param name="scope">Scope of MIDI data to handle.</param>
 /// <remarks>
 /// It's important to set desired scope to avoid performance degradation. For example, if you want to handle
 /// start of file reading and start of track chunk reading, specify <paramref name="scope"/> to
 /// <c>TargetScope.File | TargetScope.TrackChunk</c>.
 /// </remarks>
 public ReadingHandler(TargetScope scope)
 {
     Scope = scope;
 }
        public virtual ProvisioningTemplateInformation[] SearchProvisioningTemplates(string searchText, TargetPlatform platforms, TargetScope scope)
        {
            String cacheKey = JsonConvert.SerializeObject(new SharePointSearchCacheKey
            {
                TemplatesProviderTypeName = this.GetType().Name,
                SearchText = searchText,
                Platforms  = platforms,
                Scope      = scope,
            });

            List <ProvisioningTemplateInformation> result = Cache[cacheKey] as List <ProvisioningTemplateInformation>;

            if (result == null)
            {
                result = SearchProvisioningTemplatesInternal(searchText, platforms, scope, cacheKey);
            }

            return(result.ToArray());
        }
 public ProvisioningTemplateInformation[] SearchProvisioningTemplates(string searchText, TargetPlatform platforms, TargetScope scope)
 {
     throw new NotImplementedException();
 }
Example #18
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);
        }
Example #19
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;
        }
Example #20
0
 public override ProvisioningTemplateInformation[] SearchProvisioningTemplates(string searchText, TargetPlatform platforms, TargetScope scope)
 {
     return(base.SearchProvisioningTemplates(searchText, platforms, scope));
 }
 private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope)
 => s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope);
Example #22
0
        private async Task RunAnalyzer(TargetScope targetScope)
        {
            var dte2    = (DTE2)Package.GetGlobalService(typeof(SDTE));
            var project = dte2.ActiveDocument?.ProjectItem?.ContainingProject;

            if (project == null)
            {
                return;
            }

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

            try
            {
                if (!propertyProvider.IsOptimized)
                {
                    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.ActivateWindow();
            _outputLogger.WriteText("Building " + project.Name + "...");

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

            _outputLogger.ActivateWindow();

            string    assemblyFile = GetAssemblyPath(propertyProvider);
            JitTarget jitTarget    = new JitTarget(DetermineTargetPlatform(propertyProvider), propertyProvider.TargetRuntime);

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

            _outputLogger.WriteText("Starting Inlining Analyzer...");
            _outputLogger.WriteText("Assembly: " + assemblyFile);
            _outputLogger.WriteText("Runtime: " + jitTarget.Runtime);
            _outputLogger.WriteText("Platform: " + jitTarget.Platform);
            if (targetScope == null)
            {
                _outputLogger.WriteText("Scope: All Types and Methods");
            }
            else
            {
                _outputLogger.WriteText($"Scope ({targetScope.ScopeType}): {targetScope.Name}");
            }

            _outputLogger.WriteText("");

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

                _outputLogger.WriteText("Finished Inlining Analyzer");
            }
            catch (JitCompilerException jitException)
            {
                ShowError(jitException.Message);
            }
            catch (Exception ex)
            {
                _outputLogger.WriteText(ex.ToString());
                ShowError("Jit Compilation failed with errors. Check the Inlining Analyzer Output Window for details.");
            }

            _statusBarLogger.StopProgressAnimation();
            _statusBarLogger.Clear();
        }
Example #23
0
 public Button(IInterface _interface, Texture2D sprite, Vector2 position, ButtonAnimation animationType, TargetScope targetScope)
     : this(_interface, sprite, position, animationType)
 {
     TargetScope = targetScope;
 }
 public override ProvisioningTemplateInformation[] SearchProvisioningTemplates(string searchText, TargetPlatform platforms, TargetScope scope)
 {
     return (base.SearchProvisioningTemplates(searchText, platforms, scope));
 }
Example #25
0
        private static string GetAssemblyPath(IProjectPropertyProvider propertyProvider, string publishPath, TargetScope targetScope)
        {
            try
            {
                if (targetScope.ScopeType != ScopeType.AssemblyFile)
                {
                    string outputFilename = propertyProvider.GetOutputFilename(publishPath);

                    if (File.Exists(outputFilename))
                    {
                        return(outputFilename);
                    }
                }

                return(GetUserSelectedAssemblyPath(propertyProvider));
            }
            catch (Exception)
            {
                return(GetUserSelectedAssemblyPath(propertyProvider));
            }
        }
        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);
        }
Example #27
0
        /// <summary>
        /// Converts targets of the given scope into a string value for persisting</summary>
        /// <param name="scope">Target scope</param>
        /// <returns>String representation of targets</returns>
        protected virtual string SerializeTargets( TargetScope scope)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            XmlElement root = xmlDoc.CreateElement("TcpTargets");
            xmlDoc.AppendChild(root);
            try
            {
                foreach (TcpIpTargetInfo target in m_targets)
                {
                    if (target.Scope != scope)
                        continue;

                    XmlElement elem = xmlDoc.CreateElement("TcpTarget");
                    elem.SetAttribute("name", target.Name);
                    elem.SetAttribute("platform", target.Platform);
                    elem.SetAttribute("endpoint", target.Endpoint);
                    elem.SetAttribute("protocol", target.Protocol);
                    if (scope != TargetScope.PerApp)
                        elem.SetAttribute("provider", Id);
                    if (target.FixedPort > 0)
                        elem.SetAttribute("fixedport", target.FixedPort.ToString());
                     
                    root.AppendChild(elem);
                }

                if (xmlDoc.DocumentElement.ChildNodes.Count == 0)
                    xmlDoc.RemoveAll();
            }
            catch
            {
                xmlDoc.RemoveAll();
            }

            return xmlDoc.InnerXml;
        }
 internal static IEnumerable<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope)
 {
     switch (scope)
     {
         case TargetScope.Namespace:
         case TargetScope.Type:
         case TargetScope.Member:
             {
                 var results = new List<ISymbol>();
                 new TargetSymbolResolver(compilation, scope, target).Resolve(results);
                 return results;
             }
         default:
             return SpecializedCollections.EmptyEnumerable<ISymbol>();
     }
 }
Example #29
0
        /// <summary>
        /// Deserializes target objects from a string value</summary>
        /// <param name="value">String representation of targets</param>
        /// <param name="scope">Target scope</param>
        protected virtual void DeserializeTargets(string value, TargetScope scope)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(value);
            XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("TcpTargets/TcpTarget");
            if (nodes == null || nodes.Count == 0)
                return;

            foreach (XmlElement elem in nodes)
            {
               
                if (scope != TargetScope.PerApp)
                {
                    var provider = elem.GetAttribute("provider");
                    if (provider != Id)
                        continue;
                }
                var tcpTarget = new TcpIpTargetInfo
                                    {
                                        Name = elem.GetAttribute("name"),
                                        Platform = elem.GetAttribute("platform"),
                                        Endpoint = elem.GetAttribute("endpoint"),
                                        Protocol = elem.GetAttribute("protocol"),
                                        Scope = scope,
                                    };
                int fixedPort = 0;
                if (int.TryParse(elem.GetAttribute("fixedport"), out fixedPort))
                {
                    tcpTarget.FixedPort = fixedPort;
                }
                m_targets.Add(tcpTarget);
            }

            foreach (var targetConsumer in TargetConsumers)
                targetConsumer.TargetsChanged(this, m_targets);
 
        }
Example #30
0
        internal static IEnumerable <ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope)
        {
            switch (scope)
            {
            case TargetScope.Namespace:
            case TargetScope.Type:
            case TargetScope.Member:
            {
                var results = new List <ISymbol>();
                new TargetSymbolResolver(compilation, scope, target).Resolve(results);
                return(results);
            }

            default:
                return(SpecializedCollections.EmptyEnumerable <ISymbol>());
            }
        }
Example #31
0
        public void Update(GameTime gameTime)
        {
            MouseState state = Mouse.GetState();

            if (state.X >= Position.X && state.X <= Position.X + Sprite.Width &&
                state.Y >= Position.Y && state.Y <= Position.Y + Sprite.Height)
            {
                if (!Animating && IsAtPosition(InitialPosition))
                {
                    AnimatingForward = true;
                }

                if (IsMouseDown && state.LeftButton == ButtonState.Released)
                {
                    if (Target != null)
                    {
                        Interface.SwitchTo(Target);
                    }
                    else if (TargetScope != null)
                    {
                        GameState target = TargetScope.Invoke();
                        if (target != null)
                        {
                            Interface.SwitchTo(target);
                        }
                    }
                }

                IsMouseDown = state.LeftButton == ButtonState.Pressed;

                IsMouseOver = true;
            }
            else
            {
                if (!Animating && !IsAtPosition(InitialPosition))
                {
                    AnimatingBackward = true;
                }

                IsMouseOver = false;
            }

            if (AnimatingForward)
            {
                Vector2 target = Position;
                switch (AnimationType)
                {
                case ButtonAnimation.GoRight:
                    target   = new Vector2(InitialPosition.X + 75, InitialPosition.Y);
                    Position = Vector2.Lerp(InitialPosition, target, (float)(ElapsedAnimationTime / AnimationTime));
                    break;
                }

                ElapsedAnimationTime += gameTime.ElapsedGameTime.TotalSeconds;
                if (IsAtPosition(target))
                {
                    ElapsedAnimationTime = 0;
                    AnimatingForward     = false;
                }
            }
            else if (AnimatingBackward)
            {
                Vector2 target = Position;
                switch (AnimationType)
                {
                case ButtonAnimation.GoRight:
                    target   = InitialPosition;
                    Position = Vector2.Lerp(Position, target, (float)(ElapsedAnimationTime / AnimationTime));
                    break;
                }

                ElapsedAnimationTime += gameTime.ElapsedGameTime.TotalSeconds;
                if (IsAtPosition(target))
                {
                    ElapsedAnimationTime = 0;
                    AnimatingBackward    = false;
                }
            }
        }