diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3a2238d --- /dev/null +++ b/.gitignore @@ -0,0 +1,245 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +[Xx]64/ +[Xx]86/ +[Bb]uild/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml + +# TODO: Un-comment the next line if you do not want to checkin +# your web deploy settings because they may include unencrypted +# passwords +#*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Microsoft Azure ApplicationInsights config file +ApplicationInsights.config + +# Windows Store app package directory +AppPackages/ +BundleArtifacts/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# LightSwitch generated files +GeneratedArtifacts/ +ModelManifest.xml + +# Paket dependency manager +.paket/paket.exe + +# FAKE - F# Make +.fake/ \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..a164233 --- /dev/null +++ b/README.txt @@ -0,0 +1,8 @@ +WCF Message Inspector +===================== + +1) This is a self hosting fileless(no .svc) WCF REST service with WCF Message Inspectors demo. +2) Using Message Inspectors in WCF, we can log the request and response of every call to the web method. + +Useful links: +http://patrickdesjardins.com/blog/wcf-inspector-for-logging \ No newline at end of file diff --git a/wcf-rest-message-inspector.sln b/wcf-rest-message-inspector.sln new file mode 100644 index 0000000..40aca5d --- /dev/null +++ b/wcf-rest-message-inspector.sln @@ -0,0 +1,27 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "wcf-rest-message-inspector", "wcf-rest-message-inspector\wcf-rest-message-inspector.csproj", "{587AAC15-282C-45B4-8F6D-0F4C325ED5B0}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{46469D0A-2AD7-4F67-8509-DF8AA9E62DDC}" + ProjectSection(SolutionItems) = preProject + README.txt = README.txt + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {587AAC15-282C-45B4-8F6D-0F4C325ED5B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {587AAC15-282C-45B4-8F6D-0F4C325ED5B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {587AAC15-282C-45B4-8F6D-0F4C325ED5B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {587AAC15-282C-45B4-8F6D-0F4C325ED5B0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/wcf-rest-message-inspector/Global.asax b/wcf-rest-message-inspector/Global.asax new file mode 100644 index 0000000..642658d --- /dev/null +++ b/wcf-rest-message-inspector/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="wcf_rest_message_inspector.Global" Language="C#" %> diff --git a/wcf-rest-message-inspector/Global.asax.cs b/wcf-rest-message-inspector/Global.asax.cs new file mode 100644 index 0000000..3a9d89e --- /dev/null +++ b/wcf-rest-message-inspector/Global.asax.cs @@ -0,0 +1,45 @@ +using System; +using System.ServiceModel.Activation; +using System.Web.Routing; + +namespace wcf_rest_message_inspector +{ + public class Global : System.Web.HttpApplication + { + + protected void Application_Start(object sender, EventArgs e) + { + RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(PersonService))); + } + + protected void Session_Start(object sender, EventArgs e) + { + + } + + protected void Application_BeginRequest(object sender, EventArgs e) + { + + } + + protected void Application_AuthenticateRequest(object sender, EventArgs e) + { + + } + + protected void Application_Error(object sender, EventArgs e) + { + + } + + protected void Session_End(object sender, EventArgs e) + { + + } + + protected void Application_End(object sender, EventArgs e) + { + + } + } +} \ No newline at end of file diff --git a/wcf-rest-message-inspector/Log.cs b/wcf-rest-message-inspector/Log.cs new file mode 100644 index 0000000..a073a3c --- /dev/null +++ b/wcf-rest-message-inspector/Log.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.ServiceModel.Channels; +using System.Xml; + +namespace wcf_rest_message_inspector +{ + public class Log + { + private Uri _uri; + private string _path; + private List _entries; + + public Log(string path, Uri uri) + { + _uri = uri; + _path = path; + _entries = new List(); + } + + public void Write(Message message, string methodName) + { + var settings = new XmlWriterSettings(); + + settings.OmitXmlDeclaration = true; + settings.Indent = true; + settings.NewLineHandling = NewLineHandling.None; // strip new line characters + settings.Indent = false; + + using (var sw = new StringWriter()) + using (var xw = XmlWriter.Create(sw, settings)) + { + message.WriteMessage(xw); + _entries.Add("URI - " + _uri); + xw.Flush(); + sw.Flush(); + _entries.Add("Method - " + methodName); + xw.Flush(); + sw.Flush(); + _entries.Add("Message - " + sw.ToString()); + File.AppendAllLines(_path, new string[] { "" }); + } + } + + public void Flush() + { + File.AppendAllLines(_path, _entries); + } + } +} \ No newline at end of file diff --git a/wcf-rest-message-inspector/MessageLoggingBehaviour.cs b/wcf-rest-message-inspector/MessageLoggingBehaviour.cs new file mode 100644 index 0000000..ac87188 --- /dev/null +++ b/wcf-rest-message-inspector/MessageLoggingBehaviour.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.ObjectModel; +using System.ServiceModel; +using System.ServiceModel.Channels; +using System.ServiceModel.Configuration; +using System.ServiceModel.Description; + +namespace wcf_rest_message_inspector +{ + public class MessageLoggingBehaviour : BehaviorExtensionElement, IEndpointBehavior, IServiceBehavior + { + public override Type BehaviorType + { + get { return typeof(MessageLoggingBehaviour); } + } + + protected override object CreateBehavior() + { + return new MessageLoggingBehaviour(); + } + + public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) + { + } + + public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) + { + } + + public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) + { + endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MessageLoggingInspector()); + } + + public void Validate(ServiceEndpoint endpoint) + { + } + + public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { + } + + public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters) + { + } + + public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { + } + } +} \ No newline at end of file diff --git a/wcf-rest-message-inspector/MessageLoggingInspector.cs b/wcf-rest-message-inspector/MessageLoggingInspector.cs new file mode 100644 index 0000000..6bede8b --- /dev/null +++ b/wcf-rest-message-inspector/MessageLoggingInspector.cs @@ -0,0 +1,33 @@ +using System.IO; +using System.ServiceModel; +using System.ServiceModel.Channels; +using System.ServiceModel.Dispatcher; + +namespace wcf_rest_message_inspector +{ + public class MessageLoggingInspector : IDispatchMessageInspector + { + private static Message CopyAndLogMessage(Log log, MessageBuffer buffer, string methodName) + { + var message = buffer.CreateMessage(); + log.Write(message, methodName); + return buffer.CreateMessage(); + } + + public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext) + { + var buffer = request.CreateBufferedCopy(int.MaxValue); + var path = Path.Combine(Path.GetTempPath(), "wcf-rest-log.txt"); + var log = new Log(path, request.Headers.To); + request = CopyAndLogMessage(log, buffer, "AfterReceiveRequest"); + return log; + } + + public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) + { + var log = (Log)correlationState; + reply = CopyAndLogMessage(log, reply.CreateBufferedCopy(int.MaxValue), "BeforeSendReply"); + log.Flush(); + } + } +} \ No newline at end of file diff --git a/wcf-rest-message-inspector/PersonService.cs b/wcf-rest-message-inspector/PersonService.cs new file mode 100644 index 0000000..8893309 --- /dev/null +++ b/wcf-rest-message-inspector/PersonService.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using System.ServiceModel; +using System.ServiceModel.Activation; +using System.ServiceModel.Web; + +namespace wcf_rest_message_inspector +{ + [ServiceContract] + interface IPersonService + { + [OperationContract] + [WebInvoke( + Method = "*", + UriTemplate = "Person/{id}", + ResponseFormat = WebMessageFormat.Json)] + Person GetPerson(string id); + + [OperationContract] + List GetPersons(); + } + + public class Person + { + public int id { get; set; } + public string name { get; set; } + } + + [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] + public class PersonService : IPersonService + { + [WebGet( + UriTemplate = "Persons", + ResponseFormat = WebMessageFormat.Xml)] + public List GetPersons() + { + List ps = new List(); + Person p = new Person(); + p.id = 1; + p.name = "Test 1"; + ps.Add(p); + p.id = 2; + p.name = "Test 2"; + ps.Add(p); + p.id = 3; + p.name = "Test 3"; + ps.Add(p); + return ps; + } + + public Person GetPerson(string id) + { + Person p = new Person(); + p.id = 1; + p.name = "Test"; + return p; + } + } +} \ No newline at end of file diff --git a/wcf-rest-message-inspector/Properties/AssemblyInfo.cs b/wcf-rest-message-inspector/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6a80413 --- /dev/null +++ b/wcf-rest-message-inspector/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +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("wcf_rest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("wcf_rest")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f302e264-2ebd-4d95-a3ad-6e4f6fc97339")] + +// 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 Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/wcf-rest-message-inspector/Web.Debug.config b/wcf-rest-message-inspector/Web.Debug.config new file mode 100644 index 0000000..2e302f9 --- /dev/null +++ b/wcf-rest-message-inspector/Web.Debug.config @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/wcf-rest-message-inspector/Web.Release.config b/wcf-rest-message-inspector/Web.Release.config new file mode 100644 index 0000000..c358444 --- /dev/null +++ b/wcf-rest-message-inspector/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/wcf-rest-message-inspector/Web.config b/wcf-rest-message-inspector/Web.config new file mode 100644 index 0000000..98492a6 --- /dev/null +++ b/wcf-rest-message-inspector/Web.config @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wcf-rest-message-inspector/wcf-rest-message-inspector.csproj b/wcf-rest-message-inspector/wcf-rest-message-inspector.csproj new file mode 100644 index 0000000..7babe5c --- /dev/null +++ b/wcf-rest-message-inspector/wcf-rest-message-inspector.csproj @@ -0,0 +1,119 @@ + + + + + Debug + AnyCPU + + + 2.0 + {587AAC15-282C-45B4-8F6D-0F4C325ED5B0} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + wcf_rest_message_inspector + wcf-rest-message-inspector + v4.0 + true + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Global.asax + + + + + + + + + + Web.config + + + Web.config + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 64138 + / + http://localhost:64138/ + False + False + + + False + + + + + + \ No newline at end of file