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

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);

Related

Excute powershell SCVMM cmdlets from Asp.Net Web API

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.

SharePoint 2013: Why getting 500 error while creating clientContext?

I want to create a IIS webservice which has to write list items to SharePoint on Premise.
I want to use CSOM and try to create a ClientContext.
public string AddListItem()
string result = string.Empty;
string siteUrl = "https://serverUrl";
using (ClientContext context = new ClientContext(siteUrl))
{
context.Credentials = new NetworkCredential("User", "Password", "Domain");
List list = context.Web.Lists.GetByTitle("Test");
context.Load(list);
context.ExecuteQuery();
}
return result;
}
While executing, I get an error at context.ExecuteQuery();
System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error.'
In the Event Log, I see following error:
WebHost failed to process a request.
Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/41028758
Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/client.svc' cannot be activated due to an exception during compilation. The exception message is: Operation is not valid due to the current state of the object.. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.Administration.SPWebApplication.get_Context()
................................
In debugging, I also see after creating the ClientContext and before context.ExecuteQuery(); following error at some properties of ClientContext, e.g.:
ServerLibraryVersion = 'context.ServerLibraryVersion' threw an exception of type 'Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException'
Your code seems fine for on-prem SharePoint. I think You should check some settings on the farm that my be the cause of that.
Please check the services on farm server if the IIS Admin Service is on
also on SharePoint CA check the user profile service and the claims to windows token service (both should be on)
... sorry for the lang :)... usually I have access to SharePoint in PL language, but I tried to translate the most important stuff to ang.
Please also check if on IIS the app pools that You try to access are working correctly. I suppose yes, otherwise You would have a lot of other errors, but it's always better to check.
Use CSOM, what to use WCF is not clear:
ClientContextctx = newClientContext("http://gowtham.sharepoint.com");
List oList = ctx.Web.Lists.GetByTitle("Announcements");
ListItemCreationInformationitemCreateInfo = newListItemCreationInformation();
ListItemnewItem = oList.AddItem(itemCreateInfo);
newItem["Title"] = "Test Item!";
newItem["Body"] = "welcome to Gowtham Blog";
newItem.Update();
context.ExecuteQuery();
Try below code
using (ClientContext clientContext = new ClientContext(ServerURL))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(your_mail_ID, securePassword);
Web web = clientContext.Web;
var list = web.Lists.GetByTitle("your_list_name");
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
}
Check if the "SharePoint Web Servies Root" application pool was stopped or the "SharePoint Web Services" web application not start in IIS.
Go to IIS Application Pools, find the "SecurityTokenServiceApplicationPool" and click "Advanced Settings" from the action panel, then Scroll to "ProcessModel" section and change the Identity to your SharePoint Farm Account and do IISRESET.
And create a console application with the CSOM C# code to check if it works.
FWIW - I had exactly the same error - CSOM local mode to on-prem SP2016 with a 500 error requesting the list by title.
I had just applied a 10/2019 SharePoint update, but hadn't gone through Product Configuration Wizard and the prompts in Central Admin. Once I did that, CSOM requests worked again.

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;
}
}

C# code running locally but not in web hosting

in my asp.net web application i have this entity framework code snippet that work perfectly in local
CONNECTIONS_STATS cs = new CONNECTIONS_STATS();
cs.CS_ID_USER = 5211;
cs.CS_DATE = DateTime.Now;
using (var dbCtx = new ModelEntities())
{
dbCtx.CONNECTIONS_STATS.Add(cs);
dbCtx.SaveChanges();
}
but when i deploy it to my web host, i have this error at line
dbCtx.CONNECTIONS_STATS.Add(cs);
CS1502: The best overloaded method match for 'System.Data.Entity.DbSet.Add(MyAPP.CONNECTIONS_STATS)' has some invalid arguments
in the detailed compiler output
error CS1503: Argument 1: cannot convert from 'CONNECTIONS_STATS' to 'MyApp.CONNECTIONS_STATS'
i have checked that all the classes are in the same namespace , and like i said this code Work perfectly in local
any idea on this please ?

Can't get SharePoint access token

I have created an app in SharePoint 2013, using AppRegNew.aspx, from where I got an app secrete and id. For this app I set permissions of reading and writing to Documents list, using AppInv.aspx.
Now, I want to use the app secrete and Id from another project to access the documents list. I am using TokenHelper class like below:
TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken
But I get an exception:
The remote server returned an error: (404) Not Found. - The requested namespace does not exist.
I debugged the code from TokeHelper class and found that the exception comes from this web call:
https://accounts.accesscontrol.windows.net/metadata/json/1?realm=my_realm_value
which is located in method:
private static JsonMetadataDocument GetMetadataDocument(string realm)
Any help will be appreciated, thank you :-)
In the end I managed to figure it out. I used a SharePoint app that had the following permissions:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write">
<Property Name="BaseTemplateId" Value="101"/>
</AppPermissionRequest>
</AppPermissionRequests>
Beside this I used a certificate in order to get the access token. That certificate I linked with the app and set it as a trust token issuer using a PowerShell script:
$issuerID = [System.Guid]::NewGuid().ToString().ToLower()
$publicCertPath = "your_cer_file.cer"
$certificate = Get-PfxCertificate $publicCertPath
$web = Get-SPWeb "http://your.sharepoint.url/"
$realm = Get-SPAuthenticationRealm -ServiceContext $web.Site
$fullAppIdentifier = $issuerId + '#' + $realm
New-SPTrustedSecurityTokenIssuer -Name "High Trust App" -Certificate $certificate - RegisteredIssuerName $fullAppIdentifier -IsTrustBroker
$issuerID
iisreset
Then I used TokenHelper class like this:
var siteUri = new Uri("my_site_url");
TokenHelper.GetS2SAccessTokenWithWindowsIdentity(siteUri, null);

Categories