I am trying to deploy a website via the Web Deploy API (Microsoft.Web.Deployment).
Using the msdelpoy.exe, I could do as many -postSync:runcommand's (or preSync) as I like, but I can't see how to do that via the API.
Here is my deployment script in powershell, but you can see the .net classes being used.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Deployment")
function CallMSDeploy([string]$destinationServer, [string]$destinationIISSiteName, $sourceDirectory)
{
$destBaseOptions = new-object Microsoft.Web.Deployment.DeploymentBaseOptions
$destBaseOptions.UserName = $deployUserName
$destBaseOptions.Password = $deployPassword
$destBaseOptions.ComputerName = $destinationServer
$syncOptions = new-object Microsoft.Web.Deployment.DeploymentSyncOptions
$deploymentObject = [Microsoft.Web.Deployment.DeploymentManager]::CreateObject("contentPath", $sourceDirectory)
$deploymentObject.SyncTo("contentPath",$destinationIISSiteName,$destBaseOptions,$syncOptions);
}
I know that I can new up a Microsoft.Web.Deployment.DeploymentObjectProvider using the "runCommand" provider and specifiy a path, but how do I add it to the preSync of the above deployment?
Thanks in advance!
preSync / postSync is a feature of the msdeploy command line, not the Microsoft.Web.Deployment API itself. Both are basically just a call to CreateObject().SyncTo(destOptions), where destOptions are copied from the main sync.
You should have no troubles reproducing it in PS.
Related
The API is using .NET Core 3.1 and the folder structure is as follows:
Solution
--Project1
--Project2
Where Project 2 depends on Project 1 and is the entry point.
The API is hosted on kubernetes and a NFS share is mounted at /storage. The API will need to retrieve and serve files in this file share. So what I did was using the following in my startup.cs in Project2:
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), #"storage")),//this will return /app/storage
RequestPath = new PathString("/resources")
});
I know one of the file is there by checking:
System.IO.File.Exists(#"/app/storage/test.JPG");
However, when I tried to access the file by going to http://myapiurl/resources/test.JPG, I always got a 404 not found.
I was wondering what I was missing?
You're using UseFileServer, but you're not enabling directory browsing nor serving default files, so I'd recommend narrowing instead to using UseStaticFiles.
The easiest way to enable this is to just place the following in your Startup.cs file in your Configure() method.
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "storage")),
RequestPath = "/resources"
});
My guess for why this isn't working for you is that Directory.GetCurrentDirectory, when running in K8 isn't yielding the same path you see when running locally, so it's not ultimately pointing at /app/storage (which is why your File.Exists check works fine because you're not building the path out dynamically).
Use some logging to verify that it's pulling from the right path in your configuration at runtime.
I had a similar problem with static files after switching from AppService to k8s with ingress. It turned out to be problem with case-sensitivity in the URL. Some directories were uppercase, but in paths I had all lowercase letters. It was working locally on Windows and on AppService but not on k8s.
I am building a .net core web app in which i use AzureAD auth and Microsoft Graph to get data from a sharepoint online site.
I need to get the groups of the current user.
I tried to use graphClient.Me.MemberOf.Request().GetAsync();
I think i'm getting the role of the user in the Azure directory.
But i want the role of the current user for a specific sharepoint online site.
Is that possible to get this information and how ?
I don't find a working way to get this using Microsoft Graph.
EDIT:
As Microsoft Graph doesn't allow to get that data.
I tried to call the following Sharepoint Online API endpoint :
https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups
Using this api endpoint i can see all the roles of the current user in my browser.
But i don't find how to call it from my .net core web app.
Tried the following :
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-types", "application/json;odata=verbose");
var response = await client.GetAsync("https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
}
But that give me a 403 response.
EDIT 2 :
I am currently trying to use CSOM to get this informations(TCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200.)
But i don't find a way to get TokenHelper.cs.
var token = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipalId, webUri.Authority, null).AccessToken;
var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), token);
I tried to add "AppForSharePointOnlineWebToolkit" and it did not add the needed files in the project.
How can i get the TokenHelper.cs file ?
Thanks for any help.
Tristan
To execute CSOM code in .net core, do below settings.
We can install the package as below.
Install-Package TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200 -Version 16.1.8029.1200
More information is here: TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200
Or use the following solution from GitHub: NetCore.CSOM
Or follow the steps below.
1.Create a .NET Core console app.
2.Add the references: Microsoft.SharePoint.Client.Portable.dll, Microsoft.SharePoint.Client.Runtime.Portable.dll, and Microsoft.SharePoint.Client.Runtime.Windows.dll.
Note: If the project has references to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll, please remove them.
These references can be accessed by installing CSOM library into another project, and then navigating to installed nuget packages in the file directory: c:\Users\user.nuget\packages\microsoft.sharepointonline.csom(version)\lib\netcore45
3.Add the code below to the .NET Core 2.0 console application:
Get current user role:
To get the current user role, you can use Web.GetUserEffectivePermissions method.
Ex:
ClientResult<BasePermissions> permission= web.GetUserEffectivePermissions(name);
context.ExecuteQuery();
var res = permission.Value;
Refer below link to get clientcontext using access token: https://www.sharepointpals.com/post/how-to-get-the-client-context-using-app-access-token-by-passing-client-id-and-client-secret-id-using-csom-in-sharepoint-office-365/
No. Microsoft Graph doesn't expose an endpoint that allows you to get the information of SharePoint Group and its members.
If you has this requirement, you could vote this idea on Microsoft Graph UserVoice.
In previous version of asp.net the HostingEnvironment had MapPath method to get and store the path of the file but in ASP.net 5 I can't use it.
var filepath = HostingEnvironment.MapPath(#"~/Data/product.json");
Are you using RC1?
In RC1 it depends if you are writing a console or web app. In console apps, you cannot use DI anymore but PlatformServices.Default.
PlatformServices.Default.Application gives you access to the base path of your application for example. The type of the static property is IRuntimeEnvironment. And having the base path of your app, you can easily build the path to files you need...
If you are building a web app, you should be able to inject IRuntimeEnvironment to your startup and use it from there.
You have to add a reference to the Microsoft.Extensions.PlatformAbstractions package to all that stuff.
See also my post here for more details
Despite IHostingEnvironment provides MapPath() method you may also need UnmapPath() too. Another useful method might be IsPathMapped().
You can find all of them here: Reading a file in MVC 6.
And all of them, thanks to PlatformServices availability, work in Consolse, MVC, and ClassLib apps.
HTH
I'm trying to define a service endpoint in my web.config file so that I can point our staging build to a staging web service and a different end point for production. There's a question here that deals with web references in Visual Studio 2005/2008. I'm adding a service reference and can't seem to find anything in properties that would allow me to define the Url Behaviour as dynamic.
I'd like to define the url in the appSettings. Does anyone know how this works in Visual Studio 2010 for Service References?
You can change the end point using what is known as a config transformation.
In short, a config transformation allows you to tweak various config settings depending on your deployment. This is a technique commonly used for changing connection strings as well.
Here's more reading: How to: Transform Web.config When Deploying a Web Application Project
You can set the URL at run time just after you create the web service but before you use it:
string localUrl = "localhost";
string stagingUrl = "http://staging.example.com"
string url = Request.IsLocal ? localUrl : stagingUrl;
var _webService = new YourWebService { Url = url };
I want to write a few web tests (over WatiN/Selenium + CassiniDev web server) for my asp.net web application.
Problem I encountered is that I dont know what to do in such situations:
there is a page where user can click the button to call some third-party service. In my web test i want to create mock of this service, which will always return static value (some value in these test case and other value in other test case).
How can i do that?
Currently i use IoC/DI container Microsoft Unity. And my pages gets his dependencies in a manner described in http://msdn.microsoft.com/en-us/library/ff664622%28v=pandp.50%29.aspx.
The only solution that comes to my head is: place all dependencies in web.config for each test case and copy necessary web.config on SetUp of test. This solution completly painful!
Any ideas?
I use WatiN and Cassini-dev in my integration tests as well and have had to deal with similar issues. In my setup fixture I deploy my Asp.Net web application to a temporary folder in my test folder which allows me to play around with the configuration before starting up cassini-dev. I use Windsor for my CI which allows me to change injected components at the configuration level. You may also be able to acheive this with Unity.
If the service you are referring to is a web service you just mock out a web service using the interface you have been coding to.
Here are the steps that I take when running my integration tests:
Create a temp web directory
Publish the Asp.Net web application to the temp directory (I use MSBuild to do this)
Deploy temp database (Using MSbuild and database projects but could be done a number of ways)
Deploy temp membership database (see my blog post on how to do this in code)
Update the web.config of the deployed Asp.Net web application to point to the temp databases and change any other settings relevant for testing.
Start up the website using Cassini-Dev. I also hit the site with a http request so that I can verify the site is up before running any tests.
Run the tests.
After running the tests you should clean up.
Stop cassini-dev
Delete the temp hosting folder
Delete the temp databases. I use Sql server SMO objects that allow me to query the Sql Server which I use to delete up any old databases that have been left lying around after any previously failed test runs.
How to deploy a website using MSbuild in code
var properties = new Dictionary<string, string>
{
{"Configuration", isDebug ? "Debug" : "Release"},
{"WebProjectOutputDir", tempHostingDirectory.FullName},
{"DeployToDatabase", "true"},
{"OutDir", Path.Combine(tempHostingDirectory.FullName, "bin\\")}
};
using (var engine = new ProjectCollection(properties))
{
engine
.LoadProject(<web project path>, "4.0")
.Build(new[] {"Build", "ResolveReferences", "_CopyWebApplication"});
}
Unity configuration section usage: http://www.pnpguidance.net/Post/UnityContainerUnityConfigurationSectionAppConfigWebConfig.aspx
Generating asp.net membership database in code: http://bronumski.blogspot.com/2011/06/generating-creating-aspnet-application.html
Msbuild ProjectCollection on MSDN: http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.aspx
It sounds like you are trying to mock a web service.
Web services usually inherit from MarshalByRefObject, this means you can create a mock by inheriting from RealProxy to create a transparent proxy that pretends to be the webservice:
class Mock : RealProxy
{
public Mock()
: base(typeof(IStuff)) { }
public IStuff GetStuff()
{
return (IStuff)GetTransparentProxy();
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage message = (IMethodCallMessage)msg;
// the message object provides the MethodInfo that was called
// as well as the arguments.
// <Insert logic here>
return new ReturnMessage(new NotImplementedException("comming soon to a test near you ..."), message);
}
}
I belieave NMock2 uses RealProxy for it's mocks, so you should be able to use it to mock the web service instead.