Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C# API client #98

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions clients/csharp/csharpClient.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharpClient", "csharpClient\csharpClient.csproj", "{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
6 changes: 6 additions & 0 deletions clients/csharp/csharpClient/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
225 changes: 225 additions & 0 deletions clients/csharp/csharpClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Net;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace csharpClient
{
class Program
{
public static string PostHttp(string url, string body, string contentType)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 80000;

byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string htmlCharset = "GBK";
Encoding htmlEncoding = Encoding.GetEncoding(htmlCharset);
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), htmlEncoding);
string responseContent = streamReader.ReadToEnd();

httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();

return responseContent;
}

[DataContract]
[Serializable]
public class head
{
[DataMember]
public string method { get; set; }
[DataMember]
public int time { get; set; }
[DataMember]
public string service { get; set; }

}

[DataContract]
[Serializable]
public class status
{
public status()
{
this.code = 0;
this.msg = "";
}
[DataMember]
public int code { get; set; }
[DataMember]
public string msg { get; set; }

}

[DataContract]
[Serializable]
public class probs
{
public probs()
{
this.prob = 0.0;
this.cat = "";
}
[DataMember]
public double prob { get; set; }
[DataMember]
public string cat { get; set; }

}

[DataContract]
[Serializable]
public class probslast
{
public probslast()
{
this.prob = 0.0;
this.cat = "";
this.last = true;
}
[DataMember]
public bool last { get; set; }
[DataMember]
public double prob { get; set; }
[DataMember]
public string cat { get; set; }

}

[DataContract]
[Serializable]
public class classes
{
[DataMember]
public probs _probs1 { get; set; }
[DataMember]
public probs _probs2 { get; set; }
[DataMember]
public probslast _probslast { get; set; }


}

[DataContract]
[Serializable]
public class predictions
{
public predictions()
{
this._classes = new classes();
this.uri = "";
this.loss = 0;
}

[DataMember]
public string uri { get; set; }
[DataMember]
public int loss { get; set; }
[DataMember]
public classes _classes { get; set; }
}

[DataContract]
[Serializable]
public class body
{
public body()
{
this._predictions = new predictions();
}
[DataMember]
public predictions _predictions { get; set; }

}

[DataContract]
[Serializable]
public class JSonPredictData
{
public JSonPredictData()
{
this._status = new status();
this._head = new head();
this._body = new body();
}

[DataMember]
public body _body { get; set; }

[DataMember]
public head _head { get; set; }

[DataMember]
public status _status { get; set; }

}

public static T ParseFromJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}

public static string GetJson<T>(T obj)
{
DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, obj);
string szJson = Encoding.UTF8.GetString(stream.ToArray());
return szJson;
}
}

private static T Serialization<T>(string obj) where T : class
{
using (var mStream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T entity = serializer.ReadObject(mStream) as T;
return entity;
}
}

static void Main(string[] args)
{
string url = "http://123.56.191.136:8080/predict";
string picUrl = "http://www.deepdetect.com/img/ambulance.jpg";
string body = "{\"service\":\"imageserv\",\"parameters\":{\"input\":{\"width\":224,\"height\":224},\"output\":{\"best\":3}},\"data\":[\"" + picUrl + "\"]}";

string result = PostHttp(url, body, "application/x-www-form-urlencoded");

var jObject = JObject.Parse(result);

string predictResult = jObject["body"]["predictions"]["classes"][0].ToString();
//this is the best result, you can also get other prediction result: ...["classes"][1].ToString()...


}
}
}
36 changes: 36 additions & 0 deletions clients/csharp/csharpClient/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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("csharpClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("csharpClient")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[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("2098a87e-3a5c-4984-8b7e-5acbdd1a33fb")]

// 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")]
63 changes: 63 additions & 0 deletions clients/csharp/csharpClient/csharpClient.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.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>{6502B24D-41C0-40C8-846F-2BCA6AAEDABD}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>csharpClient</RootNamespace>
<AssemblyName>csharpClient</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</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="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<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="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
Binary file not shown.