-
Creare un progetto Console Application
-
aggiungere un file di configurazione app.config e configurare il servizio WCF:
<xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
<httpRuntime maxRequestLength="524288" />
system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfiguration"
hostNameComparisonMode="StrongWildcard"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
openTimeout="00:10:00"
closeTimeout="00:10:00"
maxReceivedMessageSize="65536"
maxBufferSize="65536"
maxBufferPoolSize="524288"
transferMode="Streamed"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
binding>
basicHttpBinding>
<webHttpBinding>
<binding name="webHttpBindingConfiguration"
transferMode="Streamed">
binding>
webHttpBinding>
<wsHttpBinding>
<binding name="wsHttpBindingConfiguration"
bypassProxyOnLocal="false"
transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
<reliableSession ordered="true"
inactivityTimeout="00:10:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true" establishSecurityContext="true" />
security>
binding>
wsHttpBinding>
<netNamedPipeBinding>
<binding name="netNamedPipeBindingConfiguration"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
transactionFlow="false"
transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxBufferSize="65536"
maxConnections="10"
maxReceivedMessageSize="65536">
<security mode="None">
<transport protectionLevel="EncryptAndSign" />
security>
binding>
netNamedPipeBinding>
bindings>
<services>
<service name="TestWCFStreaming.StreamingSample" behaviorConfiguration="ServiceBehaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:50001/TestWCFStreaming/"/>
baseAddresses>
host>
<endpoint name="endPoint1" address="address1" binding="wsHttpBinding"
bindingConfiguration="wsHttpBindingConfiguration"
contract="TestWCFStreaming.IStreamingSample"/>
<endpoint name="endPoint2" address="address2" binding="basicHttpBinding"
bindingConfiguration="basicHttpBindingConfiguration"
contract="TestWCFStreaming.IStreamingSample">
<identity>
<dns value="localhost"/>
identity>
endpoint>
<endpoint name="endPoint3" address="address3" binding="webHttpBinding"
bindingConfiguration="webHttpBindingConfiguration"
contract="TestWCFStreaming.IStreamingSample" behaviorConfiguration="web"/>
<endpoint name="endPoint4" address="net.pipe://localhost/TestWCFStreaming/address4" binding="netNamedPipeBinding"
bindingConfiguration="netNamedPipeBindingConfiguration" contract="TestWCFStreaming.IStreamingSample" />
<endpoint name="endPoint5" address="net.tcp://localhost:50002/TestWCFStreaming/address5" binding="netTcpBinding"
bindingConfiguration="" contract="TestWCFStreaming.IStreamingSample">
<identity>
<dns value="localhost" />
identity>
endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
service>
services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
behavior>
serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
behavior>
endpointBehaviors>
behaviors>
system.serviceModel>
configuration>
-
aggiungere una classe IStreamingSample:
[ServiceContract(Namespace = "http://TestWCFStreaming.org")]
public interface IStreamingSample
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetStream?fileName={fileName}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream GetStream(String fileName);
[OperationContract]
bool UploadStream(Stream stream);
[OperationContract]
Stream EchoStream(Stream stream);
}
Come si vede dall'interfaccia le decorazioni per l'invocazione dei metodi con comandi HTTP GET è possibile solo per il metodo "GetStream".
-
aggiungere riferimeto all'assembly System.ServiceModel.dll
-
importare System.IO, System.ServiceModel e System.ServiceModel.Web:
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
-
aggiungere una classe StreamingSample che implementa IStreamingSample:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class StreamingSample : IStreamingSample
{
public System.IO.Stream GetStream(string fileName)
{
if (System.IO.File.Exists(fileName))
{
System.IO.FileStream textFile = System.IO.File.OpenRead(fileName);
return textFile;
}
return null;
}
public bool UploadStream(System.IO.Stream stream)
{
try
{
using (System.IO.FileStream textFile = System.IO.File.OpenWrite("uploadstream.txt"))
{
stream.CopyTo(textFile);
}
}
catch
{
return false;
}
return true;
}
public System.IO.Stream EchoStream(System.IO.Stream stream)
{
return stream;
}
}
-
importare il namespace System.ServiceModel:
using System.ServiceModel;
-
aggiungere un file di testo utilizzato come stream "downloadstream.txt" ed impostare la proprietà "Copy to Output Directory" a "Copy always", quindi inserire un testo arbitrario all'interno del file.
-
per eseguire l'applicazione con diritti di Amministrazione occorre aggiungere un manifest di applicazione:
a) tasto destro sul progetto quindi selezionare "Add" e quindi "New item";
b) selezionare "Application Manifest File"
c) modificare il manifest nel seguente modo il tag "requestedExecutionLevel" impostando l'attributo "level" a "requireAdministrator":
-
creare gli oggetti client necessari per verificare il corretto funzionamento di tutti gli endpoint creati:
class Program
{
static void Main(string[] args)
{
// endpoint con binding wsHttpBinding
TestWcfStreaming.StreamingSampleClient client = new TestWcfStreaming.StreamingSampleClient("endPoint1");
testEndPoint(client);
// endpoint con binding basicHttpBinding
client = new TestWcfStreaming.StreamingSampleClient("endPoint2");
testEndPoint(client);
// endpoint con binding webHttpBinding
System.Net.WebClient webclient = new System.Net.WebClient();
byte[] data = webclient.DownloadData("http://localhost:50001/TestWcfStreaming/address3/GetStream?fileName=downloadstream.txt");
using (System.IO.StreamReader sr = new System.IO.StreamReader(new System.IO.MemoryStream(data)))
{
Console.WriteLine(sr.ReadToEnd());
}
// endpoint con binding netNamedPipeBinding
client = new TestWcfStreaming.StreamingSampleClient("endPoint4");
testEndPoint(client);
// endpoint con binding netTcpBinding
client = new TestWcfStreaming.StreamingSampleClient("endPoint5");
testEndPoint(client);
Console.WriteLine("To Close Client Press any Key ");
Console.ReadKey();
}
private static void testEndPoint(TestWcfStreaming.StreamingSampleClient client)
{
Console.WriteLine("Endpoint: {0}", client.Endpoint.Name);
using (System.IO.StreamReader sr = new System.IO.StreamReader(client.GetStream("downloadstream.txt")))
{
String textStream = sr.ReadToEnd();
Console.WriteLine(textStream);
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("testo di prova per upload")))
{
if (client.UploadStream(ms))
Console.WriteLine("Upload stream succeeded");
else
Console.WriteLine("Upload stream failed");
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes("testo di prova per echo")))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(client.EchoStream(ms)))
{
String textStream = sr.ReadToEnd();
Console.WriteLine(textStream);
}
}
client.Close();
}
}