Skip to content

Commit

Permalink
Added nuget packages and 2 helpful utilities for ASP.NET Web API calls
Browse files Browse the repository at this point in the history
Helpful for calling ASP.NET Web API services from C# code.
  • Loading branch information
lorddev committed Apr 4, 2013
1 parent a897bb5 commit d7a3f4f
Show file tree
Hide file tree
Showing 43 changed files with 63,230 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .nuget/NuGet.Config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
Binary file added .nuget/NuGet.exe
Binary file not shown.
52 changes: 52 additions & 0 deletions .nuget/NuGet.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?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>
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
<NuGetExePath>$(NuGetToolsPath)\nuget.exe</NuGetExePath>
<PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
<PackagesDir>$([System.IO.Path]::Combine($(SolutionDir), "packages"))</PackagesDir>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>

<!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
<PackageSources>""</PackageSources>

<!-- 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>

<!-- Commands -->
<RestoreCommand>"$(NuGetExePath)" install "$(PackagesConfig)" -source $(PackageSources) -o "$(PackagesDir)"</RestoreCommand>
<BuildCommand>"$(NuGetExePath)" pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols</BuildCommand>

<!-- Make the build depend on restore packages -->
<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="!Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
</Target>

<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="Exists('$(PackagesConfig)')" />
</Target>

<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true" />
</Target>
</Project>
26 changes: 26 additions & 0 deletions LordDesign.Utilities.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LordDesign.Utilities", "LordDesign.Utilities\LordDesign.Utilities.csproj", "{BDA4FCBB-3582-42E0-B383-1BAB2BC69547}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Encryptamajig", "..\Encryptamajig\Encryptamajig\Encryptamajig.csproj", "{C9385513-156E-43BB-9120-110905C5C528}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BDA4FCBB-3582-42E0-B383-1BAB2BC69547}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDA4FCBB-3582-42E0-B383-1BAB2BC69547}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDA4FCBB-3582-42E0-B383-1BAB2BC69547}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDA4FCBB-3582-42E0-B383-1BAB2BC69547}.Release|Any CPU.Build.0 = Release|Any CPU
{C9385513-156E-43BB-9120-110905C5C528}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C9385513-156E-43BB-9120-110905C5C528}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C9385513-156E-43BB-9120-110905C5C528}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C9385513-156E-43BB-9120-110905C5C528}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
187 changes: 187 additions & 0 deletions LordDesign.Utilities/ApiCall.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;

namespace LordDesign.Utilities
{
public class ApiCall
{
public ApiCall()
{
QueryParams = new Dictionary<string, string>();
Method = "GET";
}

public string Controller { get; set; }

public string Action { get; set; }

public string Id { get; set; }

public string BaseUrl { get; set; }

public string Method { get; set; }

public object Payload { get; set; }

public IDictionary<string, string> QueryParams { get; set; }

public IApiResult<dynamic> Execute<T>() where T : class
{
Func<object, string> serialize;
string format;
if (Payload is string)
{
serialize = x => x as string;
format = "application/xml";
}
else
{
serialize = JsonConvert.SerializeObject;
format = "application/json";
}

using (var httpClient = new HttpClient())
{
var endpoint = BuildEndpoint() + BuildQueryString();
HttpResponseMessage response;

switch (Method.ToUpper().Trim())
{
case "PUT":
{
var stringContent = new StringContent(serialize(Payload));
stringContent.Headers.ContentType = new MediaTypeHeaderValue(format)
{
CharSet = "utf-8"
};
response = httpClient.PutAsync(endpoint, stringContent).Result;
break;
}
case "POST":
{
var stringContent = new StringContent(serialize(Payload));
stringContent.Headers.ContentType = new MediaTypeHeaderValue(format)
{
CharSet = "utf-8"
};
response = httpClient.PostAsync(endpoint, stringContent).Result;
break;
}
default:
// Assume "GET"
response = httpClient.GetAsync(endpoint).Result;
break;
}

if (response.StatusCode == HttpStatusCode.NoContent)
{
return new ApiResult<dynamic> { StatusCode = response.StatusCode };
}

if (response.Content != null)
{
var content = response.Content.ReadAsStringAsync().Result;

if (content.Contains(@"xmlns=""http://mylearningplan.com/api/rest/"""))
{
// Assume we know how to deserialize the object.
if (format.EndsWith("json"))
{
var dataItem = JsonConvert.DeserializeObject<T>(content);

return new ApiResult<dynamic>
{
StatusCode = response.StatusCode,
DataItem = dataItem
};
}

var contentObject = content.DeserializeAs<T>();

return new ApiResult<dynamic>
{
StatusCode = response.StatusCode,
DataItem = contentObject
};
}

return new ApiResult<dynamic>
{
StatusCode = response.StatusCode,
DataItem = content
};
}

return new ApiResult<dynamic> { StatusCode = response.StatusCode };
}
}

private string BuildEndpoint()
{
var sb = new StringBuilder(50);
sb.Append(BaseUrl);
if (!BaseUrl.EndsWith("/"))
{
sb.Append("/");
}

sb.Append(Controller.ToLower());

if (!Controller.EndsWith("/"))
{
sb.Append("/");
}

if (!string.IsNullOrEmpty(Id))
{
sb.Append(Id.ToLower());
}

if (!string.IsNullOrEmpty(Action))
{
sb.Append("/").Append(Action.ToLower());
}

return sb.ToString();
}

private string BuildQueryString()
{
StringBuilder sb = new StringBuilder();

int length = QueryParams.Count;
int i = 0;
foreach (var item in QueryParams)
{
sb.AppendFormat("{0}={1}", item.Key, item.Value);

if (i < length - 1)
{
sb.Append("&");
i++;
}
}

string qs2 = sb.ToString();
return "?" + qs2;
}
}

public interface IApiResult<T>
{
HttpStatusCode StatusCode { get; set; }
T DataItem { get; set; }
}

public class ApiResult<T> : IApiResult<T>
{
public HttpStatusCode StatusCode { get; set; }

public T DataItem { get; set; }
}
}
15 changes: 15 additions & 0 deletions LordDesign.Utilities/App_Readme/Elmah.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
A new HTTP handler has been configured in your application for consulting the
error log and its feeds. It is reachable at elmah.axd under your application
root. If, for example, your application is deployed at http://www.example.com,
the URL for ELMAH would be http://www.example.com/elmah.axd. You can, of
course, change this path in your application's configuration file.

ELMAH is also set up to be secure such that it can only be accessed locally.
You can enable remote access but then it is paramount that you secure access
to authorized users or/and roles only. This can be done using standard
authorization rules and configuration already built into ASP.NET. For more
information, see http://code.google.com/p/elmah/wiki/SecuringErrorLogPages on
the project site.

Please review the commented out authorization section under
<location path="elmah.axd"> and make the appropriate changes.
18 changes: 16 additions & 2 deletions LordDesign.Utilities/LordDesign.Utilities.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,21 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Elmah">
<HintPath>..\..\ThirdParty\ELMAH-1.2-sp2\bin\net-2.0\Release\Elmah.dll</HintPath>
<HintPath>..\packages\elmah.corelibrary.1.2.2\lib\Elmah.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\ThirdParty\NewtonSoft\Newtonsoft.Json.dll</HintPath>
<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" />
<Reference Include="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.0.20710.0\lib\net40\System.Net.Http.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.WebRequest, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.2.0.20710.0\lib\net40\System.Net.Http.WebRequest.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
Expand All @@ -47,6 +55,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ApiCall.cs" />
<Compile Include="Botmail.cs" />
<Compile Include="IEachified.cs" />
<Compile Include="MailThrottle.cs" />
Expand All @@ -64,12 +73,14 @@
</Compile>
<Compile Include="RestRouteHandler.cs" />
<Compile Include="RssConverter.cs" />
<Compile Include="XmlTools.cs" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
Expand All @@ -81,6 +92,9 @@
<Name>Encryptamajig</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="App_Readme\Elmah.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- 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.
Expand Down
Loading

0 comments on commit d7a3f4f

Please sign in to comment.