master 7135b8ca6ee9 cached
25 files
49.8 KB
13.0k tokens
31 symbols
1 requests
Download .txt
Repository: danesparza/OWIN-WebAPI-Service
Branch: master
Commit: 7135b8ca6ee9
Files: 25
Total size: 49.8 KB

Directory structure:
gitextract_jqyd6uxk/

├── .gitignore
├── .nuget/
│   ├── NuGet.Config
│   └── NuGet.targets
├── LICENSE
├── OWINTest.API/
│   ├── OWINTest.API.csproj
│   ├── Properties/
│   │   └── AssemblyInfo.cs
│   ├── ValuesController.cs
│   └── packages.config
├── OWINTest.Service/
│   ├── API/
│   │   ├── PersonController.cs
│   │   └── RoutedController.cs
│   ├── APIServiceTest.Designer.cs
│   ├── APIServiceTest.cs
│   ├── App.config
│   ├── OWINTest.Service.csproj
│   ├── Program.cs
│   ├── ProjectInstaller.Designer.cs
│   ├── ProjectInstaller.cs
│   ├── ProjectInstaller.resx
│   ├── Properties/
│   │   └── AssemblyInfo.cs
│   ├── Startup.cs
│   ├── install.cmd
│   ├── packages.config
│   └── uninstall.cmd
├── OWINTest.sln
└── README.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)
[Bb]in/
[Oo]bj/

# mstest test results
TestResults

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.sln.docstates

# Build results
[Dd]ebug/
[Rr]elease/
x64/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.log
*.vspscc
*.vssscc
.builds

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf

# Visual Studio profiler
*.psess
*.vsp
*.vspx

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*

# NCrunch
*.ncrunch*
.*crunch*.local.xml

# 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
*.Publish.xml

# NuGet Packages Directory
packages

# Windows Azure Build Output
csx
*.build.csdef

# Windows Store app package directory
AppPackages/

# Others
[Bb]in
[Oo]bj
sql
TestResults
[Tt]est[Rr]esult*
*.Cache
ClientBin
[Ss]tyle[Cc]op.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects

# 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


================================================
FILE: .nuget/NuGet.Config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
</configuration>

================================================
FILE: .nuget/NuGet.targets
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>

        <!-- Enable the restore command to run before builds -->
        <RestorePackages Condition="  '$(RestorePackages)' == '' ">false</RestorePackages>

        <!-- Property that enables building a package from a project -->
        <BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>

        <!-- Determines if package restore consent is required to restore packages -->
        <RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>

        <!-- Download NuGet.exe if it does not already exist -->
        <DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
    </PropertyGroup>

    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
        <!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
        <!--
            <PackageSource Include="https://www.nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
    </ItemGroup>

    <PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
        <!-- Windows specific commands -->
        <NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
    </PropertyGroup>

    <PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
        <!-- We need to launch nuget.exe with the mono command if we're not on windows -->
        <NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
    </PropertyGroup>

    <PropertyGroup>
        <PackagesProjectConfig Condition=" '$(OS)' == 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
        <PackagesProjectConfig Condition=" '$(OS)' != 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config</PackagesProjectConfig>
    </PropertyGroup>

    <PropertyGroup>
      <PackagesConfig Condition="Exists('$(MSBuildProjectDirectory)\packages.config')">$(MSBuildProjectDirectory)\packages.config</PackagesConfig>
      <PackagesConfig Condition="Exists('$(PackagesProjectConfig)')">$(PackagesProjectConfig)</PackagesConfig>
    </PropertyGroup>
    
    <PropertyGroup>
        <!-- NuGet command -->
        <NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
        <PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>

        <NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
        <NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 "$(NuGetExePath)"</NuGetCommand>

        <PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>

        <RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
        <NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>

        <PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
        <PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>

        <!-- Commands -->
        <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
        <BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>

        <!-- We need to ensure packages are restored prior to assembly resolve -->
        <BuildDependsOn Condition="$(RestorePackages) == 'true'">
            RestorePackages;
            $(BuildDependsOn);
        </BuildDependsOn>

        <!-- Make the build depend on restore packages -->
        <BuildDependsOn Condition="$(BuildPackage) == 'true'">
            $(BuildDependsOn);
            BuildPackage;
        </BuildDependsOn>
    </PropertyGroup>

    <Target Name="CheckPrerequisites">
        <!-- Raise an error if we're unable to locate nuget.exe  -->
        <Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
        <!--
        Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
        This effectively acts as a lock that makes sure that the download operation will only happen once and all
        parallel builds will have to wait for it to complete.
        -->
        <MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
    </Target>

    <Target Name="_DownloadNuGet">
        <DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
    </Target>

    <Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">        
        <Exec Command="$(RestoreCommand)"
              Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />

        <Exec Command="$(RestoreCommand)"
              LogStandardErrorAsError="true"
              Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
    </Target>

    <Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
        <Exec Command="$(BuildCommand)"
              Condition=" '$(OS)' != 'Windows_NT' " />

        <Exec Command="$(BuildCommand)"
              LogStandardErrorAsError="true"
              Condition=" '$(OS)' == 'Windows_NT' " />
    </Target>

    <UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
            <OutputFilename ParameterType="System.String" Required="true" />
        </ParameterGroup>
        <Task>
            <Reference Include="System.Core" />
            <Using Namespace="System" />
            <Using Namespace="System.IO" />
            <Using Namespace="System.Net" />
            <Using Namespace="Microsoft.Build.Framework" />
            <Using Namespace="Microsoft.Build.Utilities" />
            <Code Type="Fragment" Language="cs">
                <![CDATA[
                try {
                    OutputFilename = Path.GetFullPath(OutputFilename);

                    Log.LogMessage("Downloading latest version of NuGet.exe...");
                    WebClient webClient = new WebClient();
                    webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);

                    return true;
                }
                catch (Exception ex) {
                    Log.LogErrorFromException(ex);
                    return false;
                }
            ]]>
            </Code>
        </Task>
    </UsingTask>
</Project>


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2014 Dan Esparza

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: OWINTest.API/OWINTest.API.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <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>
    <ProjectGuid>{1671F393-642C-46EA-9FA7-58F53818E724}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>OWINTest.API</RootNamespace>
    <AssemblyName>OWINTest.API</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
    <RestorePackages>true</RestorePackages>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Newtonsoft.Json">
      <HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Net.Http.Formatting, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.1.0\lib\net45\System.Net.Http.Formatting.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Http, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.1.0\lib\net45\System.Web.Http.dll</HintPath>
    </Reference>
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="ValuesController.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable 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('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: OWINTest.API/Properties/AssemblyInfo.cs
================================================
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("OWINTest.API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWINTest.API")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[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("d611539e-d658-4ebf-948e-98cc39d62ccf")]

// 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")]


================================================
FILE: OWINTest.API/ValuesController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace OWINTest.API
{
    public class ValuesController : ApiController
    {
        // GET api/values 
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5 
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values 
        public void Post([FromBody]string value)
        {

        }

        // PUT api/values/5 
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/values/5 
        public void Delete(int id)
        {

        } 
    }
}


================================================
FILE: OWINTest.API/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.1.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="13.0.1" targetFramework="net45" />
</packages>

================================================
FILE: OWINTest.Service/API/PersonController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace OWINTest.Service.API
{
    public class PersonController : ApiController
    {
        // GET api/values 
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5 
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values 
        public void Post([FromBody]string value)
        {

        }

        // PUT api/values/5 
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/values/5 
        public void Delete(int id)
        {

        } 
    }
}


================================================
FILE: OWINTest.Service/API/RoutedController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace OWINTest.Service.API
{
    [RoutePrefix("api/testing")]
    public class RoutedController : ApiController
    {
        [Route("getall")]
        public IEnumerable<string> GetAllItems()
        {
            return new string[] { "value1", "value2" };
        }
    }
}


================================================
FILE: OWINTest.Service/APIServiceTest.Designer.cs
================================================
namespace OWINTest.Service
{
    partial class APIServiceTest
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if(disposing)
            {
                if (_server != null)
                {
                    _server.Dispose();
                }
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "Service1";
        }

        #endregion
    }
}


================================================
FILE: OWINTest.Service/APIServiceTest.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;

namespace OWINTest.Service
{
    public partial class APIServiceTest : ServiceBase
    {
        public string baseAddress = "http://localhost:9000/";
        private IDisposable _server = null;
        
        public APIServiceTest()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _server = WebApp.Start<Startup>(url: baseAddress);
        }

        protected override void OnStop()
        {
            if(_server != null)
            {
                _server.Dispose();
            }
            base.OnStop();
        }
    }
}


================================================
FILE: OWINTest.Service/App.config
================================================
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

================================================
FILE: OWINTest.Service/OWINTest.Service.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <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>
    <ProjectGuid>{040449FC-D996-49AF-BD74-D137D5688992}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>OWINTest.Service</RootNamespace>
    <AssemblyName>OWINTest.Service</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
    <RestorePackages>true</RestorePackages>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.Owin">
      <HintPath>..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Host.HttpListener">
      <HintPath>..\packages\Microsoft.Owin.Host.HttpListener.2.0.2\lib\net45\Microsoft.Owin.Host.HttpListener.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Hosting">
      <HintPath>..\packages\Microsoft.Owin.Hosting.2.0.2\lib\net45\Microsoft.Owin.Hosting.dll</HintPath>
    </Reference>
    <Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="Owin">
      <HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Configuration.Install" />
    <Reference Include="System.Core" />
    <Reference Include="System.Management" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Net.Http.Formatting, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.1.0\lib\net45\System.Net.Http.Formatting.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Http, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.1.0\lib\net45\System.Web.Http.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Http.Owin">
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Owin.5.1.0\lib\net45\System.Web.Http.Owin.dll</HintPath>
    </Reference>
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.ServiceProcess" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="APIServiceTest.cs">
      <SubType>Component</SubType>
    </Compile>
    <Compile Include="APIServiceTest.Designer.cs">
      <DependentUpon>APIServiceTest.cs</DependentUpon>
    </Compile>
    <Compile Include="API\PersonController.cs" />
    <Compile Include="API\RoutedController.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="ProjectInstaller.cs">
      <SubType>Component</SubType>
    </Compile>
    <Compile Include="ProjectInstaller.Designer.cs">
      <DependentUpon>ProjectInstaller.cs</DependentUpon>
    </Compile>
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Startup.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
    <Content Include="install.cmd">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
    <None Include="packages.config" />
    <Content Include="uninstall.cmd">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\OWINTest.API\OWINTest.API.csproj">
      <Project>{1671f393-642c-46ea-9fa7-58f53818e724}</Project>
      <Name>OWINTest.API</Name>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <EmbeddedResource Include="ProjectInstaller.resx">
      <DependentUpon>ProjectInstaller.cs</DependentUpon>
    </EmbeddedResource>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable 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('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: OWINTest.Service/Program.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace OWINTest.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new APIServiceTest() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}


================================================
FILE: OWINTest.Service/ProjectInstaller.Designer.cs
================================================
namespace OWINTest.Service
{
    partial class ProjectInstaller
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if(disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            // 
            // serviceProcessInstaller1
            // 
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            // 
            // serviceInstaller1
            // 
            this.serviceInstaller1.DisplayName = "OWIN Service Test";
            this.serviceInstaller1.ServiceName = "OWINServiceTest";
            this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
            // 
            // ProjectInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller1,
            this.serviceInstaller1});

        }

        #endregion

        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;
    }
}

================================================
FILE: OWINTest.Service/ProjectInstaller.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;

namespace OWINTest.Service
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {

        }
    }
}


================================================
FILE: OWINTest.Service/ProjectInstaller.resx
================================================
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!-- 
    Microsoft ResX Schema 
    
    Version 2.0
    
    The primary goals of this format is to allow a simple XML format 
    that is mostly human readable. The generation and parsing of the 
    various data types are done through the TypeConverter classes 
    associated with the data types.
    
    Example:
    
    ... ado.net/XML headers & schema ...
    <resheader name="resmimetype">text/microsoft-resx</resheader>
    <resheader name="version">2.0</resheader>
    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>[base64 mime encoded serialized .NET Framework object]</value>
    </data>
    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
        <comment>This is a comment</comment>
    </data>
                
    There are any number of "resheader" rows that contain simple 
    name/value pairs.
    
    Each data row contains a name, and value. The row also contains a 
    type or mimetype. Type corresponds to a .NET class that support 
    text/value conversion through the TypeConverter architecture. 
    Classes that don't support this are serialized and stored with the 
    mimetype set.
    
    The mimetype is used for serialized objects, and tells the 
    ResXResourceReader how to depersist the object. This is currently not 
    extensible. For a given mimetype the value must be set accordingly:
    
    Note - application/x-microsoft.net.object.binary.base64 is the format 
    that the ResXResourceWriter will generate, however the reader can 
    read any of the formats listed below.
    
    mimetype: application/x-microsoft.net.object.binary.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            : and then encoded with base64 encoding.
    
    mimetype: application/x-microsoft.net.object.soap.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.bytearray.base64
    value   : The object must be serialized into a byte array 
            : using a System.ComponentModel.TypeConverter
            : and then encoded with base64 encoding.
    -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <metadata name="serviceProcessInstaller1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
    <value>17, 56</value>
  </metadata>
  <metadata name="serviceInstaller1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
    <value>196, 17</value>
  </metadata>
  <metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
</root>

================================================
FILE: OWINTest.Service/Properties/AssemblyInfo.cs
================================================
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("OWINTest.Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWINTest.Service")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[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("3c680edc-55b3-4c07-885e-15adc849c05e")]

// 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")]


================================================
FILE: OWINTest.Service/Startup.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Owin;

namespace OWINTest.Service
{
    class Startup
    {
        //  Hack from http://stackoverflow.com/a/17227764/19020 to load controllers in 
        //  another assembly.  Another way to do this is to create a custom assembly resolver
        Type valuesControllerType = typeof(OWINTest.API.ValuesController);

        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            
            //  Enable attribute based routing
            //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseWebApi(config);
        } 
    }
}


================================================
FILE: OWINTest.Service/install.cmd
================================================
path = %path%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;

installutil OWINTest.Service.exe

pause

================================================
FILE: OWINTest.Service/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.OwinSelfHost" version="5.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin" version="4.2.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.HttpListener" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Hosting" version="2.0.2" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="13.0.1" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
</packages>

================================================
FILE: OWINTest.Service/uninstall.cmd
================================================
path = %path%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;

installutil /u OWINTest.Service.exe

pause

================================================
FILE: OWINTest.sln
================================================

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30110.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OWINTest.Service", "OWINTest.Service\OWINTest.Service.csproj", "{040449FC-D996-49AF-BD74-D137D5688992}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OWINTest.API", "OWINTest.API\OWINTest.API.csproj", "{1671F393-642C-46EA-9FA7-58F53818E724}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{A89D3C9D-EDE8-4518-92A7-045C5DB112A5}"
	ProjectSection(SolutionItems) = preProject
		.nuget\NuGet.Config = .nuget\NuGet.Config
		.nuget\NuGet.exe = .nuget\NuGet.exe
		.nuget\NuGet.targets = .nuget\NuGet.targets
	EndProjectSection
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{040449FC-D996-49AF-BD74-D137D5688992}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{040449FC-D996-49AF-BD74-D137D5688992}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{040449FC-D996-49AF-BD74-D137D5688992}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{040449FC-D996-49AF-BD74-D137D5688992}.Release|Any CPU.Build.0 = Release|Any CPU
		{1671F393-642C-46EA-9FA7-58F53818E724}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{1671F393-642C-46EA-9FA7-58F53818E724}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{1671F393-642C-46EA-9FA7-58F53818E724}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{1671F393-642C-46EA-9FA7-58F53818E724}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


================================================
FILE: README.md
================================================
OWIN WebAPI Service example [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
===========================

Sometimes, you just need a good example to get started.  

The [OWIN-WebAPI-Service project](https://github.com/danesparza/OWIN-WebAPI-Service) came out of a need to create a self-hosted WebAPI 2 service in a Windows service.  Microsoft says that going forward, [OWIN is the way to go](http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api).  I wanted to use [attribute routing](http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2) in WebAPI 2.  I couldn't find a decent example anywhere, so I created my own. 

*Please be aware that OWIN (and this project template) are only compatible with .NET 4.5 and newer projects.* 

## If starting from scratch:

### Create the service project ###
If you're starting from scratch, add a new service project to your solution by selecting **'Windows Service'** in the new project template.

### Add the OWIN Nuget packages ###

From the package manager console: 

```powershell
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
```

This will install the following dependent packages automatically:
* Microsoft.AspNet.WebApi.Client
* Microsoft.AspNet.WebApi.Core
* Microsoft.AspNet.WebApi.Owin
* Microsoft.AspNet.WebApi.OwinSelfHost
* Microsoft.Owin
* Microsoft.Owin.Host.HttpListener
* Microsoft.Owin.Hosting
* Newtonsoft.Json
* Owin

### Create an OWIN configuration handler
Create the file `Startup.cs` and put a configuration handler in it:

```CSharp
class Startup
{
    //  Hack from http://stackoverflow.com/a/17227764/19020 to load controllers in 
    //  another assembly.  Another way to do this is to create a custom assembly resolver
    Type valuesControllerType = typeof(OWINTest.API.ValuesController);

    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        
        //  Enable attribute based routing
        //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    } 
}
```
    
Note that:
* You can load API controllers from another assembly by using the hack `Type valuesControllerType = typeof(OWINTest.API.ValuesController);` or by creating a [custom assembly resolver](http://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/)
* You can use Attribute based routing by including the line `config.MapHttpAttributeRoutes()` before the default `config.Routes.MapHttpRoute`

### Add API controllers
Add API controllers to the service project by creating classes inherited from `ApiController`.  Here is a simple example that uses attribute based routing:

```CSharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace OWINTest.Service.API
{
    [RoutePrefix("api/testing")]
    public class RoutedController : ApiController
    {
        [Route("getall")]
        public IEnumerable<string> GetAllItems()
        {
            return new string[] { "value1", "value2" };
        }
    }
}
```

Note that:
* Controllers in the service assembly will be loaded automatically.
* If you want to load a controller in another assembly, you'll need to update your `Startup.cs` file (and read the note about loading controllers from other assemblies, above)

### Add code to start/stop the WebAPI listener

Add code to the default service (inherited from `ServiceBase`) that the Visual Studio template created for you.  The finished service class should look something like this:

```CSharp
public partial class APIServiceTest : ServiceBase
{
    public string baseAddress = "http://localhost:9000/";
    private IDisposable _server = null;
    
    public APIServiceTest()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _server = WebApp.Start<Startup>(url: baseAddress);
    }

    protected override void OnStop()
    {
        if(_server != null)
        {
            _server.Dispose();
        }
        base.OnStop();
    }
}
```

See how simple that is?  
* In the `OnStart` handler, we start the listener and pass our `Startup` class we created.  That calls our configuration handler.
* In the `OnStop` handler, we just stop the listener
* The service will be listening with a base location of `http://localhost:9000`.

### Install the service
Create a service installer by right-clicking on the service design surface and selecting 'Add installer' from the context menu.  You can update the service name, description, [startup mode](http://superuser.com/a/285655/4508) and [default credentials](http://stackoverflow.com/a/510225/19020) by updating the properties on the 2 new controls that are added.  

After you've [added the service installer](http://msdn.microsoft.com/en-us/library/ddhy0byf(v=vs.110).aspx) by updating the service code, install the service using the [.NET installutil.exe](http://msdn.microsoft.com/en-us/library/50614e95(v=vs.110).aspx).  See the sample batch files `install.cmd` and `uninstall.cmd` for an example of making this a little easier on yourself.

### Stuff to try
Now that you've compiled and installed your service, start it up in the 'Services' app in the control panel.  
* If you've added the `RoutedController` example above, try navigating to the following url in [Postman](http://www.getpostman.com/) or your favorite REST service tester: `http://localhost:9000/api/testing/getall` -- you should get a JSON string array back.  
* Try hitting breakpoints in your running service in Visual Studio by selecting 'Debug/Attach to Process'.  Select your running service exe, then press 'Attach'.  
* Try calling the service directly from a browser-based single page application.  (Hint:  You won't be able to until you [enable CORS](http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api))

## Tips

### Building the sample service

So if you just want to take a look at the sample project, you'll need to either grab the zip or [clone the project](https://help.github.com/articles/which-remote-url-should-i-use/) in git.

Before you build and install the service you'll need to do a 'Nuget package restore'. The easiest way to do this is probably to right-click on the solution in Visual Studio and select 'Manage Nuget packages for solution...'

You should see the 'Manage NuGet Packages' screen pop up. At the very top of the screen, you'll probably see a yellow message indicating that 'Some NuGet packages are missing from this solution. Click to restore from your online package sources.' with a Restore button. Go ahead and click Restore and then close the window once the missing packages have been downloaded.

Try your build again after that, and you should be good.

### Installing the service

You'll need to run the `installutil` command as an Administrator.  To do that, you'll need to [run the command prompt itself as Administrator](https://technet.microsoft.com/en-us/library/cc947813%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396), or use [other interesting tricks](http://stackoverflow.com/a/12401075/19020)

### Serving more than just localhost

If you want to listen to all requests coming in a certain port -- not just localhost requests, you'll need to know a few things.  

**First**, understand [there are permission differences between Local System, Local service, Network service](http://stackoverflow.com/a/510225/19020), and a user account.  I recommend you run under 'Local service' because it's a minimal set of permissions. 

**Second**, you'll need to change the code that starts the service.  Instead of listening for requests to `http://localhost:9000`, you'll need to listen for requests to `http://+:9000`.  

**Third**, you'll need to use the command-line tool `netsh` to authorize 'Local Service' to listen for requests.  I usually put this command in the **install.bat** file that installs the service: 

```bash
netsh http add urlacl url=http://+:9000/ user="Local Service"
```

Without this, you'll have problems starting the service and listening to all requests for that port.

### Help -- I'm getting Error 1053 when trying to start the service

If you're getting `Error 1053: The service did not respond to the start or control request in a timely fashion.` there is a good chance you don't have the right version of the .NET framework installed.  Remember: OWIN and WebAPI 2 require .NET 4.5 or a more recent version of the framework to be installed.


Download .txt
gitextract_jqyd6uxk/

├── .gitignore
├── .nuget/
│   ├── NuGet.Config
│   └── NuGet.targets
├── LICENSE
├── OWINTest.API/
│   ├── OWINTest.API.csproj
│   ├── Properties/
│   │   └── AssemblyInfo.cs
│   ├── ValuesController.cs
│   └── packages.config
├── OWINTest.Service/
│   ├── API/
│   │   ├── PersonController.cs
│   │   └── RoutedController.cs
│   ├── APIServiceTest.Designer.cs
│   ├── APIServiceTest.cs
│   ├── App.config
│   ├── OWINTest.Service.csproj
│   ├── Program.cs
│   ├── ProjectInstaller.Designer.cs
│   ├── ProjectInstaller.cs
│   ├── ProjectInstaller.resx
│   ├── Properties/
│   │   └── AssemblyInfo.cs
│   ├── Startup.cs
│   ├── install.cmd
│   ├── packages.config
│   └── uninstall.cmd
├── OWINTest.sln
└── README.md
Download .txt
SYMBOL INDEX (31 symbols across 9 files)

FILE: OWINTest.API/ValuesController.cs
  class ValuesController (line 10) | public class ValuesController : ApiController
    method Get (line 13) | public IEnumerable<string> Get()
    method Get (line 19) | public string Get(int id)
    method Post (line 25) | public void Post([FromBody]string value)
    method Put (line 31) | public void Put(int id, [FromBody]string value)
    method Delete (line 37) | public void Delete(int id)

FILE: OWINTest.Service/API/PersonController.cs
  class PersonController (line 10) | public class PersonController : ApiController
    method Get (line 13) | public IEnumerable<string> Get()
    method Get (line 19) | public string Get(int id)
    method Post (line 25) | public void Post([FromBody]string value)
    method Put (line 31) | public void Put(int id, [FromBody]string value)
    method Delete (line 37) | public void Delete(int id)

FILE: OWINTest.Service/API/RoutedController.cs
  class RoutedController (line 10) | [RoutePrefix("api/testing")]
    method GetAllItems (line 13) | [Route("getall")]

FILE: OWINTest.Service/APIServiceTest.Designer.cs
  class APIServiceTest (line 3) | partial class APIServiceTest
    method Dispose (line 14) | protected override void Dispose(bool disposing)
    method InitializeComponent (line 36) | private void InitializeComponent()

FILE: OWINTest.Service/APIServiceTest.cs
  class APIServiceTest (line 14) | public partial class APIServiceTest : ServiceBase
    method APIServiceTest (line 19) | public APIServiceTest()
    method OnStart (line 24) | protected override void OnStart(string[] args)
    method OnStop (line 29) | protected override void OnStop()

FILE: OWINTest.Service/Program.cs
  class Program (line 10) | static class Program
    method Main (line 15) | static void Main()

FILE: OWINTest.Service/ProjectInstaller.Designer.cs
  class ProjectInstaller (line 3) | partial class ProjectInstaller
    method Dispose (line 14) | protected override void Dispose(bool disposing)
    method InitializeComponent (line 29) | private void InitializeComponent()

FILE: OWINTest.Service/ProjectInstaller.cs
  class ProjectInstaller (line 11) | [RunInstaller(true)]
    method ProjectInstaller (line 14) | public ProjectInstaller()
    method serviceInstaller1_AfterInstall (line 19) | private void serviceInstaller1_AfterInstall(object sender, InstallEven...

FILE: OWINTest.Service/Startup.cs
  class Startup (line 11) | class Startup
    method Configuration (line 19) | public void Configuration(IAppBuilder appBuilder)
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (55K chars).
[
  {
    "path": ".gitignore",
    "chars": 1522,
    "preview": "# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)\n[Bb]in/\n[Oo]bj/\n\n# mstest test results\nTestResu"
  },
  {
    "path": ".nuget/NuGet.Config",
    "chars": 162,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n  <solution>\n    <add key=\"disableSourceControlIntegration\" valu"
  },
  {
    "path": ".nuget/NuGet.targets",
    "chars": 7484,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild"
  },
  {
    "path": "LICENSE",
    "chars": 1078,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2014 Dan Esparza\n\nPermission is hereby granted, free of charge, to any person obtai"
  },
  {
    "path": "OWINTest.API/OWINTest.API.csproj",
    "chars": 4076,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microso"
  },
  {
    "path": "OWINTest.API/Properties/AssemblyInfo.cs",
    "chars": 1397,
    "preview": "using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Infor"
  },
  {
    "path": "OWINTest.API/ValuesController.cs",
    "chars": 782,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
  },
  {
    "path": "OWINTest.API/packages.config",
    "chars": 316,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.AspNet.WebApi.Client\" version=\"5.1.0\" target"
  },
  {
    "path": "OWINTest.Service/API/PersonController.cs",
    "chars": 790,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
  },
  {
    "path": "OWINTest.Service/API/RoutedController.cs",
    "chars": 422,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
  },
  {
    "path": "OWINTest.Service/APIServiceTest.Designer.cs",
    "chars": 1245,
    "preview": "namespace OWINTest.Service\n{\n    partial class APIServiceTest\n    {\n        /// <summary> \n        /// Required designe"
  },
  {
    "path": "OWINTest.Service/APIServiceTest.cs",
    "chars": 873,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostic"
  },
  {
    "path": "OWINTest.Service/App.config",
    "chars": 180,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <startup> \n        <supportedRuntime version=\"v4.0\" sku=\".N"
  },
  {
    "path": "OWINTest.Service/OWINTest.Service.csproj",
    "chars": 6490,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microso"
  },
  {
    "path": "OWINTest.Service/Program.cs",
    "chars": 561,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.ServiceProcess;\nusing System.Text;\nusin"
  },
  {
    "path": "OWINTest.Service/ProjectInstaller.Designer.cs",
    "chars": 2180,
    "preview": "namespace OWINTest.Service\n{\n    partial class ProjectInstaller\n    {\n        /// <summary>\n        /// Required design"
  },
  {
    "path": "OWINTest.Service/ProjectInstaller.cs",
    "chars": 539,
    "preview": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Con"
  },
  {
    "path": "OWINTest.Service/ProjectInstaller.resx",
    "chars": 6286,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The prim"
  },
  {
    "path": "OWINTest.Service/Properties/AssemblyInfo.cs",
    "chars": 1405,
    "preview": "using System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Infor"
  },
  {
    "path": "OWINTest.Service/Startup.cs",
    "chars": 1265,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusi"
  },
  {
    "path": "OWINTest.Service/install.cmd",
    "chars": 101,
    "preview": "path = %path%;C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;\n\ninstallutil OWINTest.Service.exe\n\npause"
  },
  {
    "path": "OWINTest.Service/packages.config",
    "chars": 810,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.AspNet.WebApi.Client\" version=\"5.1.0\" target"
  },
  {
    "path": "OWINTest.Service/uninstall.cmd",
    "chars": 104,
    "preview": "path = %path%;C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;\n\ninstallutil /u OWINTest.Service.exe\n\npause"
  },
  {
    "path": "OWINTest.sln",
    "chars": 1792,
    "preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2013\nVisualStudioVersion = 12.0.30110.0\nMi"
  },
  {
    "path": "README.md",
    "chars": 9108,
    "preview": "OWIN WebAPI Service example [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.or"
  }
]

About this extraction

This page contains the full source code of the danesparza/OWIN-WebAPI-Service GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (49.8 KB), approximately 13.0k tokens, and a symbol index with 31 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!