Set Configuration when using Microsoft.Build.Evaluation.Project? - msbuild

I can build a project with the following
static bool Build()
{
var projectCollection = ProjectCollection.GlobalProjectCollection;
var project = projectCollection.LoadProject(websiteProject);
var fileLogger = new FileLogger();
fileLogger.Parameters = #"logfile=" + #"app_data\log.txt";
projectCollection.RegisterLogger(fileLogger);
bool result = project.Build();
projectCollection.UnregisterAllLoggers();
return result;
}
But I need to be able to set the build configuration to Release. I've had a look through the documentation, but either I'm missing it or there's not an easy way to set it.

I found the answer:
projectCollection.SetGlobalProperty("Configuration", "Release");

Related

How to add custom roslyn analyzer from locally placed DLL?

I have created a Roslyn Analyzer project which generates a nuget package and DLL of it. I want to use that DLL in a standalone code analysis project. How can i do that? For example i have following code:
MSBuildLocator.RegisterDefaults();
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var analyzer = //Here i want to load analyzer from DLL present locally.
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(analyzer.GetAnalyzersForAllLanguages());
var res = compWithAnalyzer.GetAllDiagnosticsAsync().Result;
errors.AddRange(res.Where(r => r.Severity == DiagnosticSeverity.Error).ToList());
}
I have tried following
var analyzer = new AnalyzerFileReference("Path to DLL", new AnalyzerAssemblyLoader());
But here AnalyzerAssemblyLoader shows error as it is inaccessible to to its protection level (class is internal).
Kindly suggest me if we can do this.
the .WithAnalyzers() option will allow you to pass an instance of an analyzer. If you're referencing the DLL locally, you can just create the analyzer like you would any other object and pass it to the compilation.
var analyzer = new MyAnalyzer();
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
If you're not referencing the assembly, but want to load it at runtime, you can use the usual System.Reflection based methods to get an instance of the analyzer:
var assembly = Assembly.LoadFrom(#"<path to assembly>.dll");
var analyzers = assembly.GetTypes()
.Where(t => t.GetCustomAttribute<DiagnosticAnalyzerAttribute>() is object)
.Select(t => (DiagnosticAnalyzer) Activator.CreateInstance(t))
.ToArray();
compWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzers));

Elastic Search NEST Self referencing loop detected for property

Using version 2.0.2 I just cannot find where to set the serializer settings for the Nest.JsonNetSerializer to avoid Self referencing loop detected exception.
And i guess that the documentation is not updated for version 2.
There is one PR in the NEST repo explaining how you can handle this situation in version 2.x.x.
Summary:
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connectionSettings => new MyJsonNetSerializer(connectionSettings))
.DefaultIndex(indexName)
.DisableDirectStreaming()
.PrettyJson();
public class MyJsonNetSerializer : JsonNetSerializer
{
public MyJsonNetSerializer(IConnectionSettingsValues settings) : base(settings)
{
}
protected override void ModifyJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings)
{
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}
}
Hope it helps.
Once again there are some significant changes to how this is handled in v.5.
I found this example in the tests and it worked for me...
/**=== Overriding Json.NET settings
*
* Overriding the default Json.NET behaviour in NEST is an expert behavior but if you need to get to the nitty gritty, this can be really useful.
*/
/**
* The easiest way is to create an instance of `SerializerFactory` that allows you to register a modification callback
* in the constructor
*/
public void EasyWay()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(
pool,
new HttpConnection(),
new SerializerFactory((jsonSettings, nestSettings) => jsonSettings.PreserveReferencesHandling = PreserveReferencesHandling.All));
var client = new ElasticClient(connectionSettings);
}
https://github.com/elastic/elasticsearch-net/blob/5.x/src/Tests/ClientConcepts/LowLevel/Connecting.doc.cs#L289

Why I'm getting all history revisions when querying for Iterations or Releases?

I'm working with Rally REST API for Java
I want get the list of actual Iterations and Releases
here is the snippet
JsonObject projects = new JsonObject();
QueryRequest queryProjects = new QueryRequest("release");
queryProjects.setPageSize(1);
queryProjects.setLimit(1000);
queryProjects.setFetch(new Fetch("_refObjectName","Name"));
QueryResponse queryResponse;
try {
queryResponse = restApi.query(queryProjects);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new ServiceException(e);
}
In result I'm getting the list with a lot of duplicates. After closer inspection it seems I'm getting all versions of object - for the same Iteration/Release I have multiple versions - I can see different "_objectVersion" attribute for such duplicates.
Why is it so?
Can you please help me with the query which will retrieve distinct list of Iterations / Releases - I'm interested in just latest versions.
I can filter it out in Java but have a feeling there is more 'proper' way of doing this. Also getting the list with whole object history is not the best for code performance.
Thanks for any help!
When Releases and Iterations are created in Rally in a top project there is an option to propagate them throughout the project hierarchy. For example, if you have top project P1 with child project P2 and grandchild projects P21 and P22, you may create 4 releases with the same name and the same start and release dates. They are not identical releases: they have ObjectID and _ref unique to them. Please verify if this applies to your scenario.
To limit release query to a specific project set request project. Here is an example that returns only three releases that I have in a top project: R1,R2, and R3. Note
String projectRef = "/project/12352608219";
that is used later in the code:
releaseRequest.setProject(projectRef);
Note also the commented out
//String workspaceRef = "/workspace/12352608129";
and
// releaseRequest.setWorkspace(workspaceRef);
If I switch the comments: comment out project reference and uncomment workspace reference I will get what you called duplicates: multiple R1, R2 and R3 releases.
public class FindReleases {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
//String workspaceRef = "/workspace/12352608129";
String applicationName = "RESTExampleFindReleasesByProject";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar and up
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("Name"));
releaseRequest.setLimit(1000);
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
// releaseRequest.setWorkspace(workspaceRef);
releaseRequest.setProject(projectRef);
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
if(numberOfReleasesInProject >0){
for (int i=0;i<numberOfReleasesInProject;i++){
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println(releaseJsonObject.get("Name"));
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}

Generate HBM files using mapping by code

I'm using NHibernate mapping by code and I'm creating the session factory in this way:
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
const bool executeScript = false;
var configuration = new Configuration();
configuration.DataBaseIntegration(c =>
{
c.Dialect<MsSql2005Dialect>();
c.ConnectionString =
ConfigurationManager.ConnectionStrings["ShopConnectionString"]
.ConnectionString;
c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
});
configuration.AddMapping(domainMapping);
_sessionFactory = configuration.BuildSessionFactory();
I need to get the corresponding HBM files.
How can I achieve that?
Two ways:-
//This will write all the XML into the bin/mappings folder
mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();
be careful of this method above as your asp.net app will recycle as changes are detected in your bin folder, another way is:-
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
//you could add a breakpoint here!
var mappingXml = mapping.AsString();
Use the AsString() extension method:
domainMapping.AsString()
It will give you the xml which you can save into a file. You can call that method e.g. before you build the SessionFactory.

Create XML representation of WCF binding instance

I'm trying to write code to convert a WCF wsHttpBinding to customBinding, using the method described on WSHttpBinding.CreateBindingElements Method
.
Binding wsHttpBinding = ...
BindingElementCollection beCollection = originalBinding.CreateBindingElements();
foreach (var element in beCollection)
{
customBinding.Elements.Add(element);
}
Once I have generated the custom binding, I want to generate an XML representation for that new custom binding. (The same XML representation that's found in an application's .config file).
Is there a way to do that?
(I'm aware of the tool referenced in this answer: https://stackoverflow.com/a/4217892/5688, but I need something I can call within an application and without depending on a service in the cloud)
The class I was looking for was System.ServiceModel.Description.ServiceContractGenerator
Exemple to generate a configuration for an instance of any kind of Binding:
public static string SerializeBindingToXmlString(Binding binding)
{
var tempConfig = Path.GetTempFileName();
var tempExe = tempConfig + ".exe";
var tempExeConfig = tempConfig + ".exe.config";
// [... create empty .exe and empty .exe.config...]
var configuration = ConfigurationManager.OpenExeConfiguration(tempExe);
var contractGenerator = new ServiceContractGenerator(configuration);
string bindingSectionName;
string configurationName;
contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
BindingsSection bindingsSection = BindingsSection.GetSection(contractGenerator.Configuration);
// this needs to be called in order for GetRawXml() to return the updated config
// (otherwise it will return an empty string)
contractGenerator.Configuration.Save();
string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
// [... delete the temporary files ...]
return xmlConfig;
}
This solution feels like a hack because of the need to generate empty temporary files, but it works.
Now I'll have to look for a way to have a fully in-memory instance of a System.Configuration.Configuration (maybe by writing my own implementation)
Added missing code parts:
// [... create empty .exe and empty .exe.config...]
// [... delete the temporary files ...]
public static string SerializeBindingToXmlString(Binding binding)
{
var tempConfig = System.IO.Path.GetTempFileName();
var tempExe = tempConfig + ".exe";
var tempExeConfig = tempConfig + ".exe.config";
using(System.IO.FileStream fs = new System.IO.FileStream(tempExe, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
}
using (System.IO.FileStream fs = new System.IO.FileStream(tempExeConfig, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
fs.SetLength(0);
using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)) {
sr.WriteLine("<?xml version= \"1.0\" encoding=\"utf-8\" ?>");
sr.WriteLine(#"<configuration />");
}
}
var configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(tempExe);
var contractGenerator = new System.ServiceModel.Description. ServiceContractGenerator(configuration);
string bindingSectionName;
string configurationName;
contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
var bindingsSection =System.ServiceModel.Configuration.BindingsSection.GetSection(contractGenerator.Configuration);
// this needs to be called in order for GetRawXml() to return the updated config
// (otherwise it will return an empty string)
contractGenerator.Configuration.Save();
string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
System.IO.File.Delete(tempExeConfig);
System.IO.File.Delete(tempExe);
return xmlConfig;
}