.NET HTTP client implementations: examples.
authorgu.martinm@gmail.com <gu.martinm@gmail.com>
Mon, 26 May 2014 15:12:16 +0000 (17:12 +0200)
committergu.martinm@gmail.com <gu.martinm@gmail.com>
Mon, 26 May 2014 15:12:16 +0000 (17:12 +0200)
Trying out the .NET HTTP client implementations that I know (ATM)

Allgemeines/HttpClientsExamples/HttpClientsExamples.sln [new file with mode: 0644]
Allgemeines/HttpClientsExamples/HttpClientsExamples/HttpClientsExamples.csproj [new file with mode: 0644]
Allgemeines/HttpClientsExamples/HttpClientsExamples/Program.cs [new file with mode: 0644]
Allgemeines/HttpClientsExamples/HttpClientsExamples/Properties/AssemblyInfo.cs [new file with mode: 0644]
Allgemeines/HttpClientsExamples/HttpClientsExamples/WebClientExample.cs [new file with mode: 0644]

diff --git a/Allgemeines/HttpClientsExamples/HttpClientsExamples.sln b/Allgemeines/HttpClientsExamples/HttpClientsExamples.sln
new file mode 100644 (file)
index 0000000..c26afbf
--- /dev/null
@@ -0,0 +1,33 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpClientsExamples", "HttpClientsExamples\HttpClientsExamples.csproj", "{67B3556B-3F66-4209-AEFE-B88C43437475}"
+EndProject
+Global
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution
+               Debug|x86 = Debug|x86
+               Release|x86 = Release|x86
+       EndGlobalSection
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution
+               {67B3556B-3F66-4209-AEFE-B88C43437475}.Debug|x86.ActiveCfg = Debug|x86
+               {67B3556B-3F66-4209-AEFE-B88C43437475}.Debug|x86.Build.0 = Debug|x86
+               {67B3556B-3F66-4209-AEFE-B88C43437475}.Release|x86.ActiveCfg = Release|x86
+               {67B3556B-3F66-4209-AEFE-B88C43437475}.Release|x86.Build.0 = Release|x86
+       EndGlobalSection
+       GlobalSection(MonoDevelopProperties) = preSolution
+               StartupItem = HttpClientsExamples\HttpClientsExamples.csproj
+               Policies = $0
+               $0.TextStylePolicy = $1
+               $1.FileWidth = 120
+               $1.inheritsSet = VisualStudio
+               $1.inheritsScope = text/plain
+               $1.scope = text/x-csharp
+               $0.CSharpFormattingPolicy = $2
+               $2.BeforeMethodDeclarationParentheses = False
+               $2.BeforeConstructorDeclarationParentheses = False
+               $2.AfterDelegateDeclarationParameterComma = True
+               $2.inheritsSet = Mono
+               $2.inheritsScope = text/x-csharp
+               $2.scope = text/x-csharp
+       EndGlobalSection
+EndGlobal
diff --git a/Allgemeines/HttpClientsExamples/HttpClientsExamples/HttpClientsExamples.csproj b/Allgemeines/HttpClientsExamples/HttpClientsExamples/HttpClientsExamples.csproj
new file mode 100644 (file)
index 0000000..d5fced8
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
+    <ProductVersion>10.0.0</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{67B3556B-3F66-4209-AEFE-B88C43437475}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <RootNamespace>HttpClientsExamples</RootNamespace>
+    <AssemblyName>HttpClientsExamples</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug</OutputPath>
+    <DefineConstants>DEBUG;</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <Externalconsole>true</Externalconsole>
+    <PlatformTarget>x86</PlatformTarget>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <DebugType>full</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release</OutputPath>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <Externalconsole>true</Externalconsole>
+    <PlatformTarget>x86</PlatformTarget>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="WebClientExample.cs" />
+  </ItemGroup>
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project>
\ No newline at end of file
diff --git a/Allgemeines/HttpClientsExamples/HttpClientsExamples/Program.cs b/Allgemeines/HttpClientsExamples/HttpClientsExamples/Program.cs
new file mode 100644 (file)
index 0000000..ae51cea
--- /dev/null
@@ -0,0 +1,13 @@
+using System;
+
+namespace HttpClientsExamples
+{
+    class MainClass
+    {
+        public static void Main(string[] args)
+        {
+            WebClientExample webclientExample = new WebClientExample();
+            webclientExample.Test();
+        }
+    }
+}
diff --git a/Allgemeines/HttpClientsExamples/HttpClientsExamples/Properties/AssemblyInfo.cs b/Allgemeines/HttpClientsExamples/HttpClientsExamples/Properties/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..c65491f
--- /dev/null
@@ -0,0 +1,22 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+[assembly: AssemblyTitle ("HttpClientsExamples")]
+[assembly: AssemblyDescription ("")]
+[assembly: AssemblyConfiguration ("")]
+[assembly: AssemblyCompany ("")]
+[assembly: AssemblyProduct ("")]
+[assembly: AssemblyCopyright ("gmm003es")]
+[assembly: AssemblyTrademark ("")]
+[assembly: AssemblyCulture ("")]
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+[assembly: AssemblyVersion ("1.0.*")]
+// The following attributes are used to specify the signing key for the assembly,
+// if desired. See the Mono documentation for more information about signing.
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
+
diff --git a/Allgemeines/HttpClientsExamples/HttpClientsExamples/WebClientExample.cs b/Allgemeines/HttpClientsExamples/HttpClientsExamples/WebClientExample.cs
new file mode 100644 (file)
index 0000000..caa39b8
--- /dev/null
@@ -0,0 +1,132 @@
+using System;
+using System.Net;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace HttpClientsExamples
+{
+    public class WebClientExample
+    {
+        public void Test()
+        {
+            Console.WriteLine("Synchronous WebClient");
+            string line = null;
+            while (line == null || line.Length == 0)
+            {
+                Console.WriteLine("Specify the URI of the resource to retrieve.");
+                Console.WriteLine("Write URI: ");
+                line = Console.ReadLine();
+            }
+
+            using (WebClient client = new WebClient())
+            {
+                // Add a user agent header in case the  
+                // requested URI contains a query.
+                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; Linux; Mono .NET 4.5)");
+
+                using (Stream data = client.OpenRead (line))
+                using (StreamReader reader = new StreamReader(data))
+                {
+                    string s = reader.ReadToEnd();
+                    Console.WriteLine(s);
+                }
+                // data.Dispose();
+                // data.Close();
+                // reader.Dispose();
+                // reader.Close();
+            }
+            // client.Dispose();
+
+
+            line = null;
+            Console.WriteLine("Asynchronous WebClient With Events");
+            while (line == null || line.Length == 0)
+            {
+                Console.WriteLine("Specify the URI of the resource to retrieve.");
+                Console.WriteLine("Write URI: ");
+                line = Console.ReadLine();
+            }
+
+            using (WebClient client = new WebClient())
+            {
+                // Another way, using DownloadDataAsync and its delegate.
+                // client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCallback);
+                // client.DownloadDataAsync (uri, waiter);
+                client.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCallback);
+                client.OpenReadAsync(new Uri(line), null /*What is this for? :( */);
+            }
+            // How to wait for client end without using sleep? :(
+            Thread.Sleep(3000);
+
+
+            line = null;
+            Console.WriteLine("Asynchronous WebClient With Tasks");
+            while (line == null || line.Length == 0)
+            {
+                Console.WriteLine("Specify the URI of the resource to retrieve.");
+                Console.WriteLine("Write URI: ");
+                line = Console.ReadLine();
+            }
+            using (WebClient client = new WebClient())
+            using (Task<Stream> data = client.OpenReadTaskAsync(line))
+                //using (Stream stream = data.Result)
+            {
+                data.Start();
+                try {
+                    Task.WaitAll(data);
+                }
+                catch (AggregateException ae)
+                {
+                    ae.Handle(e =>
+                        {
+                            if (e is OperationCanceledException)
+                            {
+                                Console.WriteLine("Cancelling a Task, catching OperationCanceledException: {0} {1}", e.Message, e.StackTrace);
+                                return true;
+                            }
+                            else
+                            {
+                                Console.WriteLine("Cancelling a Task, dunno what are you: {0} {1}", e.Message, e.StackTrace);
+                                return false;
+                            }
+                        });
+                }
+                Stream dataStream = data.Result;
+                if (dataStream != null)
+                {
+
+                }
+            }
+        }
+
+        private void OpenReadCallback (Object sender, OpenReadCompletedEventArgs e)
+        {
+            Stream reply = null;
+            StreamReader s = null;
+
+            // Old fashined way (without using)
+            // NOTE: using statement is the same as this code (it also checks for null value before calling
+            // the Dispose method)
+            try
+            {
+                reply = (Stream)e.Result;
+                s = new StreamReader (reply);
+                Console.WriteLine (s.ReadToEnd ());
+            }
+            finally
+            {
+                if (s != null)
+                {
+                    s.Close ();
+                }
+
+                if (reply != null)
+                {
+                    reply.Close ();
+                }
+            }
+        }
+    }
+}
+