Roslyn, Could not load file or assembly System.Runtime - c#

I am new with Roslyn and I am trying to compile my first code at runtime.
The code compile(exe) without error but when i run it throught process.Start() in the concole output appers the error
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
I read that many other people had same problem but the solution here :
https://github.com/dotnet/core/issues/2082
not worked for me
This is the full code of my console app :
using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Extensions.DependencyModel;
using System.Linq;
namespace TestRoslyn
{
class Program
{
static string code = #"
using System;
namespace First
{
public class Program
{
public static void Main()
{" +
"Console.WriteLine(\"Hello, world!\");"
+ #"
}
}
}
";
static void Main(string[] args)
{
MetadataReference[] _ref = DependencyContext.Default.CompileLibraries
.SelectMany(cl => cl.ResolveReferencePaths())
.Select(asm => MetadataReference.CreateFromFile(asm))
.ToArray();
var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code));
var assemblyPath = Path.ChangeExtension(Path.GetTempFileName(), "exe");
var compilation = CSharpCompilation.Create(Path.GetFileName(assemblyPath))
.WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
.AddReferences(_ref)
.AddSyntaxTrees(syntaxTree);
var result = compilation.Emit(assemblyPath);
if (result.Success) // Compilation is Success
{
using (Process process = new Process())
{
process.StartInfo.FileName = assemblyPath;
process.Start(); // Here the error appears in the console window
}
}
else
{
System.Diagnostics.Debug.Write(string.Join(
Environment.NewLine,
result.Diagnostics.Select(diagnostic => diagnostic.ToString())
));
}
}
}
}
project file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.10.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="5.0.0" />
</ItemGroup>
</Project>
Can someone help me ?

Related

Error using the MSBuild.CodeAnalysis apis to analyze a C# project?

I am attempting to build a tool (using C# and .NET 7.0, Visual Studio 2022) that will analyze another C# project. I added the MSBuild.Locator package and invoked it with MSBuildLocator.RegisterDefaults(). However, when I attempt to actually open the project to be analyzed, I get the following error:
Here is the source code of the tool:
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace AnalysisTool
{
class Program
{
public static async Task DoActualWork()
{
var workspace = MSBuildWorkspace.Create();
workspace.LoadMetadataForReferencedProjects = true;
workspace.WorkspaceFailed += OnWorkspaceFailed;
// Error occurs here
var project = await workspace.OpenProjectAsync(
#"C:\Path\To\OtherProject.csproj");
var compilation = await project.GetCompilationAsync();
}
public static async Task Main(string[] args)
{
var vsAvail = MSBuildLocator.QueryVisualStudioInstances().ToList();
MSBuildLocator.RegisterDefaults();
await DoActualWork();
}
private static void OnWorkspaceFailed(object sender,Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs e)
{
if (e.Diagnostic.Kind == Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure)
{
Console.WriteLine(e.Diagnostic.ToString());
}
}
}
}
And the analysis tool's associated project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RollForward>Major</RollForward>
<OutDir>..\Bin\</OutDir>
<OutputPath>$(OutDir)</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Locator" Version="1.5.5" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Features" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Features" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.4.0" />
<PackageReference Include="NuGet.ProjectModel" Version="6.4.0" />
</ItemGroup>
</Project>
I've tried walking it back to .NET 5.0, with the same error. I'd appreciate any help.

OpenXml throws a different exception given identical code and similar build configuration for two distinct solutions. Why?

Suppose I have two separate solutions in Visual Studio 2019:
openxml-exceptions.sln
openxml-exceptions-reference.sln
openxml-exceptions.sln
This solution contains two projects:
basic-example: A class library
call-basic-example: A console app
basic-example
The project file is as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PlatformTarget>AnyCPU</PlatformTarget>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace>basic_example</RootNamespace>
<ImplicitUsings>disable</ImplicitUsings>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.14.0" />
</ItemGroup>
</Project>
The project also contains SpreadsheetWriterExample.cs:
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text;
namespace basic_example
{
public class SpreadSheetWriterExample
{
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
Console.WriteLine("creating spreadsheet document");
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
{
spreadsheetDocument.Close();
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("DirectoryNotFoundException");
}
catch (ArgumentException)
{
Console.WriteLine("ArgumentException");
}
catch (IOException e)
{
Console.WriteLine("IOException");
}
}
public static void Run()
{
CreateSpreadsheetWorkbook("asd\\da*dw.xlsx");
}
}
}
call-basic-example
The project file is as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>call_basic_example</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\basic-example\basic-example.csproj" />
</ItemGroup>
</Project>
The project also contains Program.cs:
using System;
using basic_example;
namespace call_basic_example
{
class Program
{
static void Main(string[] args)
{
SpreadSheetWriterExample.Run();
}
}
}
openxml-exceptions-reference.sln
This solution contains one project:
basic-example: A console app
basic-example
The project file is as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<PlatformTarget>AnyCPU</PlatformTarget>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace>basic_example</RootNamespace>
<ImplicitUsings>disable</ImplicitUsings>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.14.0" />
</ItemGroup>
</Project>
The project also includes SpreadSheetWriterExample.cs:
using System;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text;
namespace basic_example
{
public class SpreadSheetWriterExample
{
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
Console.WriteLine("creating spreadsheet document");
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
{
spreadsheetDocument.Close();
}
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("DirectoryNotFoundException");
}
catch (ArgumentException)
{
Console.WriteLine("ArgumentException");
}
catch (IOException e)
{
Console.WriteLine("IOException");
}
}
public static void Main()
{
CreateSpreadsheetWorkbook("asd\\da*dw.xlsx");
}
}
}
Question:
When I build and run openxml-exceptions.sln with call-basic-example as the startup project, I get DirectoryNotFoundException in the output.
When I build and run openxml-exceptions-reference.sln I get ArgumentException in the output.
I am using the following version of Visual Studio:
Given that I am using the exact same framework version in the class library of openxml-exceptions.sln and the console app of openxml-exceptions-reference.sln and the exact same version of OpenXml, I cannot wrap my head around why the thrown and caught error are different for each solution. As far as I can tell they should be exactly the same, but I am apparently overlooking something fundamental.
Why are the errors thrown different for each solution, given the exact same code, framework version and package version?

How to use 'Microsoft.CognitiveServices.Speech' namespace with Azure Functions?

I'm testing the Microsoft Azure Speech services, specifically trying to use Text-To-Speech. So, I'm using a free layer of Azure, and created a TimeTrigger Azure Function to read an e-mail, traverse through HTML and then call the Speech Service with the SDK Microsoft.CognitiveServices.Speech. I'm using the function.proj to load the nuget packages, loading S22.Imap and HtmlAgilityPack without any issues. But the speech package is triggering an exception:
Unable to load DLL 'Microsoft.CognitiveServices.Speech.core.dll' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E).
Am I able to use this package in an Azure Function? If so, what am I doing wrong?
I tried to remove the <PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.6.0" /> line from function.proj and deleted project.assets.json to reload the package but it didn't work.
This is my function.proj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="S22.Imap" Version="3.6.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.9" />
<PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.6.0" />
</ItemGroup>
</Project>
And this is my run.csx:
using System;
using S22.Imap;
using System.Net.Mail;
using HtmlAgilityPack;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using System.Diagnostics;
public static void Run(TimerInfo myTimer, ILogger log)
{
var username = "sample#gmail.com";
var password = "sample";
var subsKey = "sample";
using(ImapClient client = new ImapClient("imap.gmail.com", 993, username, password, AuthMethod.Login, true))
{
IEnumerable<uint> uids = client.Search(SearchCondition.From("sample#sample.com"));
IEnumerable<MailMessage> messages = client.GetMessages(uids);
log.LogInformation($"Count: {messages.Count()}.");
var msg = messages.FirstOrDefault();
if(msg != null)
{
var doc = new HtmlDocument();
doc.LoadHtml(msg.Body);
var paragraphs = doc.DocumentNode.Descendants()
.Where(x => x.Name == "p" && !string.IsNullOrEmpty(x.InnerText.Trim()))
.ToList();
var mailText = string.Empty;
foreach(var par in paragraphs)
mailText += par.InnerText;
if(!string.IsNullOrEmpty(mailText))
{
var config = SpeechConfig.FromSubscription(subsKey, "myregion");
config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3);
config.SpeechSynthesisLanguage = "pt-BR";
using (var synthesizer = new SpeechSynthesizer(config))
{
using (var result = synthesizer.SpeakTextAsync(mailText).Result)
{
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
//Do something with it
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
log.LogError($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
log.LogError($"CANCELED: ErrorCode={cancellation.ErrorCode}");
log.LogError($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
}
}
}
}
}
}
}
}
You could try to delete the function.proj then recreate one and add Microsoft.CognitiveServices.Speech at first.
Make sure the Microsoft.CognitiveServices.Speech.core.dll has been installed in win-x86 and win-x64. Please refer to this issue.
Mark as perquisite
When you publish mark Visual c++ 14 Runtime Libraries as prerequisite

How to get ExcelDNA work with R.Net

I am a C# and R beginner trying to run the example http://mockquant.blogspot.com/2011/07/yet-another-way-to-use-r-in-excel-for.html
<DnaLibrary RuntimeVersion="v4.0" Name="My First XLL" Language="CS">
<ExternalLibrary Path="R.NET.dll" />
<Reference Name="R.NET" />
<![CDATA[using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using RDotNet;
namespace CSLib
{
public class CSLib
{
static REngine rengine = null;
static CSLib()
{
// Set the folder in which R.dll locates.
REngine.SetDllDirectory(#"C:\Program Files\R\R-2.13.0\bin\i386");
rengine = REngine.CreateInstance("RDotNet", new[] { "-q" });
}
[ExcelFunction(Description = "get random numbers obey to normal distribution")]
public static double [] MyRnorm(int number)
{
return (rengine.EagerEvaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());
}
}
}
I have updated the link in the line SetDLLdirectory and I tried both 32bit and 64 bit versions of R (my cpu system is win7/64 bit)
I tried with earlier stable versions of RDotNet and googled for updates to the example code, eg. here:
https://groups.google.com/d/msg/exceldna/7_wr8pwuCZ0/GLKlVFjr6l8J
<DnaLibrary RuntimeVersion="v4.0" Name="My First XLL" Language="CS">
<ExternalLibrary Path="RDotNet.dll" />
<ExternalLibrary Path="RDotNet.NativeLibrary.dll" />
<Reference Name="RDotNet" />
<Reference Name="RDotNet.NativeLibrary" />
<![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using RDotNet;
namespace CSLib
{
public class CSLib
{
static REngine rengine = null;
static CSLib()
{
// Set the folder in which R.dll locates.
var oldPath = System.Environment.GetEnvironmentVariable("PATH");
var rPath = #"C:\Program Files\R\R-3.0.1\bin\x64";
var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
System.Environment.SetEnvironmentVariable("PATH", newPath);
rengine = REngine.CreateInstance("RDotNet");
}
[ExcelFunction(Description = "get random numbers obey to normal distribution")]
public static double [] MyRnorm(int number)
{
return (rengine.Evaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());
}
}
}
]]>
</DnaLibrary>
But I could not make it work...
After trying the older versions of r.net I also tried the newest version with the old code and then I tried to adaptthe example code present on R.Net website to the code above, presuming that initialisation of r engine now uses the path in the registry:
<DnaLibrary RuntimeVersion="v4.0" Name="R.NET" Description="R.NETExcel" Language="CS">
<Reference Path="RDotNet.NativeLibrary.dll" />
<Reference Path="RDotNet.dll" />
<Reference Path="DynamicInterop.dll" />
<![CDATA[
using System;
using System.IO;
using System.Linq;
using RDotNet;
using DynamicInterop;
namespace CSLib
{
public class CSLib
{
public static double[] MyRnorm(int number)
{
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();
engine.Initialize();
return (engine.Evaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());
engine.Dispose();
}
}
}
]]>
</DnaLibrary>
This is also giving no results. Excel function retrns #num error.
I am certain that ExcelDNA works when I comment out the section trying to connect to R and paste some other simple function like sum two values.
I believe that my problems may be related to new developments in RdotNet making the example code above obsolete (eg. it could be new way of initialising REngine instance). I am also wondering about the possibility of or 32 bit /64 bit conflict, that is why I also tried to make it work on 32 bit, win xp, dot.net 4.0 - with no results.
What then should be the right way of connecting ExcelDNA to the current R.NET version?
Thank you very much in advance for help.
These steps worked fine for me:
Ensure the R is installed. In my Windows "Add or Remove Programs" list I see "R for Windows 3.02.
Create a new "Class Library" project in Visual Studio.
In the NuGet package Manager Console, execute the commands:
PM> Install-Package Excel-DNA
PM> Install-Package R.NET.Community
Add the following code to the main .cs file:
using System;
using System.Linq;
using ExcelDna.Integration;
using ExcelDna.Logging;
using RDotNet;
namespace UsingRDotNet
{
public class AddIn : IExcelAddIn
{
public void AutoOpen()
{
MyFunctions.InitializeRDotNet();
}
public void AutoClose()
{
}
}
public static class MyFunctions
{
static REngine _engine;
internal static void InitializeRDotNet()
{
try
{
REngine.SetEnvironmentVariables();
_engine = REngine.GetInstance();
_engine.Initialize();
}
catch (Exception ex)
{
LogDisplay.WriteLine("Error initializing RDotNet: " + ex.Message);
}
}
public static double[] MyRnorm(int number)
{
return (_engine.Evaluate("rnorm(" + number + ")").AsNumeric().ToArray<double>());
}
public static object TestRDotNet()
{
// .NET Framework array to R vector.
NumericVector group1 = _engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
_engine.SetSymbol("group1", group1);
// Direct parsing from R script.
NumericVector group2 = _engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();
// Test difference of mean and get the P-value.
GenericVector testResult = _engine.Evaluate("t.test(group1, group2)").AsList();
double p = testResult["p.value"].AsNumeric().First();
return string.Format("Group1: [{0}], Group2: [{1}], P-value = {2:0.000}", string.Join(", ", group1), string.Join(", ", group2), p);
}
}
}
F5 to run the add-in in Excel.
Enter the formula =TestRDotNet()and=MyRNorm(5)`. Numbers appear in Excel.
I've added the "UsingRDotNet" project to the Excel-DNA Samples on GitHub.

Release DLL after creation in BuildManager

I have written an C# WPF Application to compile code during runtime. The application does basically the following steps
click button [Compile stuff]
Create code files via StreamWriter
Build code files using the Microsoft.Build.Execution.BuildManager class
Uses reflection to access the DLL file (Assembly.LoadFrom(filePath))
creates an instanz of the class contained in the dll (assembly.CreateInstance(NamespaceName + "." + ClassName))
I works fine, but only once (I need to restart the application to do it again)
This is what happens during the next execution
click button [Compile stuff]
Create code files via StreamWriter
Build code files using the Microsoft.Build.Execution.BuildManager class
->Produces an error saying that the DLL file is locked.
The process cannot access the file 'DLL\generatedflexform.dll' because
it is being used by another process
The problem doesn't occur when I leave out step 2 because then the code files are the same. Therefore the BuildManager doesn't recreate/copy the dll.
I need to figure out how to release the DLL after the BuildManager has done his job. This is because the code files are likely to change very often and otherwise i have to close and re-open the application for every code change.
EDIT: My first thought was that the BuildManager causes the locking but this is not the case.
I rather think the locking happens when I try to load the DLL. I will try the Shadow Copy think (as mentioned by #granadaCoder).
private Window LoadWindowFromDll(string filePathToDll)
{
var assembly = Assembly.LoadFrom(filePathToDll);
var window = assembly.CreateInstance(NamespaceName + "." + ClassName) as Window;
return window;
}
Solution:
I had to change the LoadWindowFromDllmethod to avoid the DLL locking
private Window LoadWindowFromDll(string filePathToDll)
{
byte[] readAllBytes = File.ReadAllBytes(filePathToDll);
Assembly assembly = Assembly.Load(readAllBytes);
var window = assembly.CreateInstance(NamespaceName + "." + ClassName) as Window;
return window;
}
But somehow the pdb file was locked which causes the build to failed when I try to execute it twice.
I fixed this behavior by adding one line to my build file:
<DebugType>none</DebugType>
Here is the complete build file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<AssemblyName>generatedflexform</AssemblyName>
<OutputPath>DLL\</OutputPath>
<OutputType>Library</OutputType>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Page Include="MyForm.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="MyForm.xaml.cs">
<DependentUpon>MyForm.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
And here comes the method which does the compile magic>
public Window BuildXamlWindowFromStrings(string xaml, string codeBehind)
{
//Erstellen der Codefiles (XAML und CodeBehind)
this.CreateCodeFile(codeBehind);
this.CreateXamlFile(xaml);
//Erstellen der project file
this.CreateProjectFile();
//Build der DLL
//using (var buildManager = BuildManager.DefaultBuildManager)
using (var buildManager = new BuildManager())
{
var result = buildManager.Build(this.CreateBuildParameters(), this.CreateBuildRequest());
if (result.OverallResult == BuildResultCode.Success)
{
return this.LoadWindowFromDll(FolderPath + DllRelativeFilePath + NamespaceName + DllFileExtension);
}
}
//Error handling
var stringbuilder = new StringBuilder();
using (var reader = new StreamReader(DebuggerLogFileName))
{
stringbuilder.Append(reader.ReadToEnd());
}
throw new CompilerException(stringbuilder.ToString());
}
Helper Methods:
private BuildParameters CreateBuildParameters()
{
var projectCollection = new ProjectCollection();
var buildLogger = new FileLogger { Verbosity = LoggerVerbosity.Detailed, Parameters = "logfile=" + DebuggerLogFileName };
var buildParameters = new BuildParameters(projectCollection) { Loggers = new List<ILogger>() { buildLogger } };
return buildParameters;
}
private BuildRequestData CreateBuildRequest()
{
var globalProperties = new Dictionary<string, string>();
var buildRequest = new BuildRequestData(FolderPath + ProjectFileName, globalProperties, null,
new string[] { "Build" }, null, BuildRequestDataFlags.ReplaceExistingProjectInstance);
return buildRequest;
}
Check out "Shadow Copying".
Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously.
http://msdn.microsoft.com/en-us/library/ms404279.aspx
See also:
http://gotchahunter.net/2010/12/net-how-do-you-load-an-assembly-programmatically-and-avoid-a-file-lock/
and
http://blogs.msdn.com/b/junfeng/archive/2004/02/09/69919.aspx

Categories

Resources