Skip to content
This repository was archived by the owner on Nov 25, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DotNetFunction.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26720.2
VisualStudioVersion = 15.0.26730.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DotNetFunction", "src\DotNetFunction\DotNetFunction.csproj", "{E82A3F5E-9CA6-4E2E-8D51-A938DD62A363}"
EndProject
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,4 @@ Here are the DevOps practices highlighted within this CD pipeline:
- [Application Insights integration with Functions now in preview](https://blogs.msdn.microsoft.com/appserviceteam/2017/05/10/application-insights-integration-with-functions-now-in-preview/)
- Deploying Azure Function App with Deployment Slots using ARM Templates - Blog series: [First](https://nascent.blog/2017/05/31/azure-function-app-deployment-slots-arm-template/), [Second](https://nascent.blog/2017/06/22/azure-functions-arm-templates-snags-1-http-triggers-keys/) and [Third](https://nascent.blog/2017/06/27/azure-functions-slots-arm-templates-snags-2-redeploy-causes-unwanted-swap/)
- [Is Your Serverless Application Testable? – Azure Functions](https://blog.kloud.com.au/2017/07/22/is-your-serverless-application-testable-azure-functions/)
- [Azure Functions Proxies Sample](https://github.com/Azure-Samples/functions-js-spa)
22 changes: 16 additions & 6 deletions docs/DotNet-FunctionApp-CD.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ TODO
- Override Template Parameters = -functionAppName $(ResourceGroupName) -slotName $(SlotName)
- Deployment Mode = Incremental
- Deploy Function App on Staging
- Type = Deploy Staging
- Type = Azure App Service Deploy
- Version = 3.*
- Azure Subscription = set appropriate
- App Service Name = $(ResourceGroupName)
Expand All @@ -80,20 +80,28 @@ TODO
- Slot = $(SlotName)
- Package or Folder = $(System.DefaultWorkingDirectory)/DotNet-FunctionApp-CI/function
- Publish using Web Deploy = true
- Check Production URL
- Check Staging URL
- Type = [Check URL Status](https://marketplace.visualstudio.com/items?itemName=saeidbabaei.checkUrl)
- URL = https://$(ResourceGroupName)-$(SlotName).azurewebsites.net/api/SampleHelloDotNetFunction/test
- Version = 1.*
- URL = https://$(ResourceGroupName)-$(SlotName).azurewebsites.net/api/SampleHelloDotNetFunction
- Replace tokens in integration tests config file
- Type = [Replace Tokens](https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens)
- Version = 2.*
- Target files = $(System.DefaultWorkingDirectory)/xUnit-CI/integration-tests/*.config
- Files encoding = auto
- Write unicode BOM = true
- Action (Missing variables) = log warning
- Keep token = true
- Token prefix = #{
- Token suffix = }#
- Run IntegrationTests
- Type = Visual Studio Test
- Version = 2.*
- Select tests using = Test assemblies
- Test assemblies = *IntegrationTests.dll
- Search folder = $(System.DefaultWorkingDirectory)/DotNet-FunctionApp-CI/integration-tests
- Test filter criteria = TestCategory=IntegrationTests
- Select test platform using = Version
- Test paltform version = Latest
- Settings file = $(System.DefaultWorkingDirectory)/DotNet-FunctionApp-CI/integration-tests/TestRunParameters.runsettings
- Override test run parameters = -BaseUrl https://$(ResourceGroupName)-$(SlotName).azurewebsites.net/api/SampleHelloDotNetFunction
- Test run title = IntegrationTests
- Build Platform = $(ReleasePlatform)
- Build Configuration = $(ReleaseConfiguration)
Expand Down Expand Up @@ -133,6 +141,7 @@ TODO
- Script Arguments = -ResourceGroupName $(ResourceGroupName)
- Check Production URL
- Type = [Check URL Status](https://marketplace.visualstudio.com/items?itemName=saeidbabaei.checkUrl)
- Version = 1.*
- URL = https://$(ResourceGroupName).azurewebsites.net/api/SampleHelloDotNetFunction/test

### General remark
Expand Down Expand Up @@ -167,6 +176,7 @@ This environment should be used just if necessary when the bad things happened i
- Swap with Production = true
- Check Production URL
- Type = [Check URL Status](https://marketplace.visualstudio.com/items?itemName=saeidbabaei.checkUrl)
- Version = 1.*
- URL = https://$(ResourceGroupName).azurewebsites.net/api/SampleHelloDotNetFunction/test

# Deploy to Azure buttons
Expand Down
5 changes: 4 additions & 1 deletion docs/DotNet-FunctionApp-CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,13 @@ TODO
- Select tests using = Test assemblies
- Test assemblies = \**\$(BuildConfiguration)\*UnitTests.dll\n!**\obj\**
- Search folder = $(System.DefaultWorkingDirectory)
- Test filter criteria = TestCategory=UnitTests
- Select test platform using = Version
- Test platform version = Latest
- Code coverage enabled = true
- Test run title = UnitTests
- Build Platform = $(BuildPlatform)
- Build Configuration = $(BuildConfiguration)
- Upload test attachments = true
- Validate ARM Templates: production
- Type = Azure Resource Group Deployment
- Version = 2.*
Expand Down
Binary file modified docs/imgs/DotNet-FunctionApp-CD-Rollback.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/imgs/DotNet-FunctionApp-CD-Staging.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/imgs/DotNet-FunctionApp-CD.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 29 additions & 10 deletions src/DotNetFunction/SampleHelloDotNetFunction.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,50 @@
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace DotNetFunction
{
public static class SampleHelloDotNetFunction
{
[FunctionName("SampleHelloDotNetFunction")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "SampleHelloDotNetFunction/{name}")]HttpRequestMessage request, string name, TraceWriter log)
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")]HttpRequestMessage request)
{
var responseText = InternalSampleHelloDotNetFunction(name);
var name = request.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;

log?.Info($"Response text: {responseText}");
dynamic data = await request.Content.ReadAsAsync<object>();

return request.CreateResponse(HttpStatusCode.OK, responseText);
var responseMessage = string.Empty;
HttpStatusCode httpStatusCode = HttpStatusCode.OK;
if(!GetResponseMessage(name, data?.name, out responseMessage))
{
httpStatusCode = HttpStatusCode.BadRequest;
}

return request.CreateResponse(httpStatusCode, responseMessage);
}

public static string InternalSampleHelloDotNetFunction(string name)
/// <summary>
/// Get the response message to display according the name value passed either in the query string or in the request body.
/// Note: The query string has priority over the request body.
/// </summary>
/// <param name="nameInQueryString">The name value in the query string.</param>
/// <param name="nameInRequestBody">The name value in the request body.</param>
/// <param name="responseMessage">The out parameter containing the response message.</param>
/// <returns>Return true if an appropriate name was provided and set a response message accordingly. Otherwise return false and set an help message.</returns>
public static bool GetResponseMessage(string nameInQueryString, string nameInRequestBody, out string responseMessage)
{
var responseText = "Hello, World!";
var name = !string.IsNullOrWhiteSpace(nameInQueryString) ? nameInQueryString : nameInRequestBody;

if (!string.IsNullOrEmpty(name))
responseText = $"Hello, {name}!";
responseMessage = string.IsNullOrWhiteSpace(name)
? "Please pass a name on the query string or in the request body."
: $"Hello, {name}!";

return responseText;
return !string.IsNullOrWhiteSpace(name);
}
}
}
6 changes: 6 additions & 0 deletions test/DotNetFunction.IntegrationTests/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BaseUrl" value="#{BaseUrl}#"/>
</appSettings>
</configuration>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props')" />
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\xunit.runner.visualstudio.2.2.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\packages\xunit.runner.visualstudio.2.2.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
Expand All @@ -11,12 +12,6 @@
<AssemblyName>DotNetFunction.IntegrationTests</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
Expand All @@ -38,36 +33,48 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework">
<HintPath>..\..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions">
<HintPath>..\..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll</HintPath>
</Reference>
<Reference Include="xunit.assert, Version=2.2.0.3545, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.assert.2.2.0\lib\netstandard1.1\xunit.assert.dll</HintPath>
</Reference>
<Reference Include="xunit.core, Version=2.2.0.3545, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.core.2.2.0\lib\netstandard1.1\xunit.core.dll</HintPath>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.2.0.3545, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.execution.2.2.0\lib\net452\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="SampleHelloDotNetFunctionTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SampleHelloDotNetFunctionTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<Content Include="TestRunParameters.runsettings">
<None Include="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</None>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets'))" />
<Error Condition="!Exists('..\..\packages\xunit.runner.visualstudio.2.2.0\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\xunit.runner.visualstudio.2.2.0\build\net20\xunit.runner.visualstudio.props'))" />
</Target>
<Import Project="..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets')" />
</Project>
20 changes: 18 additions & 2 deletions test/DotNetFunction.IntegrationTests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System.Reflection;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DotNetFunction.IntegrationTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
Expand All @@ -11,10 +14,23 @@
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

[assembly: Guid("a6398be2-943a-4c33-b05d-e796cbb86cf4")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("05254f4f-38fe-467d-9916-8679165cd921")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -1,56 +1,84 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace DotNetFunction.IntegrationTests
{
[TestClass]
public class SampleHelloDotNetFunctionTests
{
public TestContext TestContext { get; set; }
private string BaseUrl = "http://localhost:7071/api/SampleHelloDotNetFunction";
private string BaseUrl = "https://localhost:7071/api/SampleHelloDotNetFunction";

[TestInitialize()]
public void TestInitialize()
public SampleHelloDotNetFunctionTests()
{
if (TestContext.Properties["BaseUrl"] != null)
{
//Set the BaseURL from a build
BaseUrl = TestContext.Properties["BaseUrl"].ToString();
}
var appSettings = ConfigurationManager.AppSettings;
var baseUrlParameter = appSettings["BaseUrl"];
BaseUrl = string.IsNullOrEmpty(baseUrlParameter) || baseUrlParameter == "#{BaseUrl}#" ? BaseUrl : baseUrlParameter;
}

[TestMethod]
[TestCategory("IntegrationTests")]
public async Task EmptyNameShouldSendNotFound()
[Fact]
public async Task Get_EmptyName_ShouldSendBadRequestAndHelpMessage()
{
//Arrange
var httpClient = new HttpClient();
var urlTested = BaseUrl;

//Act
var response = await httpClient.GetAsync(urlTested);
var text = await response.Content.ReadAsStringAsync();

//Assert
Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.BadRequest);
Assert.Equal(text, "Please pass a name on the query string or in the request body.");
}

[Fact]
public async Task Post_ShouldSendNotAllowed()
{
//Arrange
var httpClient = new HttpClient();
var urlTested = BaseUrl;
var name = "test";
var httpContent = new StringContent($"name={name}");

//Act
var response = await httpClient.PostAsync(urlTested, httpContent);

//Assert
Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.MethodNotAllowed);
}

[Fact]
public async Task Put_ShouldSendNotAllowed()
{
//Arrange
var httpClient = new HttpClient();
var urlTested = BaseUrl;
var name = "test";
var httpContent = new StringContent($"name={name}");

//Act
var response = await httpClient.PutAsync(urlTested, httpContent);

//Assert
Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.NotFound);
Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.MethodNotAllowed);
}

[TestMethod]
[TestCategory("IntegrationTests")]
[Fact]
public async Task NotEmptyNameShouldSendOK()
{
//Arrange
var httpClient = new HttpClient();
var nameTested = "john";
var urlTested = $"{BaseUrl}/{nameTested}";
var name = "john";
var urlTested = $"{BaseUrl}/{name}";

//Act
var response = await httpClient.GetAsync(urlTested);
var text = await response.Content.ReadAsStringAsync();

//Assert
Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK);
Assert.AreEqual(text, $"\"Hello, {nameTested}!\"");
Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK);
Assert.Equal(text, $"\"Hello, {name}!\"");
}

}
Expand Down

This file was deleted.

Loading