Excute powershell SCVMM cmdlets from Asp.Net Web API - c#

I'm developing a Web Api in Asp.Net. I need that the web API comunicates with SCVMM, using .Net Framework.
We all know that SCVMM does not provide an API o interface similar to execute functions from c# code, but we have the option to run commands from PowerShell.
The situation is as follows:
From PowrShell prompt I can comunicate without any problem with SCVMM
From c# code using Cake.Pworsehl Nuget Package I can execute cmdlets with SCVMM commands
and comunicate with SCVNMM without problems.
Using the functions that I've wrote before, I've created a Dll with all the
functionality that I need, I have also added a TestProject for that dll and all works
fine.
The problem is that when I call the same functions from the WebApi project using
debugmode in VS 2022 I have the following error:
System.Management.Automation.CmdletInvocationException: 'You do not have access to the management server VMM NO_PARAM. (Error Id: 1604)
The weird thing is that, as I said before, I can run all funcitons from PowerShell prompt, and execute all the code from TestProjects and even a console application, but if I call the same functions form web api, I get that error.
I'm thinking that the problemas has to be realted with de Identity or something similar, but I can not found any way to specify credentials for run powershell cmdlets form c# code.
This is the function that gives me the error:
public List<Vm> GetVMsBase()
{
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;
initialSessionState.ImportPSModule(new string[] { "virtualmachinemanager" });
using (var myRunSpace = RunspaceFactory.CreateRunspace(initialSessionState))
{
myRunSpace.Open();
using (var pipeLine = myRunSpace.CreatePipeline())
{
Command cmd = new Command("Get-SCVirtualMachine");
cmd.Parameters.Add("VMMServer", "vmmserver.domain.com");
pipeLine.Commands.Add(cmd);
return pipeLine.Invoke().Select(vm =>
new Vm
{
Name = vm.Properties["name"].Value.ToString(),
Owner = ((string[])vm.Properties["CustomProperties"].Value)[1],
ExpirationDate = DateTime.TryParse(
((string[])vm.Properties["CustomProperties"].Value)[0], new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt) ?
dt : new DateTime(1800, 1, 1),
CreationDate = DateTime.TryParse(
vm.Properties["CreationTime"].Value.ToString(), new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt2) ?
dt2 : new DateTime(1800, 1, 1),
Hlnumber = ((string[])vm.Properties["CustomProperties"].Value)[2],
State = Enum.TryParse(vm.Properties["VirtualMachineState"].Value.ToString(), out VirtualMachineState vmState) ? vmState : VirtualMachineState.Unknow
}).ToList();
if (pipeLine.Error != null && pipeLine.Error.Count > 0)
{
//check error
}
}
}
Is there any way to call or run this code from web api?
thanks for your attention.

finaly I'v solved this problem, there was nothing wrong with the code to run powershell cmdlets, the problem was with the configuration of IIS expres (in visual studio) and when deploy the api in IIS 10.
In both cases I have to setup de configuration in a way that Anonymous logon was disabled and the only Authettication method used was "Windows", and that's it.
In IIS express you have to edit the .config file located in the .vs directory of the solution, and in IIS 10 you have to edit your site setting in the Authetication Options.

Related

502 Error: Bad Gateway on Azure App Service with IronPDF

I am attempting to get IronPDF working on my deployment of an ASP.NET Core 3.1 App Service.
I am not using Azure Functions for any of this, just a regular endpoints on an Azure App Service -which, when a user calls it, the service generates and returns a generated PDF document.
When running the endpoint on localhost, it works perfectly- generating the report from the HTML passed into the method. However, once I deploy it to my Azure Web App Service, I am getting a 502 - Bad Gateway error, as attached (displayed in Swagger for neatness sake).
Controller:
[HttpPost]
[Route("[action]")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> AgencyDownload([FromBody] AgencyReportSubmissionDto filters)
{
var user = await _userService.GetUserByIdAsync(HttpContext.User.GetUserId());
// Generate the PDF
var content = await _agencyReport.Generate(user, null, filters.FilterDate, filters.Content, filters.Type);
// Return the PDF to the browser
return new FileContentResult(content.BinaryData, "application/pdf") { FileDownloadName = "report.pdf" };
}
Service:
public async Task<PdfDocument> Generate(User user, byte[] letterhead, DateTimeOffset filterDate, string html, AgencyReportTypes reportType)
{
var corporateIdentity = new CorporateIdentity()
{
PrimaryColor = "#000000",
PrimaryTextColor = "#ffffff",
SecondaryColor = "#ffffff"
};
// Inserts the HTML content (from form) into the HTML template
var htmlContent = Template(corporateIdentity.PrimaryColor, corporateIdentity.PrimaryTextColor).Replace("{{HtmlContent}}", html);
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time");
var convertedDate = TimeZoneInfo.ConvertTimeFromUtc(filterDate.UtcDateTime, tz);
var Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.Title = "Agency Report - for " + convertedDate.ToString("d MMMM yyyy");
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
var doc = await Renderer.RenderHtmlAsPdfAsync(htmlContent);
return doc;
}
Solution:
I noticed that if I performed a manual deployment to that app service, it was working, but when I was deploying from my pipeline- I had the error above.
So I went snooping around my pipelines and upon changing it to this, it worked.
- task: AzureRmWebAppDeployment#4
displayName: Deploy API Artifact
inputs:
ConnectionType: 'AzureRM'
AzureSubscription: 'My-Azure-Subscription'
enableCustomDeployment: true
DeploymentType: 'zipDeploy'
deployToSlotOrASE: true
SlotName: 'development'
AppType: 'webApp'
WebAppName: 'my-api'
Package: '$(Pipeline.Workspace)/**/API.zip'
ResourceGroupName: 'MyResource'
the 'DeploymentType: 'zipDeploy'" was key.
Thanks to Alex Hanneman for pointing me in the right direction.
I am also using Azure App Service as an API, wrapping IronPDF. Upgrading to latest Iron PDF package also broke my app, returning a 502.
What I did to fix it is deploy the code using ZipDeploy and then set WEBSITE_RUN_FROM_PACKAGE to 0. This is also needed to get the Iron PDF log files to show up in Azure, as they recommend here: https://iron.helpscoutdocs.com/article/122-azure-log-files.
App Service runs your apps in a sandbox and most PDF libraries will fail. Looking at the IronPDF documentation, they say that you can run it in a VM or a container. Since you already are using App Service, simply package your app in a container, publish it to a container registry and configure App Service to run it.
We are also facing the same issue with iron PDF but while changing the type of deployment to zip it's solves.

TF400813: Resource not available for anonymous access. Client authentication required

I am working on the CodedUI Test Automation project. i am developing a framework in which i am trying to access Test Cases in VSTS through RestAPI. I have worked on an MVC application previously in which i did the same thing to pull data from VSTS using RestAPI.
Now the problem is i am not able to access the VSTS. Everytime i am trying to access the VSTS, i got the exception TF400813: Resource not available for anonymous access. Client authentication required.
I am using the same PAT token. I have all the required access on my team project. I am able to access all work items in my project from browser. I have tried all the option mentioned in below thread but still its not working.
Client authentication error when starting Visual Studio 2015.3Any leads will be appreciated.Below is my code to get data from VSTS:
public static List<WorkItem> GetWorkItemsWithSpecificFields(IEnumerable<int> ids)
{
var collectionUri = "https://<name>.visualstudio.com";
var fields = new string[] {
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
};
using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(new Uri(collectionUri), new VssBasicCredential("", System.Configuration.ConfigurationManager.AppSettings["PATToken"])))
{
// Exception is coming on below line
List<WorkItem> results = workItemTrackingHttpClient.GetWorkItemsAsync(ids, fields).Result;
return results;
}
}

Getting Error in SSRS report rendering in C# window application: The request failed with HTTP status 401: Unauthorized

I have 1 SSRS Report that deployed on server. I am able to access and see the report in ReportViewer in Test Application(C# Window Application).
But I am not able to access/run the same report in my actual actual application with same piece of code., getting error on the line where I am setting parameters to reportviewer.
Here is the code block that i am using in both Test and Actual Application:
ReportParameter[] parameters = new ReportParameter[3];
rptViewer.Reset();
rptViewer.ProcessingMode = ProcessingMode.Remote;
rptViewer.ServerReport.ReportPath = "/LIVE Reports/LicenceReport";
rptViewer.ServerReport.ReportServerUrl = new Uri(#"http://X3dRF45CC/Reportserver", System.UriKind.Absolute);
parameters[0] = new ReportParameter("IN_TIME_PERIOD_FLAG", txtType.Text, false);
parameters[1] = new ReportParameter("IN_PLAN_VERSION_ID", txtPlanVersion.Text, false);
parameters[2] = new ReportParameter("IN_MEDIA_OUTLET_ID", txtNetwork.Text, false);
// Getting error at this below line in Actual App (but not in Test App)
rptViewer.ServerReport.SetParameters(parameters);
rptViewer.RefreshReport();
Please someone help, I am wondering from last 2 days.
If your report server is running under windows authentication. Then it is possible that when you run the report using test application (which is running with user context having correct permissions) it runs fine. But when you run this in the actual application(which is not running in context of user with appropriate permissions) fails with 401 (UnAuthorized) error

SVN COPY error: 501 Method Not Implemented

We've been using VisualSVN (standard edition) for a few years without any problems. We have a C# application which stores data in SVN. It uses SharpSvn (https://sharpsvn.open.collab.net) library for SVN access. Occasionally, the application executes a server-side SVN COPY command (SharpSvn's "RemoteCopy") to create a branch based on a series of existing in the repository files.
We recently updated VisualSVN from version 2.5.2 to 3.2.2 and also purchased a license to unlock enterprise features of the product. We enabled Integrated Windows Authentication, but also kept Basic Authentication for backward compatibility.
After running for a week without any problems (performing only reads from SVN), our application tried to perform the copy for the first time, and it failed with the following error complaining about one of the files that had to be copied:
"COPY request on '/svn/repository/!svn/rvr/12345/trunk/file.xml' failed: 501 Method Not Implemented"
The server log reveals the following:
Level,Date and Time,Source,Event ID,Task Category
Error,2015-03-03 9:37:26 AM,VisualSVN Server 3.2,1001,Apache,"Multi-author commits not supported. [501, #175002] [client 192.168.1.100]"
Error,2015-03-03 9:37:26 AM,VisualSVN Server 3.2,1001,Apache,"Could not fetch resource information. [501, #0] [client 192.168.1.100]"
Error,2015-03-03 9:37:26 AM,VisualSVN Server 3.2,1001,Apache,"SSPI Challenge failed: The token supplied to the function is invalid [client 192.168.1.100]"
Error,2015-03-03 9:37:21 AM,VisualSVN Server 3.2,1001,Apache,"SSPI Challenge failed: The token supplied to the function is invalid [client 192.168.1.100]"
After restarting VisualSVN service, the command completed without any problems. This had never happened before with the older versions of VisualSVN.
This is how we create a branch using SharpSvn:
private static void Branch(ICollection<SvnUriTarget> sources, Uri targetUri, string comment, string userName, string password)
{
if (sources == null) throw new ArgumentNullException("sources");
if (targetUri == null) throw new ArgumentNullException("targetUri");
if (comment.IsNullEmptyOrSpaces()) throw new ArgumentNullException("comment");
if (userName.IsNullEmptyOrSpaces()) throw new ArgumentNullException("userName");
if (password.IsNullEmptyOrSpaces()) throw new ArgumentNullException("password");
using (var client = new SvnClient())
{
client.Authentication.Clear();
client.Authentication.DefaultCredentials = new NetworkCredential(userName, password);
client.Authentication.SslServerTrustHandlers += (sender, e) => { e.AcceptedFailures = e.Failures; e.Save = true; };
SvnCommitResult commitResult;
if (!client.RemoteCopy(sources, targetUri, new SvnCopyArgs { CreateParents = true, LogMessage = comment }, out commitResult))
throw new ApplicationException("Failed to create tag/branch in Repository");
}
}
In our application, we are still using Basic Authentication, and credentials are explicitly passed to every SharpSvn call. The application requests credentials from the user, and then it uses these credentials to perform a single call of the "Branch" method.
Two different users tried to do this using their own credentials on two different machine with the same result. Only restart of VisualSVN service fixed the problem. I'm worried that this problem may come back again...
You should disable SharpSvn (and Subversion) to use Integrated Authentication ('ntlm' and 'negotiate') if you're going to specify credentials for operation.
Try add code like this:
client.Configuration.SetOption("servers", "global", "http-auth-types", "basic");
Probably this is a bug in Subversion, SharpSvn or serf, but proposed workaround should work.

C# create site in IIS programatically in asp.net project

I am trying to create a site in IIS using Microsoft.Web.Administration dll in C#. I am using following code
using (var serverManager = new ServerManager())
{
ApplicationPool pool = serverManager.ApplicationPools.Add(ClientDomain);
pool.ManagedRuntimeVersion = "v4.0";
Site site = serverManager.Sites.Add(SiteName, httpProtocol, httpBindingInformation, physicalPath);
site.Bindings.Add(httpsBindingInformation, httpsProtocol);
serverManager.CommitChanges();
}
I am getting following exception "The method or operation is not implemented" when I run the code from asp.net project but if same code is run from console project, it works fine. Here is the details of the exception
at Microsoft.Web.Administration.Interop.IAppHostProperty.get_Value()
at Microsoft.Web.Administration.ConfigurationElement.GetPropertyValue(IAppHostProperty property)
at Microsoft.Web.Administration.ConfigurationElement.GetAttributeValue(String attributeName)
at Microsoft.Web.Administration.Binding.get_CertificateHash()
at Microsoft.Web.Administration.BindingCollection.Add(Binding binding)
at Microsoft.Web.Administration.BindingCollection.Add(String bindingInformation, String bindingProtocol)
at TestProject.BLL.CRMSiteManagement.CRMSiteIISSetup.Process() in e:\CRMSiteManagement\CRMSiteIISSetup.cs:line 35
at TestProject.BLL.CRMSiteManagement.CRMSiteService.CreateNewCRMSite(CRMSite newSite) in e:CRMSiteManagement\CRMSiteService.cs:line
Seems like an issue with rights but I have not idea how to fix it.
Update 1:
Error is coming on following line of code on localhost
site.Bindings.Add(httpsBindingInformation, httpsProtocol);
I think you're trying to set the same bindings twice :
Once by calling the Add method
Site site = serverManager.Sites.Add(SiteName, httpProtocol, httpBindingInformation, physicalPath);
Then you add again the same binding:
site.Bindings.Add(httpsBindingInformation, httpsProtocol);

Categories