├── MyApplication ├── MyApplication │ ├── packages.config │ ├── ApplicationParameters │ │ ├── Cloud.xml │ │ ├── Local.1Node.xml │ │ └── Local.5Node.xml │ ├── PublishProfiles │ │ ├── Local.1Node.xml │ │ ├── Local.5Node.xml │ │ └── Cloud.xml │ ├── ApplicationPackageRoot │ │ └── ApplicationManifest.xml │ ├── MyApplication.sfproj │ └── Scripts │ │ └── Deploy-FabricApplication.ps1 ├── MyAspNetService │ ├── PackageRoot │ │ ├── Config │ │ │ └── Settings.xml │ │ └── ServiceManifest.xml │ ├── MyAspNetService.csproj │ ├── Startup.cs │ ├── Program.cs │ ├── MyAspNetService.cs │ └── ServiceEventSource.cs └── MyApplication.sln ├── README.md ├── .gitattributes └── .gitignore /MyApplication/MyApplication/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # azure-service-fabric-aspnetcore20-getting-started 2 | A simple Service Fabric Application that shows how to integrate Windows Authentication on a Reliable Service Stateless Service built on top of ASP.NET Core 2.0. 3 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/ApplicationParameters/Cloud.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/ApplicationParameters/Local.1Node.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/ApplicationParameters/Local.5Node.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/PackageRoot/Config/Settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/PublishProfiles/Local.1Node.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/PublishProfiles/Local.5Node.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/MyAspNetService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net461 5 | win7-x64 6 | True 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace MyAspNetService 11 | { 12 | public class Startup 13 | { 14 | // This method gets called by the runtime. Use this method to add services to the container. 15 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 16 | public void ConfigureServices(IServiceCollection services) 17 | { 18 | } 19 | 20 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 21 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 22 | { 23 | if (env.IsDevelopment()) 24 | { 25 | app.UseDeveloperExceptionPage(); 26 | } 27 | 28 | app.Run(async (context) => 29 | { 30 | await context.Response.WriteAsync("Hello World!"); 31 | }); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.ServiceFabric.Services.Runtime; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace MyAspNetService 8 | { 9 | internal static class Program 10 | { 11 | /// 12 | /// This is the entry point of the service host process. 13 | /// 14 | private static void Main() 15 | { 16 | try 17 | { 18 | // The ServiceManifest.XML file defines one or more service type names. 19 | // Registering a service maps a service type name to a .NET type. 20 | // When Service Fabric creates an instance of this service type, 21 | // an instance of the class is created in this host process. 22 | 23 | ServiceRuntime.RegisterServiceAsync("MyAspNetServiceType", 24 | context => new MyAspNetService(context)).GetAwaiter().GetResult(); 25 | 26 | ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(MyAspNetService).Name); 27 | 28 | // Prevents this host process from terminating so services keeps running. 29 | Thread.Sleep(Timeout.Infinite); 30 | } 31 | catch (Exception e) 32 | { 33 | ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); 34 | throw; 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/ApplicationPackageRoot/ApplicationManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/PackageRoot/ServiceManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | MyAspNetService.exe 18 | CodePackage 19 | 20 | 21 | 22 | 23 | 25 | 26 | 27 | 28 | 29 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/PublishProfiles/Cloud.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /MyApplication/MyApplication.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{A07B5EB6-E848-4116-A8D0-A826331D98C6}") = "MyApplication", "MyApplication\MyApplication.sfproj", "{E1FB605E-581E-4EAF-9315-088EC19C5D01}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyAspNetService", "MyAspNetService\MyAspNetService.csproj", "{EA7E800E-8CA2-40FE-8140-BF6D79C4483E}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Release|Any CPU = Release|Any CPU 15 | Release|x64 = Release|x64 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Debug|Any CPU.ActiveCfg = Debug|x64 19 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Debug|x64.ActiveCfg = Debug|x64 20 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Debug|x64.Build.0 = Debug|x64 21 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Debug|x64.Deploy.0 = Debug|x64 22 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Release|Any CPU.ActiveCfg = Release|x64 23 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Release|x64.ActiveCfg = Release|x64 24 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Release|x64.Build.0 = Release|x64 25 | {E1FB605E-581E-4EAF-9315-088EC19C5D01}.Release|x64.Deploy.0 = Release|x64 26 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Debug|x64.ActiveCfg = Debug|Any CPU 29 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Debug|x64.Build.0 = Debug|Any CPU 30 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Release|x64.ActiveCfg = Release|Any CPU 33 | {EA7E800E-8CA2-40FE-8140-BF6D79C4483E}.Release|x64.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | GlobalSection(ExtensibilityGlobals) = postSolution 39 | SolutionGuid = {CDEEACC4-98C2-4A7F-BC43-D6C8C2F973E5} 40 | EndGlobalSection 41 | EndGlobal 42 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/MyAspNetService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.AspNetCore.Server.HttpSys; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.ServiceFabric.Services.Communication.AspNetCore; 5 | using Microsoft.ServiceFabric.Services.Communication.Runtime; 6 | using Microsoft.ServiceFabric.Services.Runtime; 7 | using System.Collections.Generic; 8 | using System.Fabric; 9 | using System.IO; 10 | 11 | namespace MyAspNetService 12 | { 13 | /// 14 | /// The FabricRuntime creates an instance of this class for each service type instance. 15 | /// 16 | internal sealed class MyAspNetService : StatelessService 17 | { 18 | public MyAspNetService(StatelessServiceContext context) 19 | : base(context) 20 | { } 21 | 22 | /// 23 | /// Optional override to create listeners (like tcp, http) for this service instance. 24 | /// 25 | /// The collection of listeners. 26 | protected override IEnumerable CreateServiceInstanceListeners() 27 | { 28 | return new ServiceInstanceListener[] 29 | { 30 | new ServiceInstanceListener(serviceContext => 31 | new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) => 32 | { 33 | ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting WebListener on {url}"); 34 | 35 | return new WebHostBuilder() 36 | .UseHttpSys( 37 | options => 38 | { 39 | options.Authentication.Schemes = AuthenticationSchemes.Negotiate; // Microsoft.AspNetCore.Server.HttpSys 40 | options.Authentication.AllowAnonymous = false; 41 | /* Additional options */ 42 | //options.MaxConnections = 100; 43 | //options.MaxRequestBodySize = 30000000; 44 | //options.UrlPrefixes.Add("http://localhost:5000"); 45 | } 46 | ) 47 | .ConfigureServices( 48 | services => services 49 | .AddSingleton(serviceContext)) 50 | .UseContentRoot(Directory.GetCurrentDirectory()) 51 | .UseStartup() 52 | .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None) 53 | .UseUrls(url) 54 | .Build(); 55 | })) 56 | }; 57 | } 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/MyApplication.sfproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | e1fb605e-581e-4eaf-9315-088ec19c5d01 6 | 1.7 7 | 1.5 8 | 1.6 9 | v4.6.1 10 | 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Service Fabric Tools\Microsoft.VisualStudio.Azure.Fabric.ApplicationProject.targets 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /MyApplication/MyAspNetService/ServiceEventSource.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Tracing; 4 | using System.Fabric; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Microsoft.ServiceFabric.Services.Runtime; 9 | 10 | namespace MyAspNetService 11 | { 12 | [EventSource(Name = "MyCompany-MyApplication-MyAspNetService")] 13 | internal sealed class ServiceEventSource : EventSource 14 | { 15 | public static readonly ServiceEventSource Current = new ServiceEventSource(); 16 | 17 | static ServiceEventSource() 18 | { 19 | // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized. 20 | // This problem will be fixed in .NET Framework 4.6.2. 21 | Task.Run(() => { }); 22 | } 23 | 24 | // Instance constructor is private to enforce singleton semantics 25 | private ServiceEventSource() : base() { } 26 | 27 | #region Keywords 28 | // Event keywords can be used to categorize events. 29 | // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property). 30 | // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them. 31 | public static class Keywords 32 | { 33 | public const EventKeywords Requests = (EventKeywords)0x1L; 34 | public const EventKeywords ServiceInitialization = (EventKeywords)0x2L; 35 | } 36 | #endregion 37 | 38 | #region Events 39 | // Define an instance method for each event you want to record and apply an [Event] attribute to it. 40 | // The method name is the name of the event. 41 | // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed). 42 | // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event. 43 | // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent(). 44 | // Put [NonEvent] attribute on all methods that do not define an event. 45 | // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx 46 | 47 | [NonEvent] 48 | public void Message(string message, params object[] args) 49 | { 50 | if (this.IsEnabled()) 51 | { 52 | string finalMessage = string.Format(message, args); 53 | Message(finalMessage); 54 | } 55 | } 56 | 57 | private const int MessageEventId = 1; 58 | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] 59 | public void Message(string message) 60 | { 61 | if (this.IsEnabled()) 62 | { 63 | WriteEvent(MessageEventId, message); 64 | } 65 | } 66 | 67 | [NonEvent] 68 | public void ServiceMessage(ServiceContext serviceContext, string message, params object[] args) 69 | { 70 | if (this.IsEnabled()) 71 | { 72 | 73 | string finalMessage = string.Format(message, args); 74 | ServiceMessage( 75 | serviceContext.ServiceName.ToString(), 76 | serviceContext.ServiceTypeName, 77 | GetReplicaOrInstanceId(serviceContext), 78 | serviceContext.PartitionId, 79 | serviceContext.CodePackageActivationContext.ApplicationName, 80 | serviceContext.CodePackageActivationContext.ApplicationTypeName, 81 | serviceContext.NodeContext.NodeName, 82 | finalMessage); 83 | } 84 | } 85 | 86 | // For very high-frequency events it might be advantageous to raise events using WriteEventCore API. 87 | // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code. 88 | // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties. 89 | private const int ServiceMessageEventId = 2; 90 | [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")] 91 | private 92 | #if UNSAFE 93 | unsafe 94 | #endif 95 | void ServiceMessage( 96 | string serviceName, 97 | string serviceTypeName, 98 | long replicaOrInstanceId, 99 | Guid partitionId, 100 | string applicationName, 101 | string applicationTypeName, 102 | string nodeName, 103 | string message) 104 | { 105 | #if !UNSAFE 106 | WriteEvent(ServiceMessageEventId, serviceName, serviceTypeName, replicaOrInstanceId, partitionId, applicationName, applicationTypeName, nodeName, message); 107 | #else 108 | const int numArgs = 8; 109 | fixed (char* pServiceName = serviceName, pServiceTypeName = serviceTypeName, pApplicationName = applicationName, pApplicationTypeName = applicationTypeName, pNodeName = nodeName, pMessage = message) 110 | { 111 | EventData* eventData = stackalloc EventData[numArgs]; 112 | eventData[0] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) }; 113 | eventData[1] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) }; 114 | eventData[2] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) }; 115 | eventData[3] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) }; 116 | eventData[4] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) }; 117 | eventData[5] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) }; 118 | eventData[6] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) }; 119 | eventData[7] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) }; 120 | 121 | WriteEventCore(ServiceMessageEventId, numArgs, eventData); 122 | } 123 | #endif 124 | } 125 | 126 | private const int ServiceTypeRegisteredEventId = 3; 127 | [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}", Keywords = Keywords.ServiceInitialization)] 128 | public void ServiceTypeRegistered(int hostProcessId, string serviceType) 129 | { 130 | WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType); 131 | } 132 | 133 | private const int ServiceHostInitializationFailedEventId = 4; 134 | [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed", Keywords = Keywords.ServiceInitialization)] 135 | public void ServiceHostInitializationFailed(string exception) 136 | { 137 | WriteEvent(ServiceHostInitializationFailedEventId, exception); 138 | } 139 | 140 | // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity. 141 | // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities, 142 | // and other statistics. 143 | private const int ServiceRequestStartEventId = 5; 144 | [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)] 145 | public void ServiceRequestStart(string requestTypeName) 146 | { 147 | WriteEvent(ServiceRequestStartEventId, requestTypeName); 148 | } 149 | 150 | private const int ServiceRequestStopEventId = 6; 151 | [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)] 152 | public void ServiceRequestStop(string requestTypeName, string exception = "") 153 | { 154 | WriteEvent(ServiceRequestStopEventId, requestTypeName, exception); 155 | } 156 | #endregion 157 | 158 | #region Private methods 159 | private static long GetReplicaOrInstanceId(ServiceContext context) 160 | { 161 | StatelessServiceContext stateless = context as StatelessServiceContext; 162 | if (stateless != null) 163 | { 164 | return stateless.InstanceId; 165 | } 166 | 167 | StatefulServiceContext stateful = context as StatefulServiceContext; 168 | if (stateful != null) 169 | { 170 | return stateful.ReplicaId; 171 | } 172 | 173 | throw new NotSupportedException("Context type not supported."); 174 | } 175 | #if UNSAFE 176 | private int SizeInBytes(string s) 177 | { 178 | if (s == null) 179 | { 180 | return 0; 181 | } 182 | else 183 | { 184 | return (s.Length + 1) * sizeof(char); 185 | } 186 | } 187 | #endif 188 | #endregion 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /MyApplication/MyApplication/Scripts/Deploy-FabricApplication.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Deploys a Service Fabric application type to a cluster. 4 | 5 | .DESCRIPTION 6 | This script deploys a Service Fabric application type to a cluster. It is invoked by Visual Studio when deploying a Service Fabric Application project. 7 | 8 | .NOTES 9 | WARNING: This script file is invoked by Visual Studio. Its parameters must not be altered but its logic can be customized as necessary. 10 | 11 | .PARAMETER PublishProfileFile 12 | Path to the file containing the publish profile. 13 | 14 | .PARAMETER ApplicationPackagePath 15 | Path to the folder of the packaged Service Fabric application. 16 | 17 | .PARAMETER DeployOnly 18 | Indicates that the Service Fabric application should not be created or upgraded after registering the application type. 19 | 20 | .PARAMETER ApplicationParameter 21 | Hashtable of the Service Fabric application parameters to be used for the application. 22 | 23 | .PARAMETER UnregisterUnusedApplicationVersionsAfterUpgrade 24 | Indicates whether to unregister any unused application versions that exist after an upgrade is finished. 25 | 26 | .PARAMETER OverrideUpgradeBehavior 27 | Indicates the behavior used to override the upgrade settings specified by the publish profile. 28 | 'None' indicates that the upgrade settings will not be overridden. 29 | 'ForceUpgrade' indicates that an upgrade will occur with default settings, regardless of what is specified in the publish profile. 30 | 'VetoUpgrade' indicates that an upgrade will not occur, regardless of what is specified in the publish profile. 31 | 32 | .PARAMETER UseExistingClusterConnection 33 | Indicates that the script should make use of an existing cluster connection that has already been established in the PowerShell session. The cluster connection parameters configured in the publish profile are ignored. 34 | 35 | .PARAMETER OverwriteBehavior 36 | Overwrite Behavior if an application exists in the cluster with the same name. Available Options are Never, Always, SameAppTypeAndVersion. This setting is not applicable when upgrading an application. 37 | 'Never' will not remove the existing application. This is the default behavior. 38 | 'Always' will remove the existing application even if its Application type and Version is different from the application being created. 39 | 'SameAppTypeAndVersion' will remove the existing application only if its Application type and Version is same as the application being created. 40 | 41 | .PARAMETER SkipPackageValidation 42 | Switch signaling whether the package should be validated or not before deployment. 43 | 44 | .PARAMETER SecurityToken 45 | A security token for authentication to cluster management endpoints. Used for silent authentication to clusters that are protected by Azure Active Directory. 46 | 47 | .PARAMETER CopyPackageTimeoutSec 48 | Timeout in seconds for copying application package to image store. 49 | 50 | .EXAMPLE 51 | . Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' 52 | 53 | Deploy the application using the default package location for a Debug build. 54 | 55 | .EXAMPLE 56 | . Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' -DoNotCreateApplication 57 | 58 | Deploy the application but do not create the application instance. 59 | 60 | .EXAMPLE 61 | . Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' -ApplicationParameter @{CustomParameter1='MyValue'; CustomParameter2='MyValue'} 62 | 63 | Deploy the application by providing values for parameters that are defined in the application manifest. 64 | #> 65 | 66 | Param 67 | ( 68 | [String] 69 | $PublishProfileFile, 70 | 71 | [String] 72 | $ApplicationPackagePath, 73 | 74 | [Switch] 75 | $DeployOnly, 76 | 77 | [Hashtable] 78 | $ApplicationParameter, 79 | 80 | [Boolean] 81 | $UnregisterUnusedApplicationVersionsAfterUpgrade, 82 | 83 | [String] 84 | [ValidateSet('None', 'ForceUpgrade', 'VetoUpgrade')] 85 | $OverrideUpgradeBehavior = 'None', 86 | 87 | [Switch] 88 | $UseExistingClusterConnection, 89 | 90 | [String] 91 | [ValidateSet('Never','Always','SameAppTypeAndVersion')] 92 | $OverwriteBehavior = 'Never', 93 | 94 | [Switch] 95 | $SkipPackageValidation, 96 | 97 | [String] 98 | $SecurityToken, 99 | 100 | [int] 101 | $CopyPackageTimeoutSec 102 | ) 103 | 104 | function Read-XmlElementAsHashtable 105 | { 106 | Param ( 107 | [System.Xml.XmlElement] 108 | $Element 109 | ) 110 | 111 | $hashtable = @{} 112 | if ($Element.Attributes) 113 | { 114 | $Element.Attributes | 115 | ForEach-Object { 116 | $boolVal = $null 117 | if ([bool]::TryParse($_.Value, [ref]$boolVal)) { 118 | $hashtable[$_.Name] = $boolVal 119 | } 120 | else { 121 | $hashtable[$_.Name] = $_.Value 122 | } 123 | } 124 | } 125 | 126 | return $hashtable 127 | } 128 | 129 | function Read-PublishProfile 130 | { 131 | Param ( 132 | [ValidateScript({Test-Path $_ -PathType Leaf})] 133 | [String] 134 | $PublishProfileFile 135 | ) 136 | 137 | $publishProfileXml = [Xml] (Get-Content $PublishProfileFile) 138 | $publishProfile = @{} 139 | 140 | $publishProfile.ClusterConnectionParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("ClusterConnectionParameters") 141 | $publishProfile.UpgradeDeployment = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment") 142 | $publishProfile.CopyPackageParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("CopyPackageParameters") 143 | 144 | if ($publishProfileXml.PublishProfile.Item("UpgradeDeployment")) 145 | { 146 | $publishProfile.UpgradeDeployment.Parameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment").Item("Parameters") 147 | if ($publishProfile.UpgradeDeployment["Mode"]) 148 | { 149 | $publishProfile.UpgradeDeployment.Parameters[$publishProfile.UpgradeDeployment["Mode"]] = $true 150 | } 151 | } 152 | 153 | $publishProfileFolder = (Split-Path $PublishProfileFile) 154 | $publishProfile.ApplicationParameterFile = [System.IO.Path]::Combine($PublishProfileFolder, $publishProfileXml.PublishProfile.ApplicationParameterFile.Path) 155 | 156 | return $publishProfile 157 | } 158 | 159 | $LocalFolder = (Split-Path $MyInvocation.MyCommand.Path) 160 | 161 | if (!$PublishProfileFile) 162 | { 163 | $PublishProfileFile = "$LocalFolder\..\PublishProfiles\Local.xml" 164 | } 165 | 166 | if (!$ApplicationPackagePath) 167 | { 168 | $ApplicationPackagePath = "$LocalFolder\..\pkg\Release" 169 | } 170 | 171 | $ApplicationPackagePath = Resolve-Path $ApplicationPackagePath 172 | 173 | $publishProfile = Read-PublishProfile $PublishProfileFile 174 | 175 | if (-not $UseExistingClusterConnection) 176 | { 177 | $ClusterConnectionParameters = $publishProfile.ClusterConnectionParameters 178 | if ($SecurityToken) 179 | { 180 | $ClusterConnectionParameters["SecurityToken"] = $SecurityToken 181 | } 182 | 183 | try 184 | { 185 | [void](Connect-ServiceFabricCluster @ClusterConnectionParameters) 186 | } 187 | catch [System.Fabric.FabricObjectClosedException] 188 | { 189 | Write-Warning "Service Fabric cluster may not be connected." 190 | throw 191 | } 192 | } 193 | 194 | $RegKey = "HKLM:\SOFTWARE\Microsoft\Service Fabric SDK" 195 | $ModuleFolderPath = (Get-ItemProperty -Path $RegKey -Name FabricSDKPSModulePath).FabricSDKPSModulePath 196 | Import-Module "$ModuleFolderPath\ServiceFabricSDK.psm1" 197 | 198 | $IsUpgrade = ($publishProfile.UpgradeDeployment -and $publishProfile.UpgradeDeployment.Enabled -and $OverrideUpgradeBehavior -ne 'VetoUpgrade') -or $OverrideUpgradeBehavior -eq 'ForceUpgrade' 199 | 200 | $PublishParameters = @{ 201 | 'ApplicationPackagePath' = $ApplicationPackagePath 202 | 'ApplicationParameterFilePath' = $publishProfile.ApplicationParameterFile 203 | 'ApplicationParameter' = $ApplicationParameter 204 | 'ErrorAction' = 'Stop' 205 | } 206 | 207 | if ($publishProfile.CopyPackageParameters.CopyPackageTimeoutSec) 208 | { 209 | $PublishParameters['CopyPackageTimeoutSec'] = $publishProfile.CopyPackageParameters.CopyPackageTimeoutSec 210 | } 211 | 212 | if ($publishProfile.CopyPackageParameters.CompressPackage) 213 | { 214 | $PublishParameters['CompressPackage'] = $publishProfile.CopyPackageParameters.CompressPackage 215 | } 216 | 217 | # CopyPackageTimeoutSec parameter overrides the value from the publish profile 218 | if ($CopyPackageTimeoutSec) 219 | { 220 | $PublishParameters['CopyPackageTimeoutSec'] = $CopyPackageTimeoutSec 221 | } 222 | 223 | if ($IsUpgrade) 224 | { 225 | $Action = "RegisterAndUpgrade" 226 | if ($DeployOnly) 227 | { 228 | $Action = "Register" 229 | } 230 | 231 | $UpgradeParameters = $publishProfile.UpgradeDeployment.Parameters 232 | 233 | if ($OverrideUpgradeBehavior -eq 'ForceUpgrade') 234 | { 235 | # Warning: Do not alter these upgrade parameters. It will create an inconsistency with Visual Studio's behavior. 236 | $UpgradeParameters = @{ UnmonitoredAuto = $true; Force = $true } 237 | } 238 | 239 | $PublishParameters['Action'] = $Action 240 | $PublishParameters['UpgradeParameters'] = $UpgradeParameters 241 | $PublishParameters['UnregisterUnusedVersions'] = $UnregisterUnusedApplicationVersionsAfterUpgrade 242 | 243 | Publish-UpgradedServiceFabricApplication @PublishParameters 244 | } 245 | else 246 | { 247 | $Action = "RegisterAndCreate" 248 | if ($DeployOnly) 249 | { 250 | $Action = "Register" 251 | } 252 | 253 | $PublishParameters['Action'] = $Action 254 | $PublishParameters['OverwriteBehavior'] = $OverwriteBehavior 255 | $PublishParameters['SkipPackageValidation'] = $SkipPackageValidation 256 | 257 | Publish-NewServiceFabricApplication @PublishParameters 258 | } --------------------------------------------------------------------------------