Quantcast
Channel: Microsoft "Roslyn" CTP forum
Viewing all 504 articles
Browse latest View live

AddUsing + Document.UpdateSyntaxRoot -- Buggy?

$
0
0

This isn't on the list of unimplemented features for Roslyn in C#, and I'm not positive I've found a bug either so I'm posting here.

In a code action, write the following

public CodeActionEdit GetEdit(CancellationToken cancellationToken)        {            var compilationUnit = (CompilationUnitSyntax)document.GetSyntaxRoot();            document = document.UpdateSyntaxRoot(compilationUnit.AddUsings(Syntax.UsingDirective(Syntax.ParseName("System.Linq"))));            //document = document.UpdateSyntaxRoot(compilationUnit.AddMembers(Syntax.ClassDeclaration("TESTCLASS")));            return new CodeActionEdit(document.UpdateSyntaxRoot(compilationUnit.AddUsings(Syntax.UsingDirective(Syntax.ParseName("System"))).NormalizeWhitespace()));        }


Your code action should successfully add System; and System.Linq;

Uncomment the commented out line and run again.. Only System; will be brought in.. The empty class will be created but it seems as though there is difficulty in calculating the delta between the UpdateSyntaxRoot calls when you use AddUsings (System.Linq; not brought in).

Also if you keep clicking the lightbulb you can get some pretty interesting behavior (again, whatever is keeping track here seems completely busted and you can see System.Linq; has not been added) : 

ALSO, my unit tests pass :P maybe not smart to get all high and mighty about my unit tests vs a team of MS developers but when I do editor.Actions.First().GetEdit().UpdatedSolution.GetDocument(documentId).GetText().ToString(); I'm getting the correct code back--it's only in true practice do I see these bugs.



Memory Leak in Solution.LoadStandAloneProject.

$
0
0

This is my second try at the same issue. There is a huge memory leak in Solution.LoadStandAloneProject. I am 99% sure this is caused by creating a new Microsoft.Build.Evaluation.ProjectCollection each time Solution.LoadStandAloneProject is called. The problem is that ProjectCollection doesn't clean itself up when the project is no longer used. To make things worse ProjectCollection.Dispose() also doesn't clean up. You have to call ProjectCollection.UnloadProject() or ProjectCollection.UnloadAllProjects() to release memory.

This memory leak is a huge issue for me because I am using Roslyn to parse 1,000's of projects. I have had to switch my utility to x64 just to keep it from running out of memory. Following is a trivial console application that you can copy into a Visual Studio project and run to see the memory growth. Just change the ProjectFileName to whatever you want. I'm pointing at the project being ran. After loading this trivial project 100 times it is using 66MB.

Please, please, please run this and see there is a memory leak. From looking at decompiled code, it looks like it shouldn't be too hard to fix this. In any case, here is the code:

using System;
using Roslyn.Services;

namespace ConsoleApplication1
{
    class Program
    {
        private const string ProjectFileName = @"C:\Users\Jeff\Documents\Visual Studio 2012\Projects\TestRoslynMemoryLeak2\TestRoslynMemoryLeak2.csproj";

        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++)
            {
                var project = Solution.LoadStandAloneProject(ProjectFileName);

                var memory = GC.GetTotalMemory(true);

                Console.WriteLine(i.ToString() + " - " + memory.ToString("N0"));
            }
        }
    }
}

Why is .NETFramework,Version=v4.0.AssemblyAttributes.cs part of the Project.Documents?

$
0
0

I've noticed that there appears to be a "compiler" generated file in any project I open in Roslyn. The file is named c:\Users\jlebert\AppData\Local\Temp\.NETFramework,Version=v4.0.AssemblyAttributes.cs.

The easiest example of this is in my unit tests, I'm creating a trivial project like this:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <AssemblyName>AssemblyName</AssemblyName>
    <ProjectGuid>96859EA3-A556-4A27-9796-95DDC0CE9747</ProjectGuid>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Code.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

I then load the project like this: Solution.LoadStandAloneProject(...path...). When I iterate through the Project.Documents, the last document is always the "compiler generated" one I mentioned above.

It seems odd that the file is there. Is it possible to get rid of the file from the Documents collection? If not, is it possible to have some kind of flag in the document information saying that it is "compiler generated"?

CodeIssue reports error but solution builds

$
0
0

Hi,

This is the first time I post on this forum, so firstly I want to tell you that you are doing a great job with Roslyn, keep up the good work!

Using the project template, I created a CodeIssue that reports errors when you code an empty catch block, when an exception is caught but not used in the catch, and when the caught exception is re-thrown (throw ex;).

Everything works beautifully and it's wonderful that Roslyn enables this kind of scenarios. My concern is that, even though the errors are reported in Visual Studio's Error List window, the solution builds just fine.

Is this by design or am I missing something to get the errors I issue in my extension to cause the build to fail?

Also, do you think that in the future something might be added to enable TFS Builds to incorporate CodeIssue extensions in the build process? (I would use that feature to replace CodeAnalysis rules, or to code new rules using Roslyn which validate the source code directly, something CodeAnalysis obviously can't do).

Thanks!

ICodeIssueProvider check vs solution for xml files or config files

$
0
0

I would like to have 2 possible scenarios in my ICodeIssueProvider:

  • The ability to have a config file with settings in my target solution/projects
  • The ability to check for the existence of other files types and possibly load them.

I am trying to learn how to use the features of roslyn, and one code issue provider I thought of was highlighting non virtual methods on classes that are to be used as proxies (I am mostly thinking persisted classes in NHibernate where the configuration of NH demands virtual methods)

I realise that this is quite an ambitious undertaking as there are many ways to configure NH, xml, Fluently...etc, but thought it would be a fun and useful tool.

My currently very basic impl, can find non virtual methods, yes, that was the easy bit!

Now, what I really want to do is search for files that are embedded and end in .hbm.xml.

I found a few threads indicating the differentiation between ISolution and the vs Solution and that I should potentially use EnvDTE. I have used this in the past and find it very hard to use and the documentation and example not to be that great.

Anyway, the first part was getting access to the IDE inside of my ICodeIssueProvider impl.

Is this really the way to go?

Any help would be much appreciated.

Also, thinking further ahead, I am thinking that there could be a performance hit looking for any classes that are persisted by NH. It appears that the same ICodeIssueProvider  instance is used for the life time of the VS instance, and whilst the node being looked at changes, I can cache against the ISolution each time if this makes sense?

Again, thoughts and help welcome.

Cheers

To get all function prototypes & member variables from a cs file

$
0
0
I need to get a list of all c# function prototypes , private member variables from around 2000 .cs file. I am using visual studio 2010. Tell me the better way to do it. Thanks in advance.

Roslyn : Is it a good choice for a strategic development ?

$
0
0
Hello

Roslyn is a major project extremely promising. I follows it with interest for several years now, even if I have not yet had the opportunity to make prototypes.

In the development of a framework tools based on WPF and WCF, I would like to develop an integrated editor in Visual Studio to significantly improve the productivity of our teams in the maintenance and development of the input modules.

Roslyn would obviously be the ideal tool for this editor. For cons, the development of this editor would cost us probably several hundred days of work: we can not afford to do the job at a loss: we must have good confidence on the sustainability of the underlying technical tools, and Roslyn would be the most important tool and it would be VERY difficult to replace if necessary.

My questions are as follows:

    * I did not find any reference or indication of the date of official integration into Visual Studio? Roslyn is what is present in VS 2014, 2016?
    * Is Roslyn is a strategic issue for Microsoft? If yes? Why? What are the projects planned integration term by Microsoft? Example: Will Roslyn be the new Microsoft compiler for all applications in .Net ?
    * How many developer at Microsoft are concerned with the development of this framework? es that the investment is moderate, important, VERY important (pledge of commitment and hope of sustainability )?
    * Is Roslyn is already used by Microsoft tools or other major? and if so? Which?

Thanks a lot for your advise and informations

Best Regards

LinqToWiki: A strongly typed library for accessing the Wikipedia API based on Roslyn

$
0
0

I'd like to introduce LinqToWiki: a library for accessing the Wikipedia API from .Net. Its main advantage is that it knows the API and is strongly-typed, which means it works well with IntelliSense and correctness is checked at compile time.

The way this is done is by using Roslyn to generate code based on the description the API provides about itself. (The generated code that's meant to be used by normal users doesn't require Roslyn.)

Any comments are welcome.


Run To Line and Return session

$
0
0

I am new to Roslyn, and not sure if this is a simple question.

We need to inject some kind of logic between lines of code. But these will-be-injected lines are generated dynamically and are for help analyzing data flow. 

The question is can we run a scripting engine to nth line of the code, then execute the dynamically generated code depending on session and host object. After running the code, execution should continue where it has left linewise.

What we are trying to do is similar to pex: To determine the required variable values for control flow to visit every Condition of every IfExpession.

if(a==b)
{
    if(c==d(b))
    {
        e = 5;
    }
}


Semantic info for annotated tree

$
0
0

Does adding SyntaxAnnotations cause loss of semantic info within SemanticModel?

When I do what follows:

var classAnnotation = new SyntaxAnnotation();

var newRoot = document.GetSyntaxRoot().ReplaceNode(
    classDeclaration,
    classDeclaration.WithAdditionalAnnotations(classAnnotation));

can I still ask semantic questions to the doument semantic model?

From what I understand, when the SyntaxTree is modified I lose all the data from compilation. Does the same apply to annotation process?

Instance symbols are visible from static methods in an InScope symbol lookup

$
0
0

If I do an Inscope symbol lookup from within a static method, I get results that include instance members of the same class.

For instance, the code below

public static void GetInScopeSymbols()
{
    var source = @"
class C
{
}
class Program
{
private void instance_Method(){}
private int instance_j = 0;
private static int static_i = 0;
public static void Main()
{
int j = 0; j += i;
// What symbols are in scope here?
}
}";
    var tree = SyntaxTree.ParseText(source);
    var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib");
    var compilation = Compilation.Create("MyCompilation",
        syntaxTrees: new[] { tree }, references: new[] { mscorlib });
    var model = compilation.GetSemanticModel(tree);

    // Get position of the comment above.
    var position = source.IndexOf("//");

    // Get 'all' symbols that are in scope at the above position. 
    ReadOnlyArray<Symbol> symbols = model.LookupSymbols(position);
    var results = string.Join("\r\n", symbols.Select(symbol => symbol.ToDisplayString()).OrderBy(s => s));

}


returns:

C
j
Microsoft
object.Equals(object)
object.Equals(object, object)
object.GetHashCode()
object.GetType()
object.MemberwiseClone()
object.ReferenceEquals(object, object)
object.ToString()
Program
Program.instance_j
Program.instance_Method()
Program.Main()
Program.static_i
System

Program.instance_j, Program.instance_Method() and other members of the object class shouldn't be visible from the static Main method.

This leads to an autocomplete menu I'm working on to display instance members when the user is working in a static method.

Is there a flag I can pass to Model.LookupSymbols to fix this?

Thanks!!

Get IDocument for SyntaxNode

$
0
0
What is the best and most readable way to obtain the IDocument instance that a SyntaxNode is defined in ? Should I iterate over all documents in my project/solution, and check whether my SyntaxNode belong to any of SyntaxTrees?

Redundant SyntaxKind parameter

$
0
0

Why do some Syntax.* factory methods require explicit SyntaxKind parameter, even if it is clear what kind of a node is being constructed?

Example is Syntax.MemberAccessExpression, where the first argument should be SyntaxKind.MemberAccessExpression.

WHy is this necessary ?

Observable and Roslyn

$
0
0

When trying to create an Observable in a Roslyn Session, I receive a CompilationErrorException:

(1,1): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Test code:

            var engine = new Roslyn.Scripting.CSharp.ScriptEngine();
            new[] {"System", "System.Core","System.Reactive.Core.dll", "System.Reactive.Interfaces.dll", "System.Reactive.Linq.dll", "System.Reactive.PlatformServices.dll"
                }.ToList().ForEach(z => engine.AddReference(z));
            var session = engine.CreateSession();

            session.Execute("System.Reactive.Linq.Observable.Start(() => { });");

What am I doing wrong?

Roslyn Statement Completion Service

$
0
0
I'm writing a language service that is going to use c# intellisense in certain parts of the language. From what I've found out, there should be a service in Roslyn that will give me completion items for c#. However, there's no mention of this in the official documentation so I'd like to ask, how do I go about using the intellisense service from my own VS Extension?

I tried what's described here http://social.msdn.microsoft.com/Forums/en-US/roslyn/thread/78e6f820-8f9f-4da9-8a47-d46f846b0a11 , with no success though. My guess is that this info is out of date (since Roslyn is still in development and the aforementioned thread is from 2011).

Can Roslyn be used in production -

$
0
0

Hello,

We have been using a mono compiler as a service in our customer solution. Is it possible to use Roslyn instead.

We understand its a ctp, if there is a new CTP/ or release we will move to that. We will not distribute it, we will download the CTP and install it and will have a notice stating that in the machine where we plan to use it.

IProject.AddDocument takes extremely long to finish

$
0
0

I'm trying to get statement completions by adding an in-memory IDocument file to an IProject instance of an existing project. It gives the desired result, but the method AddDocument takes a few seconds to complete. Is that normal? This is how I do it:

string completionSourceClassContent = @"namespace Consumer{class Program{static void Main(string[] args){}}}";

DTE _vsIde = GetActiveSolutionIde(); ISolution solution = Solution.Load(_vsIde.Solution.FullName); string activeDocumentProjectName =_vsIde.ActiveDocument.ProjectItem.ContainingProject.Name; IProject solutionProject = solution.Projects.FirstOrDefault(p => p.Name == activeDocumentProjectName); IDocument completionSourceClass = solutionProject.AddDocument("CodeCompletion.cs", completionSourceClassContent);

completionSourceClass.GetCompletionItemGroups(14, CompletionTriggerInfo.CreateInvokeCompletionTriggerInfo());


The solution that I load has only one MVC3 project and that project contains only a few files, so the project is very simple and small and yet, adding an in-memory document to it takes so long. Maybe the same can be done more efficiently?





Finding unused methods and remove it using Roslyn

$
0
0

I'm trying to find the unused methods in my project and remove it.

All the samples I find for Roslyn, talks about parsing a single file only. For me find the unused method I had to load and analyse the entire project.  I'm not able to find how to do that.

Or should I load the assembly and derive the unused methods from it?


cheers, :-) deepak

Roslyn directory?

$
0
0

I have a managed class library that makes use of (P/Invoke) a native dll. Everything works perfectly when a desktop application accesses the managed assembly (and, by extension, the native dll), but not the C# interactive window. It seems the native dll isn't being located by the runtime.

I've tried adding the native dll to the "Directory.GetCurrentDirectory()" being reported from the interactive window but that didn't fix the problem. Where can I put the dll so that Roslyn can find it?

-L

How does C# Interactive get documentation comments?

$
0
0

Hello,

I filed a bug report a while ago about Symbol.GetDocumentationComments() not working for PE symbols.

I observed in WebMatrix 2 that PE symbol documentation are not displayed in the intellisense pop-ups. (I believe this is caused by this bug), however, I also noticed that the PE symbol documentation are displayed in C# Interactive's intellisense pop-ups.

How does C# interactive get this information? Is it via Roslyn or some VS API?

Will this bug be fixed in the next CTP?

Thanks!

Viewing all 504 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>