Showing posts with label data transport. Show all posts
Showing posts with label data transport. Show all posts

OData + C#

1 Odata wcf Service

Create
https://msdn.microsoft.com/en-us/library/dd728275(v=vs.110).aspx

Get from browser
https://msdn.microsoft.com/en-us/library/dd728279(v=vs.110).aspx

Use
https://msdn.microsoft.com/en-US/library/dd728278(v=vs.110).aspx

2 OData WebAPI

Create
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint

Use
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/calling-an-odata-service-from-a-net-client

c# Simple socket example


client
    public class SynchronousSocketClient
    {

        public static void StartClient()
        {
            byte[] bytes = new byte[4096];

            try
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

                Socket sender = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                        sender.RemoteEndPoint.ToString());

                    byte[] msg = Encoding.UTF8.GetBytes("TEST MSG!EOF");

                    int bytesSent = sender.Send(msg);

                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                        Encoding.UTF8.GetString(bytes, 0, bytesRec)
                        );

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();

                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }


    }
server
    public class SynchronousSocketListener
    {

        public static string data = null;

        public static void StartListening()
        {
            byte[] bytes = new Byte[4096];

            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    Socket handler = listener.Accept();
                    data = null;

                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("!EOF") > -1)
                        {
                            break;
                        }
                    }


                    Console.WriteLine("Text received : {0}", data);

                    byte[] msg = Encoding.UTF8.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();

        }

    }
test console
    class Program
    {
        static void Main(string[] args)
        {

            Task.Factory.StartNew(() => SynchronousSocketListener.StartListening());
            Thread.Sleep(2000);
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
        }
    }

allowed clock skew is '00:05:00'



I had the same issue and followed all recommendations. But my fault was that I changed only server configuration, whereas I had to change client configuration too.
This is my config without maxClockSkew
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <!-- -->
  </connectionStrings>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IHotLine1" closeTimeout="00:10:00"
          openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
          maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
            maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security>
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="localhost:6767/blabla.svc" binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_IHotLine1" contract="ServiceReference2.IHotLine"
        name="WSHttpBinding_IHotLine1">
        <identity>
          <certificate encodedValue="====encodedvalue===" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>
And updated with clock skew
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="WSHttpBinding_IHotLine1">
          <transactionFlow/>
          <security authenticationMode="SecureConversation"
messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
            <localClientSettings maxClockSkew="01:30:00" />
            <localServiceSettings maxClockSkew="01:30:00" />
            <secureConversationBootstrap authenticationMode="UserNameForSslNegotiated"
messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" >
              <localClientSettings maxClockSkew="01:30:00" />
              <localServiceSettings maxClockSkew="01:30:00" />
            </secureConversationBootstrap>
          </security>
          <textMessageEncoding/>
          <httpTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
        </binding>
      </customBinding>
    </bindings>
    <client>

      <endpoint address="http://localhost:6767/blabla.svc" binding="customBinding"
        bindingConfiguration="WSHttpBinding_IHotLine1" contract="ServiceReference2.IHotLine"
        name="WSHttpBinding_IHotLine1">
        <identity>
          <certificate encodedValue="====encodedva

c# send get responce/request

using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.mydomain.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.mydomain.com/recepticle.aspx");
}
WebProxy wproxy = new WebProxy("10.10.0.2:8080", true);
wproxy.Credentials = new NetworkCredential("int", "FSinet1234", "fsrar");
webclient.Proxy=wpproxy;


http://stackoverflow.com/questions/4015324/http-request-with-post

Пишем СМЭВ сервис c#

Для проверки валидности вашего xml
http://smev.gosuslugi.ru/portal/services-tools.jsp

Будем делать чтобы сервис соответствовал методическим рекомендациям по разработке веб-сервисов версии 2.5.6

Подпись по формату ЭП-ОВ

Отправляем тем способом который без доп обертки в Envelope
http://msnet-developer.blogspot.ru/2013/03/wcf.html


WCF включаем трассировку

http://msdn.microsoft.com/ru-ru/library/ms732023(v=vs.110).aspx

В web.config

1) Добавлям секцию
<system.diagnostics>
     <sources>
       <source name="System.ServiceModel.MessageLogging">
         <listeners>
           <add name="messages"
           type="System.Diagnostics.XmlWriterTraceListener"
           initializeData="WCFLog.svclog" />
         </listeners>
       </source>
     </sources>
   </system.diagnostics>

2) в секцию system.serviceModel добавлям
<diagnostics>
       <messageLogging
            logEntireMessage="true"
            logMalformedMessages="false"
            logMessagesAtServiceLevel="true"
            logMessagesAtTransportLevel="false"
            maxMessagesToLog="30000"
            maxSizeOfMessageToLog="200000"/>
     </diagnostics>
Смотреть SvcTraceViewer.exe
Если ошибка "there is no trace loaded from the file" то надо стопнуть сервис.

c# Get all your letters from russian email service mail.ru

OpenPop.NET
using OpenPop.Common.Logging;
using OpenPop.Mime;
using OpenPop.Mime.Decode;
using OpenPop.Mime.Header;
using OpenPop.Pop3;

// FetchAllMessages("pop3.mail.ru", 995, true, "my_mail_ru_user", "mypass");

public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    //client.GetMessage(i).Headers.Subject - так получаем тему письма
                }

                // Now return the fetched messages
                return allMessages;
            }
        }

с# WCF отправляем сообщения

Сначала конечно же генерируем Service client . Для этого заходим в ServiceReference и там жмем "Добавить ссылку на службу"

Далее мы можем отправить сообщение оборачивая в Envelope


ServiceReference1.ServiceSAClient service = new ServiceReference1.ServiceSAClient();
using (FileStream stream = new FileStream(textBox1.Text, FileMode.Open))
{
         mlReader reader = XmlReader.Create(stream);
         MessageVersion ver = MessageVersion.CreateVersion(EnvelopeVersion.Soap11, AddressingVersion.None);
         System.ServiceModel.Channels.Message m = service.async_getMessage(System.ServiceModel.Channels.Message.CreateMessage(ver, "http://tempuri.org/IServiceWCF/Message", reader));
}


Или не оборачивая в Envelope
XmlDocument d = new XmlDocument();
            d.PreserveWhitespace = false;
            d.Load(@"send.xml");
            MemoryStream ms = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms);
            d.WriteTo(writer);
            writer.Flush();
 
            ms.Position = 0;

MessageVersion ver = MessageVersion.CreateVersion(EnvelopeVersion.Soap11, AddressingVersion.None);
System.ServiceModel.Channels.Message msend = System.ServiceModel.Channels.Message.CreateMessage(XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max), int.MaxValue, ver);
msend.Headers.Action = "http://tempuri.org/IServiceWCF/Message";
System.ServiceModel.Channels.Message m =service.async_getMessage(msend);


Также я как то писал как ответное сообщения от сервиса сохранить в файл. Есть другое решение, более короткое.


System.ServiceModel.Channels.Message m =service.async_getMessage(msend);
                    MessageBuffer buf = m.CreateBufferedCopy(int.MaxValue);
 
 
                    using (var msstream = new MemoryStream())
                    {
                        using (FileStream file = new FileStream("WCF Responce.xml", FileMode.Create, System.IO.FileAccess.Write))
                        {
                            buf.WriteMessage(file);
                            file.Flush();
                        }
                    }

c# System.ServiceModel.Channels.Message to file

Можно сообщение прочитать через Message.ToString(), но так неверно оно будет скопировано и если вдруг вы при этом подписываете сообщение, то может нарушиться подпись. Данный способ был рабочим для меня.
                    
using (var msstream = new MemoryStream())
                    {
                        var xmlWriter = XmlDictionaryWriter.CreateTextWriter(msstream);
 
                        m.WriteMessage(xmlWriter);
 
                        xmlWriter.Flush();
                        msstream.Position = 0;
                        using (FileStream file = new FileStream("Responce.xml", FileMode.Create, System.IO.FileAccess.Write))
                        {
                            byte[] bytes = new byte[msstream.Length];
                            msstream.Read(bytes, 0, (int)msstream.Length);
                            file.Write(bytes, 0, bytes.Length);
                        }
                    }

WCF 400 Bad request

Данная проблема начала возникать на моем сервисе. После гугления интернета наткнулся на то что она может проявляться из-за неверного представления адреса сервиса или из-за больших объемов данных. Есть наверняка и множество других причин, но в моем случае это был большой объем данных получаемый на входе сервисом.

Данную проблему можно решить двумя способами:
1 Посредством исправления web.config . Курсивом и жирным обозначено что нужно поправить. Веб конфиг необходимо править если вы развертываете сервис на своем IIS

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfService2.Service1Behavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />          
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="WcfService2.Service1Behavior"
        name="WcfService2.Service1">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="b1" contract="WcfService2.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="b1" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647"
                        maxStringContentLength="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647" />

        </binding>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>

2 Второй способ актуален для тех кто развертывает сервис через new ServiceHost() . Почитать о нём можно тут . В данном случае мы меняем readerQuotas программно.

using (ServiceHost host = new ServiceHost(typeof(WCF_Lic_SA.ServiceLicSA), new Uri("http://localhost:8202/MyService")))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
                host.OpenTimeout = TimeSpan.FromSeconds(10);

                BasicHttpBinding b = new BasicHttpBinding();

                System.Xml.XmlDictionaryReaderQuotas myReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                myReaderQuotas.MaxArrayLength = 2147483647;
                myReaderQuotas.MaxBytesPerRead = 2147483647;
                myReaderQuotas.MaxDepth = 2147483647;
                myReaderQuotas.MaxNameTableCharCount = 2147483647;
                myReaderQuotas.MaxStringContentLength = 2147483647;
                b.ReaderQuotas = myReaderQuotas;
                b.MaxBufferPoolSize = 2147483647;
                b.MaxBufferSize = 2147483647;
                b.MaxReceivedMessageSize = 2147483647;

                host.AddServiceEndpoint(typeof(WCF_Lic_SA.IServiceLicSA), b, "");

                host.Open();
            }