'InitializeComponent' does not exist in the current context - c#

I am using Roslyn to parse a very basic WPF solution. I setup a diagnostics and found the following errors:
MainWindow.xaml.cs(25,13): error CS0103: The name
'InitializeComponent' does not exist in the current context
error CS5001: Program does not contain a static 'Main' method suitable
for an entry point
Any idea how to solve this?
UPDATE
So I added a main method and now I am getting the following error:
App.xaml.cs(20,17): error CS1061: 'App' does not contain a definition
for 'InitializeComponent' and no extension method
'InitializeComponent' accepting a first argument of type 'App' could
be found (are you missing a using directive or an assembly reference?)
MainWindow.xaml.cs(25,13): error CS0103: The name
'InitializeComponent' does not exist in the current context
Here is the main method
public partial class App : Application
{
[STAThread]
public static void Main()
{
var app = new App();
app.InitializeComponent();
app.Run();
}
}

If you are loading this solution with code similar to the following:
var ws = MSBuildWorkspace.Create();
var solution = await ws.OpenSolutionAsync(path);
Then the problem is that you are not analyzing the code that should be generated from your .xaml files. This can be solved by changing the above code to:
var properties = new Dictionary<string, string> { ["DesignTimeBuild"] = "true" };
var ws = MSBuildWorkspace.Create(properties);
var solution = await ws.OpenSolutionAsync(path);
For more information, see also https://github.com/dotnet/roslyn/issues/2779

Related

Implement a simple IFindSaga

I have a simple IFindSaga implemented, I referred and followed the same steps that was provided in particular software document for SQL Persistence Saga Finding Logic. I'm getting an error at session.GetSagaData<SagaData> stating that: "SynchronizedStorageSession does not contain a definition for GetSagaData and no extension method GetSagaData accepting a first argument of type SynchronizedStorageSession could be found (are you missing a using directive or an assembly reference)." Please help me to solve this.
This is my code where I have implemented IFindSaga
public class TrackerFind : IFindSagas<SagaData>.Using<ITrackerData>
{
public Task<SagaData> FindBy(ITrackerData message, SynchronizedStorageSession session, ReadOnlyContextBag context)
{
return session.GetSagaData<SagaData>(
context: context,
whereClause: "JSON_VALUE(Data,'$.PaymentTransactionId') = #propertyValue",
appendParameters: (builder, append) =>
{
var parameter = builder();
parameter.ParameterName = "propertyValue";
parameter.Value = message.TrackerID;
append(parameter);
});
}
}
"GetSagaData" is an extension method which is part of "NserviceBus" namespace.
include following statement
using NServiceBus;
This worked for me. I am not getting that error now
use nuget
package NServiceBus.Persistence.Sql

Automatically resolving dependencies when compiling using Roslyn

I'm currently writing an application that currently loads a project via Roslyn's workspace API, turns a specified C# file into a syntax tree then creates an in memory assembly form it, then eventually extracts the IL.
This is all working fine, however as soon as I reference any external libraries within the said C# file, the compilation fails as Roslyn doesn't know where to resolve those references.
Here's a simplified version of what I'm currently doing:
MetadataReference[] metaDatareferences = {
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(DynamicAttribute).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(AssemblyMetadata).GetTypeInfo().Assembly.Location),
};
var sourceLanguage = new CSharpLanguage();
var syntaxTree = sourceLanguage.ParseText(sourceCode, SourceCodeKind.Regular);
var options = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Debug,
allowUnsafe: true
);
CSharpCompilation compilation = CSharpCompilation.Create("ExampleAssembly", options: options);
var stream = new MemoryStream();
var result = compilation.
AddReferences(metaDatareferences)
.AddSyntaxTrees(syntaxTree)
.Emit(stream);
// Success is false
if (!emitResult.Success)
{
foreach (var diagnostic in emitResult.Diagnostics)
{
Debug.WriteLine(diagnostic.ToString());
}
}
The output of the Debug.WriteLine is:
(1,7): error CS0246: The type or namespace name 'MediatR' could not be found (are you missing a using directive or an assembly reference?)
(9,32): error CS0246: The type or namespace name 'Mediator' could not be found (are you missing a using directive or an assembly reference?)
And the file my Roslyn project is reading is simply this:
using MediatR;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var mediator = new Mediator(null, null);
}
}
}
My question is, does Roslyn provide an API for automatically load any dependencies a file may have? I was hopeful that the Roslyn workspace would allow this to be done, but I've not been able to find anything.
If the MediatR console project is a project.json project, then you can use ProjectJsonWorkspace from "Microsoft.DotNet.ProjectModel.Workspaces": "1.0.0-preview2-1-003177". You can point it at your project.json and get a Compilation object, this will have done all the hard work for you of getting the project references, file references, etc... Then you can just emit your IL from here.
Here is an example:
var compilation = new ProjectJsonWorkspace(#"PathToYour\project.json").CurrentSolution.Projects.First().GetCompilationAsync().Result;
var stream = new MemoryStream();
var emitResult = compilation.Emit(stream);
Or if you need total control, you could continue to use CSharpCompilation.Create, copying in what you need from the compilation object here, and passing in a SyntaxTree.
Hope that helps.

System.Diagnostics.StackFrame.GetFrame(index) not found in mscorlib

I created two console applications, both targeting v4.5.2 of the .NET framework.
class MyDisposable : IDisposable
{
public void Dispose()
{
var callerName = new StackTrace().GetFrame(1)?.GetMethod()?.Name;
Console.WriteLine($"Dispose called by {callerName}.");
}
}
which run perfectly well.
In the other, I have the following, which are in effect the same.
return Disposable.Create(() =>
{
var stackFrame = new StackFrame();
var callingMethodBase = stackFrame.GetFrame(1)?.GetMethod();
...
});
But Visual Studio intellisense reports:
'StackFrame' does not contain a definition for
'GetFrame' and no extension method 'GetFrame'
accepting a first argument of type 'StackFrame'
could be found (are you missing a using
directive or an assembly reference?)
When I Go to Definition on the StackFramesclass, I see the method GetFrames is absent from the class declaration of the StackFrame class. Both the assembly versions for mscorlib are the same, i.e. v4.0.0.0.
Why is that?
In the first example you are using StackTrace, but in the second you are using StackFrame.
StackTrace has the method GetFrame(), but StackFrame doesn't.

namespace name soapcontext could not be found

I am building a form application that makes a call to a third party web service, but keep getting a "namespace name soapcontext could not be found" error.
I already added a web reference that points to the wsdl for the web service. Here is what I have:
private void btnGetInfo_Click(object sender, EventArgs e)
{
QTWebSvcsService svc = new qtref.QTWebSvcsService();
// The getVehicleInformation method accepts an AssetIdentifier and returns a
// VehicleInfo object. Instantiate them both.
qtref.AssetIdentifier ai = new qtref.AssetIdentifier();
qtref.VehicleInfo vi = new qtref.VehicleInfo();
// Replace these strings with valid company name, user name and password
string sUsername = "[usernasme]";
string sCompanyname = "[company]";
string sIdentity = sUsername + "#" + sCompanyname;
string sPassword = "[password]";
//This is where it fails
SoapContext requestContext = RequestSoapContext.Current;
}
Here is the exact error:
Error 1 The type or namespace name 'SoapContext' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Sophia Carter\Documents\Visual Studio 2010\Projects\DemoGetVehInf\DemoGetVehInf\Form1.cs 45 13 DemoGetVehInf
Based on the error, it looks like you need a using statement to include the namespace that contains SoapContext.
I don't know what namespace this would be but at the top of your code you will place something like:
using SoapContextNamespace;
I personally use Visual Studio with ReSharper. This combination of tools detects this error and offers a way to correct it with selecting something from the context menu when you right click. Depending on your tool set, you may find this or a similar option.

CompilationErrorException when including System.Linq in Roslyn CP2

I have downloaded the Roslyn CTP and have run across the following error.A CompilationErrorException is thrown when executing the line session.Execute(#"using System.Linq;"); with the following message:
(1,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
My code is:
namespace RoslynError
{
using System;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
internal class RoslynError
{
static void Main(string[] args)
{
var engine = new ScriptEngine();
Session session = engine.CreateSession();
session.Execute(#"using System.Collections;");
session.Execute(#"using System.Linq;");
Console.ReadKey();
}
}
}
I'm especially confused as to why the System.Linq line throws an error while System.Collections is fine.
The engine needs a reference to the assembly that the System.Linq namespace is in (System.Core.dll)
engine.AddReference(typeof(System.Linq.Enumerable).Assembly.Location);
This needs to be done before the session is created.

Categories

Resources