Using MSDeploy API to get a web server's dependencies - c#

I'm just getting to grips with the C# API for MSDeploy (Microsoft.Web.Deployment.dll), but I'm struggling to find a way that I can determine the dependencies for a given web server.
Basically, I'd like the C# equivalent of the following MSDeploy command line call:
msdeploy.exe -verb:getDependencies -source:webServer
I've tried the documentation, but I've had no luck. Can anybody point me in the right direction?

Having examined the MSDeploy executable in Reflector, it seems that the getDependencies operation is not exposed by the API (the method is internal).
So instead I've had to fall back on calling out to the command line, and processing the results:
static void Main()
{
var processStartInfo = new ProcessStartInfo("msdeploy.exe")
{
RedirectStandardOutput = true,
Arguments = "-verb:getDependencies -source:webServer -xml",
UseShellExecute = false
};
var process = new Process {StartInfo = processStartInfo};
process.Start();
var outputString = process.StandardOutput.ReadToEnd();
var dependencies = ParseGetDependenciesOutput(outputString);
}
public static GetDependenciesOutput ParseGetDependenciesOutput(string outputString)
{
var doc = XDocument.Parse(outputString);
var dependencyInfo = doc.Descendants().Single(x => x.Name == "dependencyInfo");
var result = new GetDependenciesOutput
{
Dependencies = dependencyInfo.Descendants().Where(descendant => descendant.Name == "dependency"),
AppPoolsInUse = dependencyInfo.Descendants().Where(descendant => descendant.Name == "apppoolInUse"),
NativeModules = dependencyInfo.Descendants().Where(descendant => descendant.Name == "nativeModule"),
ManagedTypes = dependencyInfo.Descendants().Where(descendant => descendant.Name == "managedType")
};
return result;
}
public class GetDependenciesOutput
{
public IEnumerable<XElement> Dependencies;
public IEnumerable<XElement> AppPoolsInUse;
public IEnumerable<XElement> NativeModules;
public IEnumerable<XElement> ManagedTypes;
}
Hopefully this is useful to anybody else that ever tries to do the same thing!

There actually is a way of getting there via the public API by using DeploymentObject.Invoke(string methodName, params object[] parameters).
When "getDependencies" is used for methodName, the method returns an XPathNavigator object:
DeploymentObject deplObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.WebServer, String.Empty);
var result = deplObj.Invoke("getDependencies") as XPathNavigator;
var xml = XDocument.Parse(result.InnerXml);

Related

Getting Value cannot be null. parameter name: source on release but not in debug

I'm creating a Revit plugin that reads and writes modelinformation to a database, and it all works fine in debug mode, but when I release the project and run Revit with the plugin outside visual studio, I'm getting an error when the plugin tries to read data from the database.
The code runs on DocumenetOpened event and looks like this:
public void application_DocumentOpenedEvent(object sender, DocumentOpenedEventArgs e)
{
UIApplication uiapp = new UIApplication(sender as Autodesk.Revit.ApplicationServices.Application);
Document doc = uiapp.ActiveUIDocument.Document;
//ModelGUID COMMAND
var command = new ModelCheckerCommandExec();
command.Execute(uiapp);
}
It then fails on the following line:
ModelsList = (DatabaseHelper.ReadNonAsync<RevitModel>())
.Where(m => m.ModelGUID == DataStores.ModelData.ModelGUID).ToList();
In this code block that gets executed:
public class ModelCheckerCommandExec : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
return Execute(commandData.Application);
}
public Result Execute(UIApplication uiapp)
{
Document doc = uiapp.ActiveUIDocument.Document;
Transaction trans = new Transaction(doc);
try
{
trans.Start("ModelGUID");
ModelGUIDCommand.GetAndSetGUID(doc);
trans.Commit();
var ModelsList = new List<RevitModel>();
ModelsList = (DatabaseHelper.ReadNonAsync<RevitModel>()).ToList();//.Where(m => m.ModelGUID == DataStores.ModelData.ModelGUID).ToList(); // Read method only finds models the are similar to the DataStore.ModelDate.DBId;
if (ModelsList.Count == 1)
{
trans.Start("DataFromDB");
doc.ProjectInformation.Name = ModelsList[0].ProjectName;
doc.ProjectInformation.Number = ModelsList[0].ModelNumber;
doc.ProjectInformation.Status = ModelsList[0].ModelStatus;
doc.ProjectInformation.IssueDate = ModelsList[0].ProjectIssueDate;
doc.ProjectInformation.ClientName = ModelsList[0].ClientName;
doc.ProjectInformation.Address = ModelsList[0].ProjectAddress;
doc.ProjectInformation.LookupParameter("Cadastral Data").Set(ModelsList[0].ProjectIssueDate);
doc.ProjectInformation.LookupParameter("Current Version").Set(ModelsList[0].CurrentVersion);
doc.ProjectInformation.BuildingName = ModelsList[0].BuildingName;
DataStores.ModelData.ModelManager1 = ModelsList[0].ModelManagerOne;
DataStores.ModelData.ModelManager1Id = ModelsList[0].ModelManagerOneId;
DataStores.ModelData.ModelManager2 = ModelsList[0].ModelManagerTwo;
DataStores.ModelData.ModelManager2Id = ModelsList[0].ModelManagerTwoId;
trans.Commit();
}
return Result.Succeeded;
}
catch (Exception ex)
{
TaskDialog.Show("Error", ex.Message);
return Result.Failed;
}
}
}
The "ReadNonAsync" method is as follows:
public static List<T> ReadNonAsync<T>() where T : IHasId
{
using (var client = new HttpClient())
{
var result = client.GetAsync($"{dbPath}{Properties.Settings.Default.CompanyName}_{typeof(T).Name.ToLower()}.json?access_token={DataStores.IdToken.UserIdToken}").GetAwaiter().GetResult();
var jsonResult = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (result.IsSuccessStatusCode)
{
var objects = JsonConvert.DeserializeObject<Dictionary<string, T>>(jsonResult);
List<T> list = new List<T>();
if (objects != null)
{
foreach (var o in objects)
{
o.Value.Id = o.Key;
list.Add(o.Value);
}
}
return list;
}
else
{
return null;
}
}
}
In the rest of my code I use a async Read method which works, so I'm wondering wether or not that's the issue, but Revit wont let me use an async method inside an Execute method.
How do I debug this issue correctly, and why could there be code working in debug that doesn't work in "live" versions?
I found a solution!
The issue:
The reason for the error was that when I run the software in debug-mode, a file path of "xxx.txt" finds files in the solution folder, but when I run the software "xxx.txt" points to the folder of the software and not the .dll -
So in my case it pointed to "c:\Program Files\Autodesk\Revit\2021".
The fix:
Hard coding the path, or by getting the path of the executing .dll
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Debugging/Troubleshooting:
I found the issue by inserting dialogboxes with errormessages in all my try/catch statements.

C# dynamics throws RuntimeBinderException when accessing property

I'm getting a RuntimeBinderException when attempting to read a property from a dynamic object. This is no doubt one of those issues where I've not got the syntax quite right, but I'm just not seeing it....
Using a simple LinqPad script, the following works fine:
void Main()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
dynamic d = response;
var x = d.DotNet as Version;
x.Major.Dump();
}
If I return it from a Web Method, then I'm running into issues. Here is my simple web method (.Net 5 WebAPI)
public IActionResult GetEnvironmentDetails()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
return this.Ok(response);
}
In my unit test, I can read the property using reflection, but not using dynamics:
var c = new MyController();
var response = c.GetEnvironmentDetails() as OkObjectResult;
// This next line gets me the property using reflection:
Version dotNet = response.Value.GetType().GetProperty("DotNet").GetValue(response.Value, null) as Version;
// But...using dynamics
dynamic d = response.Value;
// then the following fails for me
object x = d.DotNet;
If I put the variable d in my WATCH window, then the Value shows as { DotNet = {5.0.4}, ServerName = "MyComputerName" } and the Type is <Anonymous Type>.

Extent Reports version 3.0.2 - AppendExisting

Below is the code I am trying to use to append all tests to a single report. However, latest test is replacing all the older test reports. So, it's not appending to a single report for some reason. Can you please help me out here?
var htmlReporter = new ExtentHtmlReporter(ResourcesConfig.ReportPath);
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
htmlReporter.LoadConfig(ResourcesConfig.ReportXMLPath);
**htmlReporter.AppendExisting = true;**
I had a lot of trouble with this as well as the documentation doesn't explain much. I have one method called ReportCreation which runs for every test case and in that method i have the following:
public static ExtentReports ReportCreation(){
System.out.println(extent);
if (extent == null) {
extent = new ExtentReports();
htmlReports = new ExtentHtmlReporter(fileName+ n + "\\extentReportFile.html");
htmlReports.config().setReportName("Pre release Smoke test");
htmlReports.config().setTheme(Theme.STANDARD);
htmlReports.config().setTestViewChartLocation(ChartLocation.BOTTOM);
extent.attachReporter(htmlReports);
}
else {
htmlReports = new ExtentHtmlReporter(fileName+ n+ "\\extentReportFile.html");
htmlReports.setAppendExisting(true);
extent.attachReporter(htmlReports);
}
return extent;
}
So when the first unit test is run, it will create the html report, but the second unit test will see that the report has already been generated and so use the existing one.
I have created a random number generator so that it goes to a different report on every run
public static Random rand = new Random();
public static int n = rand.nextInt(10000)+1;
I was facing the same issue. My solution was using .NET Core so ExtentReports 3 and 4 were not supported.
Instead, I wrote code to merge the results from previous html file to the new html file.
This is the code I used:
public static void GenerateReport()
{
// Publish test results to extentnew.html file
extent.Flush();
if (!File.Exists(extentConsolidated))
{
// Rename extentnew.html to extentconsolidated.html after execution of 1st batch
File.Move(extentLatest, extentConsolidated);
}
else
{
// Append test results to extentconsolidated.html from 2nd batch onwards
_ = AppendExtentHtml();
}
}
public static async Task AppendExtentHtml()
{
var htmlconsolidated = File.ReadAllText(extentConsolidated);
var htmlnew = File.ReadAllText(extentLatest);
var config = Configuration.Default;
var context = BrowsingContext.New(config);
var newdoc = await context.OpenAsync(req => req.Content(htmlnew));
var newlis = newdoc.QuerySelector(#"ul.test-list-item");
var consolidateddoc = await context.OpenAsync(req => req.Content(htmlconsolidated));
var consolidatedlis = consolidateddoc.QuerySelector(#"ul.test-list-item");
foreach (var li in newlis.Children)
{
li.RemoveFromParent();
consolidatedlis.AppendElement(li);
}
File.WriteAllText(extentConsolidated, consolidateddoc.DocumentElement.OuterHtml);
}
This logic bypasses any Extent Report reference and treats the result file as any other html.
Hope this helps.

Fetching documentation of ISymbol from MetadataReference

I started learning about Roslyn Code Analysis recently. I went through provided sample codes. My question is following:
Is there a way how to get XML documentation comment of a symbol loaded from a referenced library?
Sample code I worked with is FAQ(7). The goal is to get documentation comment of, let us say, a Console.Write function.
public void GetWriteXmlComment()
{
var project1Id = ProjectId.CreateNewId();
var document1Id = DocumentId.CreateNewId(project1Id);
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var solution = new AdhocWorkspace().CurrentSolution
.AddProject(project1Id, "Project1", "Project1", LanguageNames.CSharp)
.AddMetadataReference(project1Id, mscorlib);
var declarations = SymbolFinder.FindDeclarationsAsync(solution.Projects.First(), "Write", true).Result;
var decFirst = declarations.First();
var commentXml = decFirst.GetDocumentationCommentXml();
}
The sample code works well for some methods - it gets the documentation text. But for methods, such as Console.Write, it uses NullDocumentationProvider and therefore returns empty string.
UPDATE
I have found I can load the MetadataReference with TestDocumentationProvider instance as following:
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location,
default(MetadataReferenceProperties), new TestDocumentationProvider());
where TestDocumentationProvider implements Microsoft.CodeAnalysis DocumentationProvider abstract class.
private class TestDocumentationProvider : DocumentationProvider
{
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
// To-Be-Done
}
}
Now the question narrows to how to read documentation using documentationMemberID?
Update: In Roslyn 2.0 you can use XmlDocumentationProvider.CreateFromFile.
The only way I can think of is using Reflection to create a FileBasedXmlDocumentationProvider (or otherwise copying its implementation from GitHub). You'll also need to search for the reference assemblies, since the load location of the framework assemblies does not contain documentation.
private static MetadataReference FromType(Type type)
{
var path = type.Assembly.Location;
return MetadataReference.CreateFromFile(path, documentation: GetDocumentationProvider(path));
}
private static string GetReferenceAssembliesPath()
{
var programFiles =
Environment.GetFolderPath(Environment.Is64BitOperatingSystem
? Environment.SpecialFolder.ProgramFilesX86
: Environment.SpecialFolder.ProgramFiles);
var path = Path.Combine(programFiles, #"Reference Assemblies\Microsoft\Framework\.NETFramework");
if (Directory.Exists(path))
{
var directories = Directory.EnumerateDirectories(path).OrderByDescending(Path.GetFileName);
return directories.FirstOrDefault();
}
return null;
}
private static DocumentationProvider GetDocumentationProvider(string location)
{
var referenceLocation = Path.ChangeExtension(location, "xml");
if (File.Exists(referenceLocation))
{
return GetXmlDocumentationProvider(referenceLocation);
}
var referenceAssembliesPath = GetReferenceAssembliesPath();
if (referenceAssembliesPath != null)
{
var fileName = Path.GetFileName(location);
referenceLocation = Path.ChangeExtension(Path.Combine(referenceAssembliesPath, fileName), "xml");
if (File.Exists(referenceLocation))
{
return GetXmlDocumentationProvider(referenceLocation);
}
}
return null;
}
private static DocumentationProvider GetXmlDocumentationProvider(string location)
{
return (DocumentationProvider)Activator.CreateInstance(Type.GetType(
"Microsoft.CodeAnalysis.FileBasedXmlDocumentationProvider, Microsoft.CodeAnalysis.Workspaces.Desktop"),
location);
}
I've used something similar in RoslynPad.

Getting "mergable revisions" with SharpSvn

When setting up a merge, the TortoiseSvn client has a wonderful checkbox labeled "Hide non-mergable revisions". I'm looking to reproduce the list of revisions that shows up when it's enabled using SharpSvn.
The TortoiseSvn documentation explains this checkbox:
When merge tracking is used, the log dialog will show previously merged revisions, and revisions pre-dating the common ancestor point, i.e. before the branch was copied, as greyed out. The Hide non-mergeable revisions checkbox allows you to filter out these revisions completely so you see only the revisions which can be merged.
How can I reproduce this functionality in SharpSvn code? I need a list of SvnLogEventArgs (or similar) that are candidates for merging.
Current status: I've only gotten as far as pulling the logs for both branches. I can't figure out how to get the appropriate svn:mergeinfo attribute or what to do with it once I get it.
I kept plugging away, and following links, and here's what I ended up with:
using (var client = new SvnClient())
{
var release = SvnTarget.FromUri(new Uri(#"https://******/branches/Release"));
var trunk = SvnTarget.FromUri(new Uri(#"https://******/trunk"));
string trunkMergeinfo, releaseMergeinfo;
client.GetProperty(release, "svn:mergeinfo", out releaseMergeinfo);
client.GetProperty(trunk, "svn:mergeinfo", out trunkMergeinfo);
var relInfos = releaseMergeinfo.Split("\n");
var trunkInfos = trunkMergeinfo.Split("\n");
// This is here because I don't know what will happen once I merge something into trunk.
Debug.Assert(relInfos.Except(trunkInfos).Count() == 1,"Too many unknown merge paths");
var trunklist = relInfos.SingleOrDefault(i => i.StartsWith("/trunk:"));
var revisions = trunklist.Replace("/trunk:", "").Split(",").SelectMany(t =>
{
// If the log contains a range, break it out to it's specific revisions.
if (t.Contains("-"))
{
var match = Regex.Match(t, #"(\d+)-(\d+)");
var start = int.Parse(match.Groups[1].Value);
var end = int.Parse(match.Groups[2].Value);
return Enumerable.Range(start, end - start + 1).ToArray();
}
else
return new[] { int.Parse(t) };
}).Select(x => (long)x);
Collection<SvnLogEventArgs> baseRevs;
// Why can't this take "trunk" or a property thereof as an argument?
client.GetLog(new Uri(#"https://******/trunk"), new SvnLogArgs { Start = 1725, End = SvnRevisionType.Head }, out baseRevs);
baseRevs.Reverse().Where(r => !revisions.Contains(r.Revision) ).Select(x => x.LogMessage).Dump();
}
Hopefully, this helps someone else, although I'll note that it does not have a lot of the sanity checking that I'd put in production code - this is the quick-and-dirty version.
Try SvnClient.ListMergesEligible:
http://sharpsvn.qqn.nl/current/html/M_SharpSvn_SvnClient_ListMergesEligible_1.htm
Edit.
SharpSVN seems bugged for me, so I went for cmd.
Check this out:
private static void mergelhetőVerziókListája()
{
string revíziók = cmd("svn", "mergeinfo --show-revs eligible \".../branches/dev\" \".../trunk\"");
}
private static string cmd(string utasítás, string paraméter)
{
StringBuilder eredmény = new StringBuilder();
Process cmd = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = utasítás,
Arguments = paraméter,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
cmd.Start();
while (!cmd.StandardOutput.EndOfStream)
{
string kimenet = cmd.StandardOutput.ReadLine();
eredmény.AppendLine(kimenet); //...
}
return eredmény.ToString();
}

Categories

Resources