Exemple #1
0
        /// <summary>
        /// Initialize an new HTTP server for the eMIP HTTP/SOAP/XML CPO API.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="ServiceName">An optional identification for this SOAP service.</param>
        /// <param name="HTTPServerPort">An optional TCP port for the HTTP server.</param>
        /// <param name="URLPathPrefix">An optional prefix for the HTTP URIs.</param>
        /// <param name="AuthorisationURL">The HTTP/SOAP/XML URI for eMIP authorization requests.</param>
        /// <param name="ContentType">An optional HTTP content type to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public CPOServer(String HTTPServerName           = DefaultHTTPServerName,
                         IPPort?HTTPServerPort           = null,
                         String ServiceName              = null,
                         HTTPPath?URLPathPrefix          = null,
                         String AuthorisationURL         = DefaultAuthorisationURL,
                         HTTPContentType ContentType     = null,
                         Boolean RegisterHTTPRootService = true,
                         DNSClient DNSClient             = null,
                         Boolean AutoStart = false)

            : base(HTTPServerName.IsNotNullOrEmpty() ? HTTPServerName : DefaultHTTPServerName,
                   HTTPServerPort ?? DefaultHTTPServerPort,
                   ServiceName ?? "eMIP " + Version.Number + " " + nameof(CPOServer),
                   URLPathPrefix ?? DefaultURLPathPrefix,
                   ContentType ?? DefaultContentType,
                   RegisterHTTPRootService,
                   DNSClient,
                   AutoStart: false)

        {
            this.ServiceName      = ServiceName ?? "eMIP " + Version.Number + " " + nameof(CPOServer);
            this.AuthorisationURL = AuthorisationURL ?? DefaultAuthorisationURL;

            RegisterURITemplates();

            if (AutoStart)
            {
                Start();
            }
        }
Exemple #2
0
        /// <summary>
        /// Initialize a new HTTP server for the central system HTTP/SOAP/XML API.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="URLPrefix">An optional prefix for the HTTP URLs.</param>
        /// <param name="ContentType">An optional HTTP content type to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public CentralSystemWSServer(String HTTPServerName           = DefaultHTTPServerName,
                                     IPPort?TCPPort                  = null,
                                     HTTPPath?URLPrefix              = null,
                                     HTTPContentType ContentType     = null,
                                     Boolean RegisterHTTPRootService = true,
                                     DNSClient DNSClient             = null,
                                     Boolean AutoStart               = false)

        //: base(HTTPServerName.IsNotNullOrEmpty()
        //           ? HTTPServerName
        //           : DefaultHTTPServerName,
        //       TCPPort     ?? DefaultHTTPServerPort,
        //       URLPrefix   ?? DefaultURLPrefix,
        //       ContentType ?? DefaultContentType,
        //       RegisterHTTPRootService,
        //       DNSClient,
        //       AutoStart: false)
            : base(System.Net.IPAddress.Parse("127.0.0.1"),
                   TCPPort.HasValue ? TCPPort.Value.ToUInt16() : 8000)

        {
            base.OnTextMessage += ProcessTextMessages;

            //if (AutoStart)
            //    Start();
        }
Exemple #3
0
        /// <summary>
        /// Initialize a new HTTP server for the HTTP/SOAP/XML Server API using IPAddress.Any.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="URIPrefix">An optional prefix for the HTTP URIs.</param>
        /// <param name="SOAPContentType">The HTTP content type for SOAP messages.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public ASOAPServer(String HTTPServerName           = DefaultHTTPServerName,
                           IPPort TCPPort                  = null,
                           String URIPrefix                = DefaultURIPrefix,
                           HTTPContentType SOAPContentType = null,
                           Boolean RegisterHTTPRootService = true,
                           DNSClient DNSClient             = null,
                           Boolean AutoStart               = false)

            : this(new SOAPServer(TCPPort ?? DefaultHTTPServerPort,
                                  HTTPServerName,
                                  SOAPContentType ?? DefaultContentType,
                                  DNSClient :  DNSClient,
                                  Autostart :  false),
                   URIPrefix)

        {
            if (RegisterHTTPRootService)
            {
                RegisterRootService();
            }

            if (AutoStart)
#pragma warning disable RECS0021
            {
                Start();
            }
#pragma warning restore RECS0021
        }
Exemple #4
0
        /// <summary>
        /// Initialize a new HTTP server for the charge point HTTP/SOAP/XML API.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="ServiceName">The TCP service name shown e.g. on service startup.</param>
        /// <param name="URLPrefix">An optional prefix for the HTTP URLs.</param>
        /// <param name="ContentType">An optional HTTP content type to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public ChargePointSOAPServer(String HTTPServerName           = DefaultHTTPServerName,
                                     IPPort?TCPPort                  = null,
                                     String ServiceName              = null,
                                     HTTPPath?URLPrefix              = null,
                                     HTTPContentType ContentType     = null,
                                     Boolean RegisterHTTPRootService = true,
                                     DNSClient DNSClient             = null,
                                     Boolean AutoStart               = false)

            : base(HTTPServerName.IsNotNullOrEmpty()
                       ? HTTPServerName
                       : DefaultHTTPServerName,
                   TCPPort ?? DefaultHTTPServerPort,
                   ServiceName ?? DefaultServiceName,
                   URLPrefix ?? DefaultURLPrefix,
                   ContentType ?? DefaultContentType,
                   RegisterHTTPRootService,
                   DNSClient,
                   AutoStart: false)

        {
            RegisterURLTemplates();

            if (AutoStart)
            {
                Start();
            }
        }
Exemple #5
0
        public RoamingNetworkInfo(Tracker_Id TrackerId,
                                  String IncomingURI,
                                  DateTime ExpiredAfter,

                                  RoamingNetwork_Id RoamingNetworkId,
                                  Byte priority,
                                  Byte weight,
                                  String hostname,
                                  IPPort port,
                                  TransportTypes transport,
                                  String uriPrefix,
                                  HTTPContentType contentType,
                                  ProtocolTypes protocolType,
                                  IEnumerable <String> PublicKeys)
        {
            this.TrackerId    = TrackerId;
            this.IncomingURI  = IncomingURI;
            this.ExpiredAfter = ExpiredAfter;

            this.RoamingNetworkId = RoamingNetworkId;

            this.priority     = priority;
            this.weight       = weight;
            this.hostname     = hostname;
            this.port         = port;
            this.transport    = transport;
            this.uriPrefix    = uriPrefix;
            this.contentType  = contentType;
            this.protocolType = protocolType;
            this.publicKeys   = PublicKeys;

            this.AnnouncedURI = String.Concat(transport, "://", hostname, ":", port, uriPrefix, "_", contentType);
        }
Exemple #6
0
        public RoamingNetworkInfo(Tracker_Id TrackerId,
                                  String IncomingURI,
                                  DateTime ExpiredAfter,

                                  RoamingNetwork RoamingNetwork,
                                  Byte priority,
                                  Byte weight,
                                  String hostname,
                                  IPPort port,
                                  TransportTypes transport,
                                  String uriPrefix,
                                  HTTPContentType contentType,
                                  ProtocolTypes protocolType,
                                  IEnumerable <String> PublicKeys)

            : this(TrackerId,
                   IncomingURI,
                   ExpiredAfter,

                   RoamingNetwork.Id,
                   priority,
                   weight,
                   hostname,
                   port,
                   transport,
                   uriPrefix,
                   contentType,
                   protocolType,
                   PublicKeys)

        {
            this.RoamingNetwork = RoamingNetwork;
        }
Exemple #7
0
        public static RoamingNetworkInfo Create(this RoamingNetwork RoamingNetwork,
                                                Tracker_Id TrackerId,
                                                DateTime ExpiredAfter,

                                                Byte priority,
                                                Byte weight,
                                                String hostname,
                                                IPPort port,
                                                TransportTypes transport,
                                                String uriPrefix,
                                                HTTPContentType contentType,
                                                ProtocolTypes protocolType,
                                                IEnumerable <String> PublicKeys)
        {
            return(new RoamingNetworkInfo(TrackerId,
                                          "",
                                          ExpiredAfter,
                                          RoamingNetwork.Id,
                                          priority,
                                          weight,
                                          hostname,
                                          port,
                                          transport,
                                          uriPrefix,
                                          contentType,
                                          protocolType,
                                          PublicKeys));
        }
Exemple #8
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="ContentType"></param>
 /// <param name="MethodHandler"></param>
 /// <param name="ContentTypeAuthentication"></param>
 /// <param name="ContentTypeError"></param>
 public ContentTypeNode(HTTPContentType ContentType, MethodInfo MethodHandler = null, Boolean ContentTypeAuthentication = false, MethodInfo ContentTypeError = null)
 {
     this.ContentType                = ContentType;
     this.MethodHandler              = MethodHandler;
     this.ContentTypeAuthentication  = ContentTypeAuthentication;
     this.ContentTypeErrorHandler    = ContentTypeErrorHandler;
     this.ContentTypeErrorHandlers   = new ConcurrentDictionary<HTTPStatusCode, MethodInfo>();
 }
        public static string GetHttpContentType(HTTPContentType contentType)
        {
            switch (contentType)
            {
            default:
            case HTTPContentType.DEFAULT:
            case HTTPContentType.APPLICATION: return(CONTENT_TYPE_APP);

            case HTTPContentType.MULTIPART: return(CONTENT_TYPE_MULTI);
            }
        }
Exemple #10
0
        /// <summary>
        /// Creates a new abstract HTTPService.
        /// </summary>
        /// <param name="HTTPContentType">A content type.</param>
        public AHTTPService(HTTPContentType HTTPContentType)
        {
            #region Initial checks

            if (HTTPContentType == null)
                throw new ArgumentNullException("The given HTTPContentType must not be null!");

            #endregion

            this.HTTPContentTypes = new HTTPContentType[1] { HTTPContentType };
        }
Exemple #11
0
        /// <summary>
        /// Create a new SOAP dispatcher.
        /// </summary>
        /// <param name="URITemplate">The URI template of the SOAP dispatcher.</param>
        /// <param name="SOAPContentType">The HTTP content type the SOAP/XML request will be send.</param>
        public SOAPDispatcher(String URITemplate,
                              HTTPContentType SOAPContentType)
        {
            #region Initial checks

            if (URITemplate == null)
            {
                throw new ArgumentNullException(nameof(URITemplate), "The given URI template must not be null!");
            }

            #endregion

            this.URITemplate     = URITemplate;
            this.SOAPContentType = SOAPContentType;
            this._SOAPDispatches = new List <SOAPDispatch>();
        }
Exemple #12
0
        /// <summary>
        /// Create a new SOAP dispatcher.
        /// </summary>
        /// <param name="URITemplate">The URI template of the SOAP dispatcher.</param>
        /// <param name="SOAPContentType">The HTTP content type the SOAP/XML request will be send.</param>
        public SOAPDispatcher(String           URITemplate,
                              HTTPContentType  SOAPContentType)
        {

            #region Initial checks

            if (URITemplate == null)
                throw new ArgumentNullException(nameof(URITemplate), "The given URI template must not be null!");

            #endregion

            this.URITemplate      = URITemplate;
            this.SOAPContentType  = SOAPContentType;
            this._SOAPDispatches  = new List<SOAPDispatch>();

        }
Exemple #13
0
        /// <summary>
        /// Creates a new abstract HTTPService.
        /// </summary>
        /// <param name="IHTTPConnection">The http connection for this request.</param>
        /// <param name="HTTPContentType">A http content type.</param>
        /// <param name="ResourcePath">The path to internal resources.</param>
        public AHTTPService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType, String ResourcePath)
        {
            #region Initial checks

            if (IHTTPConnection == null)
                throw new ArgumentNullException("The given IHTTPConnection must not be null!");

            if (HTTPContentType == null)
                throw new ArgumentNullException("The given HTTPContentType must not be null!");

            if (ResourcePath.IsNullOrEmpty())
                throw new ArgumentNullException("The given ResourcePath must not be null or empty!");

            #endregion

            this.IHTTPConnection  = IHTTPConnection;
            this.HTTPContentTypes = new HTTPContentType[1] { HTTPContentType };
            this.ResourcePath     = ResourcePath;
        }
Exemple #14
0
        /// <summary>
        /// Initialize the SOAP server using the given parameters.
        /// </summary>
        /// <param name="TCPPort">An IP port to listen on.</param>
        /// <param name="DefaultServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="SOAPContentType">The default HTTP content type used for all SOAP requests/responses.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="CallingAssemblies">A list of calling assemblies to include e.g. into embedded ressources lookups.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the HTTP server thread immediately (default: no).</param>
        public SOAPServer(IPPort TCPPort                           = null,
                          String DefaultServerName                 = DefaultHTTPServerName,
                          HTTPContentType SOAPContentType          = null,
                          X509Certificate2 X509Certificate         = null,
                          IEnumerable <Assembly> CallingAssemblies = null,
                          String ServerThreadName                  = null,
                          ThreadPriority ServerThreadPriority      = ThreadPriority.AboveNormal,
                          Boolean ServerThreadIsBackground         = true,
                          ConnectionIdBuilder ConnectionIdBuilder  = null,
                          ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                          ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                          Boolean ConnectionThreadsAreBackground = true,
                          TimeSpan?ConnectionTimeout             = null,
                          UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,
                          DNSClient DNSClient = null,
                          Boolean Autostart   = false)

            : base(TCPPort,
                   DefaultServerName,
                   X509Certificate,
                   CallingAssemblies,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   DNSClient,
                   false)

        {
            this.SOAPContentType  = SOAPContentType != null ? SOAPContentType : DefaultSOAPContentType;
            this._SOAPDispatchers = new Dictionary <String, SOAPDispatcher>();

            if (Autostart)
            {
                Start();
            }
        }
Exemple #15
0
 /// <summary>
 /// Create a new attached file.
 /// </summary>
 private AttachedFile(AttachedFile_Id Id,
                      I18NString Description,
                      IEnumerable <HTTPPath> Locations,
                      HTTPContentType ContentType = null,
                      UInt64?Size          = null,
                      HTTPPath?Icon        = null,
                      DateTime?Created     = null,
                      DateTime?LastModifed = null,
                      String DataSource    = null)
 {
     this.Id           = Id;
     this.Description  = Description;
     this.Locations    = Locations;
     this.ContentType  = ContentType;
     this.Size         = Size;
     this.Icon         = Icon;
     this.Created      = Created ?? Timestamp.Now;
     this.LastModified = LastModifed ?? Timestamp.Now;
     //this.CryptoHashes  =
     //this.Signatures    =
 }
Exemple #16
0
        /// <summary>
        /// Creates a new HTTP ContentTypeNode.
        /// </summary>
        /// <param name="HTTPContentType">The http content type for this service.</param>
        /// <param name="HTTPContentTypeAuthentication">This and all subordinated nodes demand an explicit HTTP content type authentication.</param>
        /// <param name="RequestHandler">The default delegate to call for any request to this URI template.</param>
        /// <param name="DefaultErrorHandler">The default error handling delegate.</param>
        /// <param name="AllowReplacement">How to handle duplicate URI handlers.</param>
        internal ContentTypeNode(HTTPContentType     HTTPContentType,
                                 HTTPAuthentication  HTTPContentTypeAuthentication   = null,
                                 HTTPDelegate        RequestHandler                  = null,
                                 HTTPDelegate        DefaultErrorHandler             = null,
                                 URIReplacement      AllowReplacement                = URIReplacement.Fail)
        {
            #region Initial checks

            if (HTTPContentType == null)
                throw new ArgumentNullException(nameof(HTTPContentType),  "The given HTTP content type must not be null!");

            #endregion

            this.HTTPContentType                = HTTPContentType;
            this.HTTPContentTypeAuthentication  = HTTPContentTypeAuthentication;
            this.RequestHandler                 = RequestHandler;
            this.DefaultErrorHandler            = DefaultErrorHandler;
            this.AllowReplacement               = AllowReplacement;

            this.ErrorHandlers                  = new Dictionary<HTTPStatusCode, HTTPDelegate>();
        }
Exemple #17
0
        /// <summary>
        /// Initialize the SOAP server using the given parameters.
        /// </summary>
        /// <param name="TCPPort">An IP port to listen on.</param>
        /// <param name="DefaultServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="SOAPContentType">The default HTTP content type used for all SOAP requests/responses.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="CallingAssemblies">A list of calling assemblies to include e.g. into embedded ressources lookups.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the HTTP server thread immediately (default: no).</param>
        public SOAPServer(IPPort                            TCPPort                           = null,
                          String                            DefaultServerName                 = DefaultHTTPServerName,
                          HTTPContentType                   SOAPContentType                   = null,
                          X509Certificate2                  X509Certificate                   = null,
                          IEnumerable<Assembly>             CallingAssemblies                 = null,
                          String                            ServerThreadName                  = null,
                          ThreadPriority                    ServerThreadPriority              = ThreadPriority.AboveNormal,
                          Boolean                           ServerThreadIsBackground          = true,
                          ConnectionIdBuilder               ConnectionIdBuilder               = null,
                          ConnectionThreadsNameBuilder      ConnectionThreadsNameBuilder      = null,
                          ConnectionThreadsPriorityBuilder  ConnectionThreadsPriorityBuilder  = null,
                          Boolean                           ConnectionThreadsAreBackground    = true,
                          TimeSpan?                         ConnectionTimeout                 = null,
                          UInt32                            MaxClientConnections              = TCPServer.__DefaultMaxClientConnections,
                          DNSClient                         DNSClient                         = null,
                          Boolean                           Autostart                         = false)
            : base(TCPPort,
                   DefaultServerName,
                   X509Certificate,
                   CallingAssemblies,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   DNSClient,
                   false)
        {
            this.SOAPContentType  = SOAPContentType != null ? SOAPContentType : DefaultSOAPContentType;
            this._SOAPDispatchers  = new Dictionary<String, SOAPDispatcher>();

            if (Autostart)
                Start();
        }
Exemple #18
0
        /// <summary>
        /// Initialize an new HTTP server for the OICP HTTP/SOAP/XML EMP API.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="ServiceName">An optional identification for this SOAP service.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="ServerCertificateSelector">An optional delegate to select a SSL/TLS server certificate.</param>
        /// <param name="ClientCertificateValidator">An optional delegate to verify the SSL/TLS client certificate used for authentication.</param>
        /// <param name="ClientCertificateSelector">An optional delegate to select the SSL/TLS client certificate used for authentication.</param>
        /// <param name="AllowedTLSProtocols">The SSL/TLS protocol(s) allowed for this connection.</param>
        /// <param name="URLPathPrefix">An optional prefix for all HTTP URLs.</param>
        /// <param name="AuthorizationURL">An alternative HTTP/SOAP/XML URL for OICP authorization requests.</param>
        /// <param name="ContentType">An optional HTTP content type to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public EMPSOAPServer(String HTTPServerName = DefaultHTTPServerName,
                             IPPort?TCPPort        = null,
                             String ServiceName    = null,
                             ServerCertificateSelectorDelegate ServerCertificateSelector    = null,
                             RemoteCertificateValidationCallback ClientCertificateValidator = null,
                             LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                             SslProtocols AllowedTLSProtocols = SslProtocols.Tls12,
                             HTTPPath?URLPathPrefix           = null,
                             String AuthorizationURL          = DefaultAuthorizationURL,
                             HTTPContentType ContentType      = null,
                             Boolean RegisterHTTPRootService  = true,
                             DNSClient DNSClient = null,
                             Boolean AutoStart   = false)

            : base(HTTPServerName.IsNotNullOrEmpty() ? HTTPServerName : DefaultHTTPServerName,
                   TCPPort ?? DefaultHTTPServerPort,
                   ServiceName ?? "OICP " + Version.Number + " " + nameof(EMPSOAPServer),
                   ServerCertificateSelector,
                   ClientCertificateValidator,
                   ClientCertificateSelector,
                   AllowedTLSProtocols,
                   URLPathPrefix ?? DefaultURLPathPrefix,
                   ContentType ?? DefaultContentType,
                   RegisterHTTPRootService,
                   DNSClient,
                   AutoStart: false)

        {
            this.ServiceName      = ServiceName ?? "OICP " + Version.Number + " " + nameof(EMPSOAPServer);
            this.AuthorizationURL = AuthorizationURL ?? DefaultAuthorizationURL;

            RegisterURLTemplates();

            if (AutoStart)
            {
                Start();
            }
        }
Exemple #19
0
        public static HTTPResult<String> GetRequestBodyAsUTF8String(this HTTPRequest  Request,
                                                                    HTTPContentType   HTTPContentType)
        {

            if (Request.ContentType != HTTPContentType)
                return new HTTPResult<String>(Request, HTTPStatusCode.BadRequest);

            if (Request.ContentLength == 0)
                return new HTTPResult<String>(Request, HTTPStatusCode.BadRequest);

            if (Request.TryReadHTTPBodyStream() == false)
                return new HTTPResult<String>(Request, HTTPStatusCode.BadRequest);

            if (Request.HTTPBody == null || Request.HTTPBody.Length == 0)
                return new HTTPResult<String>(Request, HTTPStatusCode.BadRequest);

            var RequestBodyString = Request.HTTPBody.ToUTF8String().Trim();

            if (RequestBodyString.IsNullOrEmpty())
                return new HTTPResult<String>(Request, HTTPStatusCode.BadRequest);

            return new HTTPResult<String>(Result: RequestBodyString);

        }
Exemple #20
0
 /// <summary>
 /// Creates a new abstract Aegir HTTP service.
 /// </summary>
 /// <param name="HTTPContentType">A content type.</param>
 public AAegirHTTPService(HTTPContentType HTTPContentType)
     : base(HTTPContentType)
 {
 }
Exemple #21
0
 /// <summary>
 /// Creates a new abstract Aegir HTTP service.
 /// </summary>
 /// <param name="IHTTPConnection">The http connection for this request.</param>
 /// <param name="HTTPContentType">A content type.</param>
 /// <param name="ResourcePath">The path to internal resources.</param>
 public AAegirHTTPService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType)
     : base(IHTTPConnection, HTTPContentType, "LinkedEnergyMap.resources.")
 {
 }
Exemple #22
0
 /// <summary>
 /// Creates a new abstract OCPP CIMS service.
 /// </summary>
 /// <param name="IHTTPConnection">The http connection for this request.</param>
 /// <param name="HTTPContentType">A content type.</param>
 /// <param name="ResourcePath">The path to internal resources.</param>
 public AProjectService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType)
     : base(IHTTPConnection, HTTPContentType, "graph_database.org.resources.")
 {
 }
Exemple #23
0
 /// <summary>
 /// Return the best matching error handler for the given parameters.
 /// </summary>
 public Tuple<MethodInfo, IEnumerable<Object>> GetErrorHandler(String myHost, String myURL, HTTPMethod myHTTPMethod = null, HTTPContentType myHTTPContentType = null, HTTPStatusCode myHTTPStatusCode = null)
 {
     return null;
 }
        internal Tuple <HttpStatusCode, string> MakeRequest(string path, HttpMethod method, HTTPContentType contentType = HTTPContentType.json, byte[] body = null, bool isQRS = true, string port = "4242")
        {
            // Fix Path
            if (!path.StartsWith("/"))
            {
                path = '/' + path;
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            int indexOfSlash = path.LastIndexOf('/');
            int indexOfQuery = path.LastIndexOf('?');

            if (indexOfQuery <= indexOfSlash)
            {
                path += "?";
            }
            else
            {
                path += "&";
            }

            string         responseString = "";
            HttpStatusCode responseCode   = 0;
            string         xrfkey         = "0123456789abcdef";

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            HttpRequestMessage req = new HttpRequestMessage();

            if (isQRS)
            {
                req.RequestUri = new Uri(@"https://" + _hostname + ":4242/qrs" + path + "xrfkey=" + xrfkey);
            }
            else
            {
                req.RequestUri = new Uri(@"https://" + _hostname + ":" + port + path);
            }
            req.Method = method;
            if (isQRS)
            {
                req.Headers.Add("X-Qlik-xrfkey", xrfkey);
                req.Headers.Add("X-Qlik-User", @"UserDirectory=internal;UserId=sa_api");
            }

            WebRequestHandler handler = new WebRequestHandler();

            handler.ClientCertificates.Add(_certificate);

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                req.Content = new ByteArrayContent(body);

                // Set Headers
                if (contentType == HTTPContentType.json)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/json");
                }
                else if (contentType == HTTPContentType.app)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/vnd.qlik.sense.app");
                }
                else
                {
                    throw new ArgumentException("Content type '" + contentType.ToString() + "' is not supported.");
                }
            }

            TelemetryDashboardMain.Logger.Log(string.Format("Request - Ready to send request: '{0}' to '{1}'.", method.ToString(), path), LogLevel.Debug);

            using (HttpClient client = new HttpClient(handler))
            {
                client.Timeout = TimeSpan.FromMilliseconds(_timeout);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    Task <HttpResponseMessage> responseTask = client.SendAsync(req);
                    responseTask.Wait();
                    responseTask.Result.EnsureSuccessStatusCode();
                    responseCode = responseTask.Result.StatusCode;
                    Task <string> responseBodyTask = responseTask.Result.Content.ReadAsStringAsync();
                    responseBodyTask.Wait();
                    responseString = responseBodyTask.Result;
                }
                catch (Exception e)
                {
                    if (responseCode != 0)
                    {
                        return(new Tuple <HttpStatusCode, string>(responseCode, e.Message));
                    }
                    else
                    {
                        return(new Tuple <HttpStatusCode, string>(HttpStatusCode.InternalServerError, e.Message));
                    }
                }
            }
            TelemetryDashboardMain.Logger.Log(string.Format("Request - Response code received: '{0}'", responseCode), LogLevel.Debug);
            return(new Tuple <HttpStatusCode, string>(responseCode, responseString));
        }
Exemple #25
0
        /// <summary>
        /// Creates a new abstract graph service.
        /// </summary>
        /// <param name="IHTTPConnection">The http connection for this request.</param>
        /// <param name="HTTPContentType">A http content type.</param>
        /// <param name="ResourcePath">The path to internal resources.</param>
        protected ABifrostService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType, String ResourcePath)
            : base(IHTTPConnection, HTTPContentType, ResourcePath)
        {
            this.Graph  = new ThreadLocal<IReadOnlyGenericPropertyGraph <String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object>>();

            this.Vertex = new ThreadLocal<IReadOnlyGenericPropertyVertex<String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object>>();

            this.Edge   = new ThreadLocal<IReadOnlyGenericPropertyEdge  <String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object,
                                                                         String, Int64, String, String, Object>>();

            this.Skip   = new ThreadLocal<UInt64>();
            this.Take   = new ThreadLocal<UInt64>();
        }
 /// <summary>
 /// Creates a new abstract OCPP CIMS service.
 /// </summary>
 /// <param name="HTTPContentType">A content type.</param>
 public AGraphService(HTTPContentType HTTPContentType)
     : base(HTTPContentType)
 { }
 /// <summary>
 /// Set the HTTP Content-Type header field.
 /// </summary>
 /// <param name="ContentType">The type of the HTTP content/body.</param>
 public HTTPRequestBuilder SetContentType(HTTPContentType ContentType)
 {
     this.ContentType = ContentType;
     return this;
 }
Exemple #28
0
        public void AddHandler(HTTPDelegate        HTTPDelegate,

                               HTTPMethod          HTTPMethod                  = null,
                               HTTPContentType     HTTPContentType             = null,

                               HTTPAuthentication  HTTPMethodAuthentication    = null,
                               HTTPAuthentication  ContentTypeAuthentication   = null,

                               HTTPDelegate        DefaultErrorHandler         = null,
                               URIReplacement      AllowReplacement            = URIReplacement.Fail)
        {
            HTTPMethodNode _HTTPMethodNode = null;

            if (!_HTTPMethods.TryGetValue(HTTPMethod, out _HTTPMethodNode))
            {
                _HTTPMethodNode = new HTTPMethodNode(HTTPMethod, HTTPMethodAuthentication, HTTPDelegate, DefaultErrorHandler);
                _HTTPMethods.Add(HTTPMethod, _HTTPMethodNode);
            }

            _HTTPMethodNode.AddHandler(HTTPDelegate,

                                       HTTPContentType,

                                       ContentTypeAuthentication,

                                       DefaultErrorHandler,
                                       AllowReplacement);
        }
Exemple #29
0
        private static Tuple <HttpStatusCode, string> MakeQrsRequest(string path, HttpMethod method, HTTPContentType contentType = HTTPContentType.json, byte[] body = null)
        {
            // Fix Path
            if (!path.StartsWith("/"))
            {
                path = '/' + path;
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            int indexOfSlash = path.LastIndexOf('/');
            int indexOfQuery = path.LastIndexOf('?');

            if (indexOfQuery <= indexOfSlash)
            {
                path += "?";
            }
            else
            {
                path += "&";
            }

            string         responseString = "";
            HttpStatusCode responseCode   = 0;
            string         xrfkey         = "0123456789abcdef";

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            HttpRequestMessage req = new HttpRequestMessage();

            req.RequestUri = new Uri(@"https://" + HOSTNAME.Value + ":4242/qrs" + path + "xrfkey=" + xrfkey);
            req.Method     = method;
            req.Headers.Add("X-Qlik-xrfkey", xrfkey);
            req.Headers.Add("X-Qlik-User", @"UserDirectory=internal;UserId=sa_api");

            WebRequestHandler handler = new WebRequestHandler();

            handler.ClientCertificates.Add(SENSE_CERT.Value);

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                req.Content = new ByteArrayContent(body);

                // Set Headers
                if (contentType == HTTPContentType.json)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/json");
                }
                else if (contentType == HTTPContentType.app)
                {
                    req.Content.Headers.Remove("Content-Type");
                    req.Content.Headers.Add("Content-Type", "application/vnd.qlik.sense.app");
                }
                else
                {
                    throw new ArgumentException("Content type '" + contentType.ToString() + "' is not supported.");
                }
            }

            using (HttpClient client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    Task <HttpResponseMessage> responseTask = client.SendAsync(req);
                    responseTask.Wait();
                    responseTask.Result.EnsureSuccessStatusCode();
                    responseCode = responseTask.Result.StatusCode;
                    Task <string> responseBodyTask = responseTask.Result.Content.ReadAsStringAsync();
                    responseBodyTask.Wait();
                    responseString = responseBodyTask.Result;
                }
                catch (Exception e)
                {
                    if (responseCode != 0)
                    {
                        return(new Tuple <HttpStatusCode, string>(responseCode, e.Message));
                    }
                    else
                    {
                        return(new Tuple <HttpStatusCode, string>(HttpStatusCode.InternalServerError, e.Message));
                    }
                }
            }

            return(new Tuple <HttpStatusCode, string>(responseCode, responseString));
        }
Exemple #30
0
        protected HTTPResult<String> GetRequestBodyAsUTF8String(HTTPContentType HTTPContentType)
        {
            if (IHTTPConnection.RequestHeader.ContentType != HTTPContentType)
                return new HTTPResult<String>(IHTTPConnection.RequestHeader, HTTPStatusCode.BadRequest);

            if (IHTTPConnection.RequestBody == null || IHTTPConnection.RequestBody.Length == 0)
                return new HTTPResult<String>(IHTTPConnection.RequestHeader, HTTPStatusCode.BadRequest);

            var RequestBodyString = IHTTPConnection.RequestBody.ToUTF8String();

            if (RequestBodyString.IsNullOrEmpty())
                return new HTTPResult<String>(IHTTPConnection.RequestHeader, HTTPStatusCode.BadRequest);

            return new HTTPResult<String>(RequestBodyString);
        }
Exemple #31
0
        /// <summary>
        /// Add a method handler for the given parameters.
        /// </summary>
        public void AddHandler(MethodInfo       myMethodHandler,
                               String           myHost,
                               String           myURL,
                               HTTPMethod       myHTTPMethod                = null,
                               HTTPContentType  myHTTPContentType           = null,
                               Boolean          HostAuthentication          = false,
                               Boolean          URLAuthentication           = false,
                               Boolean          HTTPMethodAuthentication    = false,
                               Boolean          ContentTypeAuthentication   = false)
        {
            #region Initial Checks

            if (myMethodHandler == null)
                throw new ArgumentNullException("The MethodHandler must not be null!");

            if (myHost == null || myHost == String.Empty)
                myHost = "*";

            if (myURL == null || myURL == String.Empty)
                throw new ArgumentNullException("The URL must not be null!");

            if (myHTTPMethod == null && myHTTPContentType != null)
                throw new ArgumentNullException("If myHTTPMethod is null the myHTTPContentType has also to be null!");

            #endregion

            #region AddOrUpdate HostNode

            HostNode _HostNode = null;
            if (!_HostNodes.TryGetValue(myHost, out _HostNode))
            {
                _HostNode = new HostNode(myHost, HostAuthentication);
                _HostNodes.AddOrUpdate(myHost, _HostNode, (k, v) => v);
            }

            #endregion

            #region AddOrUpdate URLNode

            URLNode _URLNode = null;
            if (!_HostNode.URLNodes.TryGetValue(myURL, out _URLNode))
            {

                if (myHTTPMethod == null)
                    _URLNode = new URLNode(myURL, myMethodHandler, URLAuthentication);

                else
                    _URLNode = new URLNode(myURL, null, URLAuthentication);

            }

            _HostNode.URLNodes.AddOrUpdate(myURL, _URLNode, (k, v) => v);

            if (myHTTPMethod == null)
                return;

            #endregion

            #region AddOrUpdate HTTPMethodNode

            HTTPMethodNode _HTTPMethodNode = null;
            if (!_URLNode.HTTPMethods.TryGetValue(myHTTPMethod, out _HTTPMethodNode))
            {

                if (myHTTPContentType == null)
                    _HTTPMethodNode = new HTTPMethodNode(myHTTPMethod, myMethodHandler, HTTPMethodAuthentication);

                else
                    _HTTPMethodNode = new HTTPMethodNode(myHTTPMethod, null, HTTPMethodAuthentication, HandleContentTypes: true);

            }

            _URLNode.HTTPMethods.AddOrUpdate(myHTTPMethod, _HTTPMethodNode, (k, v) => v);

            if (myHTTPContentType == null)
                return;

            #endregion

            #region AddOrUpdate ContentTypeNode

            ContentTypeNode _ContentTypeNode = null;
            if (!_HTTPMethodNode.HTTPContentTypes.TryGetValue(myHTTPContentType, out _ContentTypeNode))
            {
                _ContentTypeNode = new ContentTypeNode(myHTTPContentType, myMethodHandler, ContentTypeAuthentication);
            }

            _HTTPMethodNode.HTTPContentTypes.AddOrUpdate(myHTTPContentType, _ContentTypeNode, (k, v) => v);

            #endregion
        }
Exemple #32
0
        /// <summary>
        /// Return the best matching method handler for the given parameters.
        /// </summary>
        public Tuple<MethodInfo, IEnumerable<Object>> GetHandler(String myHost, String myURL, HTTPMethod myHTTPMethod = null, HTTPContentType myHTTPContentType = null)
        {
            #region Initial Checks

            if (myHost == null || myHost == String.Empty)
                myHost = "*";

            if (myURL == null || myURL == String.Empty)
                throw new ArgumentNullException("The URL must not be null!");

            #endregion

            #region Get HostNode

            HostNode _HostNode = null;
            if (!_HostNodes.TryGetValue(myHost, out _HostNode))
                if (!_HostNodes.TryGetValue("*", out _HostNode))
                    return null;

            #endregion

            #region Get best matchin URLNode

            var _RegexList    = from   __URLNode
                                in     _HostNode.URLNodes.Values
                                select new {
                                    URLNode = __URLNode,
                                    Regex   = __URLNode.URLRegex
                                };

            var _AllTemplates = from   _RegexTupel
                                in     _RegexList
                                select new {
                                    URLNode = _RegexTupel.URLNode,
                                    Match   = _RegexTupel.Regex.Match(myURL)
                                };

            var _Matches      = from    _Match
                                in      _AllTemplates
                                where   _Match.Match.Success
                                orderby 100*_Match.URLNode.SortLength +
                                            _Match.URLNode.ParameterCount
                                        descending
                                select  new {
                                    URLNode = _Match.URLNode,
                                    Match   = _Match.Match
                                };

            var _BestMatch    = _Matches.First();

            //Console.WriteLine(_BestMatch.URLNode.URLTemplate);
            //_Matches.ForEach(_m => { if (_m.Match.Success) Console.WriteLine("Match Length:'" + _m.Match.Length + "'+" + _m.URLNode.ParameterCount + " Groups[1]:'" + _m.Match.Groups[1] + "' URLTemplate:'" + _m.URLNode.URLTemplate + "'"); });

            // Copy MethodHandler Parameters
            var _Parameters = new List<Object>();
            for (var i=1; i< _BestMatch.Match.Groups.Count; i++)
                _Parameters.Add(_BestMatch.Match.Groups[i].Value);

            // If no HTTPMethod was given => return best matching URL MethodHandler
            if (myHTTPMethod == null)
                return new Tuple<MethodInfo, IEnumerable<Object>>(_BestMatch.URLNode.MethodHandler, _Parameters);

            #endregion

            #region Get HTTPMethodNode

            HTTPMethodNode _HTTPMethodNode = null;

            // If no HTTPMethod was found => return best matching URL MethodHandler
            if (!_BestMatch.URLNode.HTTPMethods.TryGetValue(myHTTPMethod, out _HTTPMethodNode))
                return new Tuple<MethodInfo, IEnumerable<Object>>(_BestMatch.URLNode.MethodHandler, _Parameters);

            // If no HTTPContentType was given => return HTTPMethod MethodHandler
            if (myHTTPContentType == null)
                return new Tuple<MethodInfo, IEnumerable<Object>>(_HTTPMethodNode.MethodHandler, _Parameters);
            else
            {
                var _ContentTypeNode = _HTTPMethodNode.HTTPContentTypes[myHTTPContentType];
                return new Tuple<MethodInfo, IEnumerable<Object>>(_ContentTypeNode.MethodHandler, _Parameters);
            }

            #endregion

            // If all fails => return ErrorHandler!
            return GetErrorHandler(myHost, myURL, myHTTPMethod, myHTTPContentType, HTTPStatusCode.BadRequest);
        }
        /// <summary>
        /// Create a new OICP roaming client for CPOs.
        /// </summary>
        /// <param name="ClientId">A unqiue identification of this client.</param>
        /// <param name="RemoteHostname">The hostname of the remote OICP service.</param>
        /// <param name="RemoteTCPPort">An optional TCP port of the remote OICP service.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCertificateSelector">A delegate to select a TLS client certificate.</param>
        /// <param name="RemoteHTTPVirtualHost">An optional HTTP virtual hostname of the remote OICP service.</param>
        /// <param name="HTTPUserAgent">An optional HTTP user agent identification string for this HTTP client.</param>
        /// <param name="RequestTimeout">An optional timeout for upstream queries.</param>
        /// <param name="MaxNumberOfRetries">The default number of maximum transmission retries.</param>
        ///
        /// <param name="ServerName">An optional identification string for the HTTP server.</param>
        /// <param name="ServiceName">An optional identification for this SOAP service.</param>
        /// <param name="ServerTCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="ServerURLPrefix">An optional prefix for the HTTP URLs.</param>
        /// <param name="ServerContentType">An optional HTTP content type to use.</param>
        /// <param name="ServerRegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="ServerAutoStart">Whether to start the server immediately or not.</param>
        ///
        /// <param name="ClientLoggingContext">An optional context for logging client methods.</param>
        /// <param name="ServerLoggingContext">An optional context for logging server methods.</param>
        /// <param name="LogfileCreator">A delegate to create a log file from the given context and log file name.</param>
        ///
        /// <param name="DNSClient">An optional DNS client to use.</param>
        public CPORoaming(String ClientId,
                          HTTPHostname RemoteHostname,
                          IPPort?RemoteTCPPort = null,
                          RemoteCertificateValidationCallback RemoteCertificateValidator = null,
                          LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                          HTTPHostname?RemoteHTTPVirtualHost = null,
                          HTTPPath?URLPrefix           = null,
                          String EVSEDataURL           = CPOClient.DefaultEVSEDataURL,
                          String EVSEStatusURL         = CPOClient.DefaultEVSEStatusURL,
                          String AuthorizationURL      = CPOClient.DefaultAuthorizationURL,
                          String AuthenticationDataURL = CPOClient.DefaultAuthenticationDataURL,
                          String HTTPUserAgent         = CPOClient.DefaultHTTPUserAgent,
                          TimeSpan?RequestTimeout      = null,
                          Byte?MaxNumberOfRetries      = CPOClient.DefaultMaxNumberOfRetries,

                          String ServerName                     = CPOSOAPServer.DefaultHTTPServerName,
                          IPPort?ServerTCPPort                  = null,
                          String ServiceName                    = null,
                          HTTPPath?ServerURLPrefix              = null,
                          String ServerAuthorizationURL         = CPOSOAPServer.DefaultAuthorizationURL,
                          String ServerReservationURL           = CPOSOAPServer.DefaultReservationURL,
                          HTTPContentType ServerContentType     = null,
                          Boolean ServerRegisterHTTPRootService = true,
                          Boolean ServerAutoStart               = false,

                          String ClientLoggingContext           = CPOClient.CPOClientLogger.DefaultContext,
                          String ServerLoggingContext           = CPOServerLogger.DefaultContext,
                          LogfileCreatorDelegate LogfileCreator = null,

                          DNSClient DNSClient = null)

            : this(new CPOClient(ClientId,
                                 RemoteHostname,
                                 RemoteTCPPort,
                                 RemoteCertificateValidator,
                                 ClientCertificateSelector,
                                 RemoteHTTPVirtualHost,
                                 URLPrefix ?? CPOClient.DefaultURLPrefix,
                                 EVSEDataURL,
                                 EVSEStatusURL,
                                 AuthorizationURL,
                                 AuthenticationDataURL,
                                 HTTPUserAgent,
                                 RequestTimeout,
                                 MaxNumberOfRetries,
                                 DNSClient,
                                 ClientLoggingContext,
                                 LogfileCreator),

                   new CPOSOAPServer(ServerName,
                                     ServerTCPPort,
                                     ServiceName,
                                     ServerURLPrefix ?? CPOSOAPServer.DefaultURLPathPrefix,
                                     ServerAuthorizationURL,
                                     ServerReservationURL,
                                     ServerContentType,
                                     ServerRegisterHTTPRootService,
                                     DNSClient,
                                     false),

                   ServerLoggingContext,
                   LogfileCreator)

        {
            if (ServerAutoStart)
            {
                Start();
            }
        }
 /// <summary>
 /// Creates a new abstract OCPP CIMS service.
 /// </summary>
 /// <param name="IHTTPConnection">The http connection for this request.</param>
 /// <param name="HTTPContentType">A content type.</param>
 /// <param name="ResourcePath">The path to internal resources.</param>
 public AGraphService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType)
     : base(IHTTPConnection, HTTPContentType, "GraphServer.resources.")
 { }
 /// <summary>
 /// Add a HTTPContentType and its quality to the Accept header field.
 /// </summary>
 /// <param name="HTTPContentType">A HTTPContentType.</param>
 /// <param name="Quality">The quality of the HTTPContentType.</param>
 public HTTPRequestBuilder AddAccept(HTTPContentType HTTPContentType, Double Quality = 1)
 {
     this.Accept.Add(HTTPContentType, Quality);
     return this;
 }
Exemple #36
0
 /// <summary>
 /// Creates a new abstract OCPP CIMS service.
 /// </summary>
 /// <param name="HTTPContentType">A content type.</param>
 public AProjectService(HTTPContentType HTTPContentType)
     : base(HTTPContentType)
 {
 }
Exemple #37
0
 /// <summary>
 /// Creates a new abstract graph service.
 /// </summary>
 /// <param name="HTTPContentType">A content type.</param>
 public ABifrostService(HTTPContentType HTTPContentType)
     : base(HTTPContentType)
 {
 }
Exemple #38
0
        /// <summary>
        /// Add a method callback for the given URL template.
        /// </summary>
        /// <param name="CommonAPI">The OCPI Common API.</param>
        /// <param name="Hostname">The HTTP hostname.</param>
        /// <param name="HTTPMethod">The HTTP method.</param>
        /// <param name="URLTemplate">The URL template.</param>
        /// <param name="HTTPContentType">The HTTP content type.</param>
        /// <param name="URLAuthentication">Whether this method needs explicit uri authentication or not.</param>
        /// <param name="HTTPMethodAuthentication">Whether this method needs explicit HTTP method authentication or not.</param>
        /// <param name="ContentTypeAuthentication">Whether this method needs explicit HTTP content type authentication or not.</param>
        /// <param name="OCPIRequestLogger">A OCPI request logger.</param>
        /// <param name="OCPIResponseLogger">A OCPI response logger.</param>
        /// <param name="DefaultErrorHandler">The default error handler.</param>
        /// <param name="OCPIRequestHandler">The method to call.</param>
        public static void AddOCPIMethod(this CommonAPI CommonAPI,
                                         HTTPHostname Hostname,
                                         HTTPMethod HTTPMethod,
                                         HTTPPath URLTemplate,
                                         HTTPContentType HTTPContentType              = null,
                                         HTTPAuthentication URLAuthentication         = null,
                                         HTTPAuthentication HTTPMethodAuthentication  = null,
                                         HTTPAuthentication ContentTypeAuthentication = null,
                                         OCPIRequestLogHandler OCPIRequestLogger      = null,
                                         OCPIResponseLogHandler OCPIResponseLogger    = null,
                                         HTTPDelegate DefaultErrorHandler             = null,
                                         OCPIRequestDelegate OCPIRequestHandler       = null,
                                         URLReplacement AllowReplacement              = URLReplacement.Fail)

        {
            CommonAPI.HTTPServer.
            AddMethodCallback(Hostname,
                              HTTPMethod,
                              URLTemplate,
                              HTTPContentType,
                              URLAuthentication,
                              HTTPMethodAuthentication,
                              ContentTypeAuthentication,
                              (timestamp, httpAPI, httpRequest) => OCPIRequestLogger?.Invoke(timestamp, null, HTTP.OCPIRequest.Parse(httpRequest, CommonAPI)),
                              (timestamp, httpAPI, httpRequest, httpResponse) => OCPIResponseLogger?.Invoke(timestamp, null, httpRequest.SubprotocolRequest  as OCPIRequest,
                                                                                                            (httpResponse.SubprotocolResponse as OCPIResponse)
                                                                                                            ?? new OCPIResponse(httpRequest.SubprotocolRequest as OCPIRequest,
                                                                                                                                2000,
                                                                                                                                "OCPIResponse is null!",
                                                                                                                                httpResponse.HTTPBodyAsUTF8String,
                                                                                                                                httpResponse.Timestamp,
                                                                                                                                httpResponse)),
                              DefaultErrorHandler,
                              async httpRequest => {
                try
                {
                    // When no OCPIRequestLogger was used!
                    if (httpRequest.SubprotocolRequest is null)
                    {
                        httpRequest.SubprotocolRequest = OCPIRequest.Parse(httpRequest, CommonAPI);
                    }

                    var OCPIResponseBuilder = await OCPIRequestHandler(httpRequest.SubprotocolRequest as OCPIRequest);
                    var httpResponseBuilder = OCPIResponseBuilder.ToHTTPResponseBuilder();

                    httpResponseBuilder.SubprotocolResponse = new OCPIResponse(OCPIResponseBuilder.Request,
                                                                               OCPIResponseBuilder.StatusCode ?? 3000,
                                                                               OCPIResponseBuilder.StatusMessage,
                                                                               OCPIResponseBuilder.AdditionalInformation,
                                                                               OCPIResponseBuilder.Timestamp ?? DateTime.UtcNow,
                                                                               httpResponseBuilder.AsImmutable);

                    return(httpResponseBuilder);
                }
                catch (Exception e)
                {
                    return(new HTTPResponse.Builder(HTTPStatusCode.InternalServerError)
                    {
                        ContentType = HTTPContentType.JSON_UTF8,
                        Content = new OCPIResponse <JObject>(
                            JSONObject.Create(
                                new JProperty("description", e.Message),
                                new JProperty("stacktrace", e.StackTrace.Split(new String[] { Environment.NewLine }, StringSplitOptions.None).ToArray()),
                                new JProperty("source", e.TargetSite.Module.Name),
                                new JProperty("type", e.TargetSite.ReflectedType.Name)
                                ),
                            2000,
                            e.Message,
                            null,
                            DateTime.UtcNow,
                            null,
                            (httpRequest.SubprotocolRequest as OCPIRequest)?.RequestId,
                            (httpRequest.SubprotocolRequest as OCPIRequest)?.CorrelationId
                            ).ToJSON(json => json).ToUTF8Bytes(),
                        Connection = "close"
                    });
                }
            },
                              AllowReplacement);
        }
        private static Tuple <HttpStatusCode, string> MakeQrsRequest(string path, HTTPMethod method, HTTPContentType contentType = HTTPContentType.json, byte[] body = null)
        {
            // Fix Path
            if (!path.StartsWith("/"))
            {
                path = '/' + path;
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            int indexOfSlash = path.LastIndexOf('/');
            int indexOfQuery = path.LastIndexOf('?');

            if (indexOfQuery <= indexOfSlash)
            {
                path += "?";
            }
            else
            {
                path += "&";
            }

            string         responseString = "";
            HttpStatusCode responseCode   = 0;

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

            //Create the HTTP Request and add required headers and content in xrfkey
            string         xrfkey  = "0123456789abcdef";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://*****:*****@"UserDirectory=internal;UserId=sa_api");
            // Add the certificate to the request and provide the user to execute as
            request.ClientCertificates.Add(SENSE_CERT.Value);

            if (method == HTTPMethod.POST || method == HTTPMethod.PUT)
            {
                // Set Headers
                if (contentType == HTTPContentType.json)
                {
                    request.ContentType = "application/json";
                }
                else if (contentType == HTTPContentType.app)
                {
                    request.ContentType = "application/vnd.qlik.sense.app";
                }
                else
                {
                    throw new ArgumentException("Content type '" + contentType.ToString() + "' is not supported.");
                }

                // Set Body
                if (body == null)
                {
                    request.ContentLength = 0;
                }
                else
                {
                    request.ContentLength = body.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(body, 0, body.Length);
                    requestStream.Close();
                }
            }

            // make the web request and return the content
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    responseCode = response.StatusCode;
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            // if response is invalid, throw exception and expect it to be handled in calling function (4xx errors)
                            responseString = JsonConvert.SerializeObject(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (WebException webEx)
            {
                return(new Tuple <HttpStatusCode, string>(HttpStatusCode.ServiceUnavailable, webEx.Message));
            }
            catch (Exception e)
            {
                return(new Tuple <HttpStatusCode, string>(HttpStatusCode.InternalServerError, e.Message));
            }

            return(new Tuple <HttpStatusCode, string>(responseCode, responseString));
        }
        /// <summary>
        /// Returns a resource from the given file system location.
        /// </summary>
        /// <param name="HTTPServer">A HTTP server.</param>
        /// <param name="Hostname">The HTTP hostname.</param>
        /// <param name="URITemplate">An URI template.</param>
        /// <param name="ResourceFilenameBuilder">The path to the file within the assembly.</param>
        /// <param name="DefaultFile">If an error occures, return this file.</param>
        /// <param name="ResponseContentType">Set the HTTP MIME content-type of the file. If null try to autodetect the content type based on the filename extention.</param>
        /// <param name="CacheControl">Set the HTTP cache control response header.</param>
        public static void RegisterFilesystemFile(this HTTPServer         HTTPServer,
                                                  HTTPHostname            Hostname,
                                                  String                  URITemplate,
                                                  Func<String[], String>  ResourceFilenameBuilder,
                                                  String                  DefaultFile          = null,
                                                  HTTPContentType         ResponseContentType  = null,
                                                  String                  CacheControl         = "no-cache")
        {
            #region Get the appropriate content type based on the suffix returned by the ResourceFilenameBuilder

                                                                                  // NumberOfTemplateParameters
            var _ResourceFilename = ResourceFilenameBuilder(Enumerable.Repeat("", URITemplate.Count(c => c == '{')).ToArray());

            if (ResponseContentType == null)
                switch (_ResourceFilename.Remove(0, _ResourceFilename.LastIndexOf(".") + 1))
                {
                    case "htm":  ResponseContentType = HTTPContentType.HTML_UTF8;       break;
                    case "html": ResponseContentType = HTTPContentType.HTML_UTF8;       break;
                    case "css":  ResponseContentType = HTTPContentType.CSS_UTF8;        break;
                    case "gif":  ResponseContentType = HTTPContentType.GIF;             break;
                    case "jpg":  ResponseContentType = HTTPContentType.JPEG;            break;
                    case "jpeg": ResponseContentType = HTTPContentType.JPEG;            break;
                    case "svg":  ResponseContentType = HTTPContentType.SVG;             break;
                    case "png":  ResponseContentType = HTTPContentType.PNG;             break;
                    case "ico":  ResponseContentType = HTTPContentType.ICO;             break;
                    case "swf":  ResponseContentType = HTTPContentType.SWF;             break;
                    case "js":   ResponseContentType = HTTPContentType.JAVASCRIPT_UTF8; break;
                    case "txt":  ResponseContentType = HTTPContentType.TEXT_UTF8;       break;
                    default:     ResponseContentType = HTTPContentType.OCTETSTREAM;     break;
                }

            #endregion

            HTTPServer.AddMethodCallback(Hostname,
                                         HTTPMethod.GET,
                                         URITemplate,
                                         HTTPContentType: ResponseContentType,
                                         HTTPDelegate: async Request => {

                                             var ResourceFilename = ResourceFilenameBuilder(Request.ParsedURIParameters);

                                             if (!File.Exists(ResourceFilename) && DefaultFile != null)
                                                 ResourceFilename = DefaultFile;

                                             if (File.Exists(ResourceFilename))
                                             {

                                                 var FileStream = File.OpenRead(ResourceFilename);
                                                 if (FileStream != null)
                                                 {

                                                     return new HTTPResponseBuilder(Request)
                                                     {
                                                         HTTPStatusCode  = HTTPStatusCode.OK,
                                                         Server          = HTTPServer.DefaultServerName,
                                                         Date            = DateTime.Now,
                                                         ContentType     = ResponseContentType,
                                                         ContentStream   = FileStream,
                                                         CacheControl    = CacheControl,
                                                         Connection      = "close",
                                                     };

                                                 }

                                             }

                                             return new HTTPResponseBuilder(Request)
                                             {
                                                 HTTPStatusCode  = HTTPStatusCode.NotFound,
                                                 Server          = HTTPServer.DefaultServerName,
                                                 Date            = DateTime.Now,
                                                 CacheControl    = "no-cache",
                                                 Connection      = "close",
                                             };

                                         }, AllowReplacement: URIReplacement.Fail);

            return;
        }
Exemple #41
0
        /// <summary>
        /// Creates a new abstract graph service.
        /// </summary>
        /// <param name="IHTTPConnection">The http connection for this request.</param>
        /// <param name="HTTPContentType">A http content type.</param>
        public ABifrostService(IHTTPConnection IHTTPConnection, HTTPContentType HTTPContentType)
            : base(IHTTPConnection, HTTPContentType, "GraphServer.resources.")
        {
            this.Graph    = new ThreadLocal<IReadOnlyGenericPropertyGraph <String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object>>();

            this.Vertex   = new ThreadLocal<IReadOnlyGenericPropertyVertex<String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object>>();

            this.Edge     = new ThreadLocal<IReadOnlyGenericPropertyEdge  <String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object,
                                                                           String, Int64, String, String, Object>>();

            this.Callback = new ThreadLocal<String>();
            this.Skip     = new ThreadLocal<UInt64>();
            this.Take     = new ThreadLocal<UInt64>();
        }
Exemple #42
0
        // Error Handling

        #region (internal) GetErrorHandler(Host, URL, HTTPMethod = null, HTTPContentType = null, HTTPStatusCode = null)

        /// <summary>
        /// Return the best matching error handler for the given parameters.
        /// </summary>
        internal Tuple<MethodInfo, IEnumerable<Object>> GetErrorHandler(String           Host,
                                                                        String           URL,
                                                                        HTTPMethod       HTTPMethod       = null,
                                                                        HTTPContentType  HTTPContentType  = null,
                                                                        HTTPStatusCode   HTTPStatusCode   = null)

        {

            lock (Lock)
            {
                return null;
            }

        }
        /// <summary>
        /// Returns internal resources embedded within the given assembly.
        /// </summary>
        /// <param name="HTTPServer">A HTTP server.</param>
        /// <param name="Hostname">The HTTP hostname.</param>
        /// <param name="URITemplate">An URI template.</param>
        /// <param name="ResourceAssembly">The assembly where the resources are located.</param>
        /// <param name="ResourceFilename">The path to the file within the assembly.</param>
        /// <param name="ResponseContentType">Set the HTTP MIME content-type of the file. If null try to autodetect the content type based on the filename extention.</param>
        /// <param name="CacheControl">Set the HTTP cache control response header.</param>
        public static void RegisterResourcesFile(this HTTPServer  HTTPServer,
                                                 HTTPHostname     Hostname,
                                                 String           URITemplate,
                                                 Assembly         ResourceAssembly,
                                                 String           ResourceFilename,
                                                 HTTPContentType  ResponseContentType  = null,
                                                 String           CacheControl         = "no-cache")
        {
            #region Get the appropriate content type based on the suffix of the requested resource

            if (ResponseContentType == null)
                switch (ResourceFilename.Remove(0, ResourceFilename.LastIndexOf(".") + 1))
                {
                    case "htm":  ResponseContentType = HTTPContentType.HTML_UTF8;       break;
                    case "html": ResponseContentType = HTTPContentType.HTML_UTF8;       break;
                    case "css":  ResponseContentType = HTTPContentType.CSS_UTF8;        break;
                    case "gif":  ResponseContentType = HTTPContentType.GIF;             break;
                    case "jpg":  ResponseContentType = HTTPContentType.JPEG;            break;
                    case "jpeg": ResponseContentType = HTTPContentType.JPEG;            break;
                    case "svg":  ResponseContentType = HTTPContentType.SVG;             break;
                    case "png":  ResponseContentType = HTTPContentType.PNG;             break;
                    case "ico":  ResponseContentType = HTTPContentType.ICO;             break;
                    case "swf":  ResponseContentType = HTTPContentType.SWF;             break;
                    case "js":   ResponseContentType = HTTPContentType.JAVASCRIPT_UTF8; break;
                    case "txt":  ResponseContentType = HTTPContentType.TEXT_UTF8;       break;
                    case "xml":  ResponseContentType = HTTPContentType.XML_UTF8;        break;
                    default:     ResponseContentType = HTTPContentType.OCTETSTREAM;     break;
                }

            #endregion

            HTTPServer.AddMethodCallback(Hostname,
                                         HTTPMethod.GET,
                                         URITemplate,
                                         HTTPContentType: ResponseContentType,
                                         HTTPDelegate: async Request => {

                                             var FileStream = ResourceAssembly.GetManifestResourceStream(ResourceFilename);

                                             if (FileStream != null)
                                                 return new HTTPResponseBuilder(Request) {
                                                     HTTPStatusCode  = HTTPStatusCode.OK,
                                                     Server          = HTTPServer.DefaultServerName,
                                                     Date            = DateTime.Now,
                                                     ContentType     = ResponseContentType,
                                                     ContentStream   = FileStream,
                                                     CacheControl    = CacheControl,
                                                     Connection      = "close",
                                                 };

                                             else
                                             {

                                                 #region Try to find a appropriate customized errorpage...

                                                 Stream ErrorStream = null;

                                                 Request.BestMatchingAcceptType = Request.Accept.BestMatchingContentType(new HTTPContentType[] { HTTPContentType.HTML_UTF8, HTTPContentType.TEXT_UTF8 });

                                                 if (Request.BestMatchingAcceptType == HTTPContentType.HTML_UTF8)
                                                 {
                                                     ResponseContentType = HTTPContentType.HTML_UTF8;
                                                     ErrorStream         = ResourceAssembly.GetManifestResourceStream(ResourceFilename.Substring(0, ResourceFilename.LastIndexOf(".")) + ".ErrorPages." + "404.html");
                                                 }

                                                 else if (Request.BestMatchingAcceptType == HTTPContentType.TEXT_UTF8)
                                                 {
                                                     ResponseContentType = HTTPContentType.TEXT_UTF8;
                                                     ErrorStream         = ResourceAssembly.GetManifestResourceStream(ResourceFilename.Substring(0, ResourceFilename.LastIndexOf(".")) + ".ErrorPages." + "404.txt");
                                                 }

                                                 else if (Request.BestMatchingAcceptType == HTTPContentType.JSON_UTF8)
                                                 {
                                                     ResponseContentType = HTTPContentType.JSON_UTF8;
                                                     ErrorStream         = ResourceAssembly.GetManifestResourceStream(ResourceFilename.Substring(0, ResourceFilename.LastIndexOf(".")) + ".ErrorPages." + "404.js");
                                                 }

                                                 else if (Request.BestMatchingAcceptType == HTTPContentType.XML_UTF8)
                                                 {
                                                     ResponseContentType = HTTPContentType.XML_UTF8;
                                                     ErrorStream         = ResourceAssembly.GetManifestResourceStream(ResourceFilename.Substring(0, ResourceFilename.LastIndexOf(".")) + ".ErrorPages." + "404.xml");
                                                 }

                                                 else if (Request.BestMatchingAcceptType == HTTPContentType.ALL)
                                                 {
                                                     ResponseContentType = HTTPContentType.HTML_UTF8;
                                                     ErrorStream         = ResourceAssembly.GetManifestResourceStream(ResourceFilename.Substring(0, ResourceFilename.LastIndexOf(".")) + ".ErrorPages." + "404.html");
                                                 }

                                                 if (ErrorStream != null)
                                                     return new HTTPResponseBuilder(Request) {
                                                         HTTPStatusCode = HTTPStatusCode.NotFound,
                                                         ContentType    = ResponseContentType,
                                                         ContentStream  = ErrorStream,
                                                         CacheControl   = "no-cache",
                                                         Connection     = "close",
                                                     };

                                                 #endregion

                                                 #region ...or send a default error page!

                                                 else
                                                     return new HTTPResponseBuilder(Request) {
                                                         HTTPStatusCode  = HTTPStatusCode.NotFound,
                                                         Server          = HTTPServer.DefaultServerName,
                                                         Date            = DateTime.Now,
                                                         CacheControl    = "no-cache",
                                                         Connection      = "close",
                                                     };

                                                 #endregion

                                             }

                                         }, AllowReplacement: URIReplacement.Fail);

            return;
        }
Exemple #44
0
        // Method Callbacks

        #region (internal) AddHandler(HTTPDelegate, Hostname = "*", URITemplate = "/", HTTPMethod = null, HTTPContentType = null, HostAuthentication = null, URIAuthentication = null, HTTPMethodAuthentication = null, ContentTypeAuthentication = null, DefaultErrorHandler = null)

        /// <summary>
        /// Add a method callback for the given URI template.
        /// </summary>
        /// <param name="HTTPDelegate">A delegate called for each incoming HTTP request.</param>
        /// <param name="Hostname">The HTTP hostname.</param>
        /// <param name="URITemplate">The URI template.</param>
        /// <param name="HTTPMethod">The HTTP method.</param>
        /// <param name="HTTPContentType">The HTTP content type.</param>
        /// <param name="HostAuthentication">Whether this method needs explicit host authentication or not.</param>
        /// <param name="URIAuthentication">Whether this method needs explicit uri authentication or not.</param>
        /// <param name="HTTPMethodAuthentication">Whether this method needs explicit HTTP method authentication or not.</param>
        /// <param name="ContentTypeAuthentication">Whether this method needs explicit HTTP content type authentication or not.</param>
        /// <param name="DefaultErrorHandler">The default error handler.</param>
        internal void AddHandler(HTTPDelegate        HTTPDelegate,

                                 HTTPHostname        Hostname                    = null,
                                 String              URITemplate                 = "/",
                                 HTTPMethod          HTTPMethod                  = null,
                                 HTTPContentType     HTTPContentType             = null,

                                 HTTPAuthentication  HostAuthentication          = null,
                                 HTTPAuthentication  URIAuthentication           = null,
                                 HTTPAuthentication  HTTPMethodAuthentication    = null,
                                 HTTPAuthentication  ContentTypeAuthentication   = null,

                                 HTTPDelegate        DefaultErrorHandler         = null,
                                 URIReplacement      AllowReplacement            = URIReplacement.Fail)

        {

            lock (Lock)
            {

                #region Initial Checks

                if (HTTPDelegate == null)
                    throw new ArgumentNullException("HTTPDelegate", "The given parameter must not be null!");

                if (Hostname == null)
                    Hostname = HTTPHostname.Any;

                if (URITemplate.IsNullOrEmpty())
                    URITemplate = "/";

                if (HTTPMethod == null && HTTPContentType != null)
                    throw new ArgumentNullException("If HTTPMethod is null the HTTPContentType must also be null!");

                #endregion

                #region AddOrUpdate HostNode

                HostnameNode _HostnameNode = null;
                if (!_HostnameNodes.TryGetValue(Hostname, out _HostnameNode))
                {
                    _HostnameNode = new HostnameNode(Hostname, HostAuthentication, HTTPDelegate, DefaultErrorHandler);
                    _HostnameNodes.Add(Hostname, _HostnameNode);
                }

                #endregion

                _HostnameNode.AddHandler(HTTPDelegate,

                                         URITemplate,
                                         HTTPMethod,
                                         HTTPContentType,

                                         URIAuthentication,
                                         HTTPMethodAuthentication,
                                         ContentTypeAuthentication,

                                         DefaultErrorHandler,
                                         AllowReplacement);

            }

        }
Exemple #45
0
        public static HTTPResult<XDocument> ParseXMLRequestBody(this HTTPRequest  Request,
                                                                HTTPContentType   ContentType = null)
        {

            var RequestBodyString = Request.GetRequestBodyAsUTF8String(ContentType != null ? ContentType : HTTPContentType.XMLTEXT_UTF8);
            if (RequestBodyString.HasErrors)
                return new HTTPResult<XDocument>(RequestBodyString.Error);

            XDocument RequestBodyXML;

            try
            {
                RequestBodyXML = XDocument.Parse(RequestBodyString.Data);
            }
            catch (Exception e)
            {
                Log.WriteLine(e.Message);
                return new HTTPResult<XDocument>(Request, HTTPStatusCode.BadRequest);
            }

            return new HTTPResult<XDocument>(RequestBodyXML);

        }
Exemple #46
0
        /// <summary>
        /// Add a method call back for the given URI template and
        /// add a HTTP Sever Sent Events source.
        /// </summary>
        /// <param name="EventIdentification">The unique identification of the event source.</param>
        /// <param name="MaxNumberOfCachedEvents">Maximum number of cached events.</param>
        /// <param name="RetryIntervall">The retry intervall.</param>
        /// 
        /// <param name="Hostname">The HTTP host.</param>
        /// <param name="URITemplate">The URI template.</param>
        /// <param name="HTTPMethod">The HTTP method.</param>
        /// <param name="HTTPContentType">The HTTP content type.</param>
        /// 
        /// <param name="HostAuthentication">Whether this method needs explicit host authentication or not.</param>
        /// <param name="URIAuthentication">Whether this method needs explicit uri authentication or not.</param>
        /// <param name="HTTPMethodAuthentication">Whether this method needs explicit HTTP method authentication or not.</param>
        /// 
        /// <param name="DefaultErrorHandler">The default error handler.</param>
        internal HTTPEventSource AddEventSource(String              EventIdentification,
                                                UInt32              MaxNumberOfCachedEvents     = 500,
                                                TimeSpan?           RetryIntervall              = null,

                                                HTTPHostname        Hostname                    = null,
                                                String              URITemplate                 = "/",
                                                HTTPMethod          HTTPMethod                  = null,
                                                HTTPContentType     HTTPContentType             = null,

                                                HTTPAuthentication  HostAuthentication          = null,
                                                HTTPAuthentication  URIAuthentication           = null,
                                                HTTPAuthentication  HTTPMethodAuthentication    = null,

                                                HTTPDelegate        DefaultErrorHandler         = null)

        {

            lock (Lock)
            {

                #region Get or Create Event Source

                HTTPEventSource _HTTPEventSource;

                if (!_EventSources.TryGetValue(EventIdentification, out _HTTPEventSource))
                    _HTTPEventSource = _EventSources.AddAndReturnValue(EventIdentification,
                                                                       new HTTPEventSource(EventIdentification, MaxNumberOfCachedEvents, RetryIntervall));

                #endregion

                #region Define HTTP Delegate

                HTTPDelegate _HTTPDelegate = Request => {

                    var _LastEventId        = 0UL;
                    var _Client_LastEventId = 0UL;
                    var _EventSource        = GetEventSource(EventIdentification);

                    if (Request.TryGet<UInt64>("Last-Event-ID", out _Client_LastEventId))
                        _LastEventId = _Client_LastEventId;

                    var _HTTPEvents      = (from   _HTTPEvent
                                            in     _EventSource.GetAllEventsGreater(_LastEventId)
                                            where  _HTTPEvent != null
                                            select _HTTPEvent.ToString())
                                           .ToArray(); // For thread safety!

                    // Transform HTTP events into an UTF8 string
                    var _ResourceContent = String.Empty;

                    if (_HTTPEvents.Length > 0)
                        _ResourceContent = Environment.NewLine + _HTTPEvents.Aggregate((a, b) => a + Environment.NewLine + b) + Environment.NewLine;

                    else
                        _ResourceContent += Environment.NewLine + "retry: " + ((UInt32) _EventSource.RetryIntervall.TotalMilliseconds) + Environment.NewLine + Environment.NewLine;


                    return Task.FromResult<HTTPResponse>(
                        new HTTPResponseBuilder(Request) {
                            HTTPStatusCode  = HTTPStatusCode.OK,
                            ContentType     = HTTPContentType.EVENTSTREAM,
                            CacheControl    = "no-cache",
                            Connection      = "keep-alive",
                            KeepAlive       = new KeepAliveType(TimeSpan.FromSeconds(2*_EventSource.RetryIntervall.TotalSeconds)),
                            Content         = _ResourceContent.ToUTF8Bytes()
                        });

                };

                #endregion

                AddHandler(_HTTPDelegate,
                           Hostname,
                           URITemplate,
                           HTTPMethod ?? HTTPMethod.GET,
                           HTTPContentType.EVENTSTREAM,

                           HostAuthentication,
                           URIAuthentication,
                           HTTPMethodAuthentication,
                           null,

                           DefaultErrorHandler);

                return _HTTPEventSource;

            }

        }
        public static bool HttpWebResponsePOST(WebProxy objProxy, string strURL, Dictionary <string, string> objHttpHeader, string strPostData, HTTPContentType enumContentType, out string strContent)
        {
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, charin, sslPolicyErrors) => true;
            try
            {
                WebRequest webRequest  = (WebRequest)WebRequest.Create(strURL);
                Encoding   objEncoding = new UTF8Encoding();
                byte[]     objData     = objEncoding.GetBytes(strPostData);
                webRequest.Method = "GET";
                if (objHttpHeader != null)
                {
                    foreach (KeyValuePair <string, string> item in objHttpHeader)
                    {
                        webRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                webRequest.ContentLength = objData.Length;
                if (enumContentType == HTTPContentType.UTF8)
                {
                    webRequest.ContentType = "charset=UTF-8";
                }
                else
                {
                    webRequest.ContentType = "application/json";
                }

                if (objProxy != null)
                {
                    webRequest.Proxy = objProxy;
                }

                Stream objStream = webRequest.GetRequestStream();
                objStream.Write(objData, 0, objData.Length);
                objStream.Close();

                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (Stream data = webResponse.GetResponseStream())
                        using (var objReader = new StreamReader(data))
                            strContent = objReader.ReadToEnd();
                }
                return(true);
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    strContent = ex.Message;
                }
                else
                {
                    using (WebResponse webResponse = ex.Response)
                    {
                        HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
                        Console.WriteLine("Error Code: {0} for {1}", httpWebResponse.StatusCode, strURL);
                        using (Stream objData = webResponse.GetResponseStream())
                            using (var objReader = new StreamReader(objData))
                                strContent = objReader.ReadToEnd();
                    }
                }
                return(false);
            }
        }
 /// <summary>
 /// Set the HTTP Content-Type.
 /// </summary>
 /// <param name="ContentType">The type of the HTTP content/body.</param>
 public HTTPResponseBuilder SetContentType(HTTPContentType ContentType)
 {
     this.ContentType = ContentType;
     return this;
 }