Unable to read data from the transport connection.System.Net.Sockets.SocketException from compact framework? - web-services

We get this error about 2 weeks and working resolve but still can't solved !
Do you have any idea about this problem ?
Error Detail;
System.Net.WebException: Unable to read data from the transport connection.System.Net.Sockets.SocketException: Unknown error (0x0).
at System.Net.HttpWebRequest.fillBuffer(HttpWebRequest request, Connection connection, CoreResponseData data)
at System.Net.HttpWebRequest.getLine(HttpWebRequest request, Connection connection, CoreResponseData data)
at System.Net.HttpWebRequest.parseResponse(HttpWebRequest request, Connection connection, Boolean defaultKeepAlive)
at System.Net.HttpWebRequest.startReceiving(Connection connection)
at System.Net.Connection.startReceiving(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
at System.Net.HttpWebRequest.finishGetResponse()
at System.Net.HttpWebRequest.GetResponse()
at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.doInvoke(String methodName, Object[] parameters, WebClientAsyncResult asyncResult)

Related

Channels websocket AsyncJsonWebsocketConsumer disconnect not reached

I have the following consumer:
class ChatConsumer(AsyncJsonWebsocketConsumer):
pusher = None
async def connect(self):
print(self.scope)
ip = self.scope['client'][0]
print(ip)
self.pusher = await self.get_pusher(ip)
print(self.pusher)
await self.accept()
async def disconnect(self, event):
print("closed connection")
print("Close code = ", event)
await self.close()
raise StopConsumer
async def receive_json(self, content):
#print(content)
if 'categoryfunctionname' in content:
await cellvoltage(self.pusher, content)
else:
print("ERROR: Wrong data packets send")
print(content)
#database_sync_to_async
def get_pusher(self, ip):
p = Pusher.objects.get(auto_id=1)
try:
p = Pusher.objects.get(ip=ip)
except ObjectDoesNotExist:
print("no pusher found")
finally:
return p
Connecting, receiving and even getting stuff async from the database works perfectly. Only disconnecting does not work as expected. The following Terminal Log explains what's going on:
2018-09-19 07:09:56,653 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras)
2018-09-19 07:09:56,653 - INFO - server - Configuring endpoint tcp:port=1111:interface=192.168.1.111
2018-09-19 07:09:56,653 - INFO - server - Listening on TCP address 192.168.1.111:1111
[2018/09/19 07:11:25] HTTP GET / 302 [0.02, 10.171.253.112:35236]
[2018/09/19 07:11:25] HTTP GET /login/?next=/ 200 [0.05, 10.111.253.112:35236]
{'type': 'websocket', 'path': '/ws/chat/RP1/', 'headers': [(b'upgrade', b'websocket'), (b'connection', b'Upgrade'), (b'host', b'10.111.111.112:1111'), (b'origin', b'http://10.111.253.112:1111'), (b'sec-websocket-key', b'vKFAnqaRMm84AGUCxbAm3g=='), (b'sec-websocket-version', b'13')], 'query_string': b'', 'client': ['10.111.253.112', 35238], 'server': ['192.168.1.111', 1111], 'subprotocols': [], 'cookies': {}, 'session': <django.utils.functional.LazyObject object at 0x7fe4a8d1ba20>, 'user': <django.utils.functional.LazyObject object at 0x7fe4a8d1b9e8>, 'path_remaining': '', 'url_route': {'args': (), 'kwargs': {'room_name': 'RP1'}}}
10.111.253.112
[2018/09/19 07:11:25] WebSocket HANDSHAKING /ws/chat/RP1/ [10.111.253.112:35238]
[2018/09/19 07:11:25] WebSocket CONNECT /ws/chat/RP1/ [10.111.111.112:35238]
no pusher found
1 - DEFAULT - 0.0.0.0
ERROR: Wrong data packets send
{'hello': 'Did I achieve my objective?'}
[2018/09/19 07:11:46] WebSocket DISCONNECT /ws/chat/RP1/ [10.111.253.112:35238]
2018-09-19 07:11:56,792 - WARNING - server - Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /home/pi/PycharmProjects/LOGGER/venv/lib/python3.6/site-packages/channels/sessions.py:175> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.6/asyncio/futures.py:403, <TaskWakeupMethWrapper object at 0x7fe4a82e6fd8>()]>> for connection <WebSocketProtocol client=['10.171.253.112', 35238] path=b'/ws/chat/RP1/'> took too long to shut down and was killed.
After the 10 seconds timeout it gives a warning that the connection was killed:
WARNING - server - Application instance taskname running at location
at linenumber for connection cxn-name took too long to shut down and
was killed.
The disconnect method was thus also not reached.
What could this be?
Am I using the correct method?
Could I expand the timeout period?
if you are intending to run some custom logic during connection close then you should override websocket_disconnect and then call super (rather than rais the exception yourself)
https://github.com/django/channels/blob/507cb54fcb36df63282dd19653ea743036e7d63c/channels/generic/websocket.py#L228-L241
The code linked in the other answer was very helpful. Here it is for reference (as of May 2022):
async def websocket_disconnect(self, message):
"""
Called when a WebSocket connection is closed. Base level so you don't
need to call super() all the time.
"""
try:
for group in self.groups:
await self.channel_layer.group_discard(group, self.channel_name)
except AttributeError:
raise InvalidChannelLayerError(
"BACKEND is unconfigured or doesn't support groups"
)
await self.disconnect(message["code"])
raise StopConsumer()
async def disconnect(self, code):
"""
Called when a WebSocket connection is closed.
"""
pass
I'd note that there is no need to use super() on websocket_disconnect. They have a hook disconnect which was perhaps added since the original answer that can be used to add any teardown code. You can simply override the disconnect method in your own class and it will be called.

Python Orion Context Broker Token problems

I've been developing the following code:
datos = {
"id":"1",
"type":"Car",
"bra":"0",
}
jsonData = json.dumps(datos)
url = 'http://130.456.456.555:1026/v2/entities'
head = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Auth-Token": token
}
response = requests.post(url, data=jsonData, headers=head)
My problem is that I can't establish a connection between my computer and my fiware Lab instance.
The error is:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='130.206.113.177', port=1026): Max retries exceeded with url: /v1/entities (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f02c97c1f90>: Failed to establish a new connection: [Errno 110] Connection timed out',))
Seems to be a network connectivity problem.
Assuming that there actually an Orion process listening to port 1026 at IP 130.206.113.177 (should be checked, eg. curl localhost:1026/version command executed in the same VM where Orion runs), the most probable causes of Orion connection problems are:
Something in the Orion host (e.g a firewall or security group) is blocking the incoming connection
Something in the client host (e.g a firewall) is blocking the outcoming connection
There is some other network issue is causing the connection problem.

My proxy webservice is missing one method from the real webservice?

I can browse to the urls for both my proxy webservice and my actual webservice and I am missing one method between my proxy service and my actual account service?
I've tried a lot of things and cannot get my proxy to show the same methods. I don't know how to generate the wsdl file that maps the methods and I can even see the file is missing the method and the file is a file from TFS that I downloaded to build my website on the first day I started working here.
I'm trying to change the generated file by hand but its not working. When I do a find on my computer for svcutil or wsdl it comes up with nothing. Is there a special computer I need to be able to run these utilities?
Server Error in '/' Application.
System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://account.hse.org/GetUserNameByMembershipId.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://account.hse.org/GetUserNameByMembershipId.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
Source Error:
Line 197: public string GetUserNameByMembershipId(int membershipID)
Line 198: {
Line 199: object[] results = this.Invoke("GetUserNameByMembershipId", new object[] {
Line 200: membershipID});
Line 201: return ((string)(results[0]));
Source File: c:\TFS\IT\Web\HseStore.org\HseStore\Hse.Sso.Client\Proxies\AuthServiceProxy.cs Line: 199
Stack Trace:
[SoapException: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://account.hse.org/GetUserNameByMembershipId.
at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)]
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +503338
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +215
Vfw.Sso.Client.Proxies.AuthServiceProxy.GetUserNameByMembershipId(Int32 membershipID) in c:\TFS\IT\Web\HseStore.org\HseStore\Hse.Sso.Client\Proxies\AuthServiceProxy.cs:199
Vfw.Sso.Client.Helpers.AuthServiceHelper.GetUserNameByMembershipId(Int32 membershipID) in c:\TFS\IT\Web\HseStore.org\HseStore\Hse.Sso.Client\Helpers\AuthServiceHelper.cs:103
OMS.CreateAccount.btnCreateAccount_Click(Object sender, EventArgs e) in c:\TFS\IT\Web\MAIN\OMSDomain\OMS\CreateAccount.aspx.cs:63
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +124
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
are you using Visual Studio?
an easy way to regenerate the proxy is to remove the service reference and re-add it.
If you need to generate the proxy manually then you need svcutil and this link will tell you how to get it : https://msdn.microsoft.com/en-us/library/aa347733%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
In short, you need the Windows Sdk and then you can find svcutil at this path : C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin

Caused by: java.net.ConnectException: Connection refused: connect org.springframework.web.client.ResourceAccessException: I/O error on POST

I've the following CURL command which works very fine. But when using through java code. I am using WSO2 API Manager version 1.9.1
curl -k -d "grant_type=password&username=test&password=test" -H
"Authorization: Basic QU01dE04MXFrdzg5ZFNFTjk2Vm0waGgwWnBNYTpzeHcxbko3c2gzdm5NVVlmUDEzVmV1bWtsbTRh,
Content-Type: application/x-www-form-urlencoded" https://XXXXXX:8243/token
I developed the following code using RestTemplate API
public class Demo {
public static void main(String[] args) {
String url = "https://xxxxxxxx:8243/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic QU01dE04MXFrdzg5ZFNFTjk2Vm0waGgwWnBNYTpzeHcxbko3c2gzdm5NVVlmUDEzVmV1bWtsbTRh");
headers.add("Content-Type", "application/x-www-form-urlencoded");
headers.add("data", "grant_type=password&username=mahesh&password=mahesh00");
String json =" {\"data\":\"grant_type=password&username=test&password=test\"}";
HttpEntity<String> postEntity = new HttpEntity<String>(json, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =restTemplate.exchange(url, HttpMethod.POST,postEntity,String.class);
System.out.println("\nSTATUS : "+ response.getStatusCode()+" "+response.getStatusCode().getReasonPhrase());
System.out.println("Response :"+ response.getBody());
}
}
When I execute below, I see the following error:
Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://192.168.0.102:8243/token":java.security.cert.CertificateException: No subject alternative names present; nested exception is javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:580)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:448)
at com.java.pushNotifications.Demo.main(Demo.java:25)
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:901)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:837)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:81)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:569)
... 3 more
Caused by: java.security.cert.CertificateException: No subject alternative names present
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:142)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:91)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:203)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
... 17 more
You forgot to specify the port in your java code:
https://192.168.0.102:/token
It should be:
https://192.168.0.102:8243/token
You also forgot to hide the IP here as you did with the curl command, but since it is an internal IP there is no reason to bother with it, it means nothing outside of your own LAN. So I am not masking it either.
I were facing the similar issue-
org.springframework.web.client.ResourceAccessException: I/O error on
POST request for
"http://hostname:port_number/projectname/inbound/message": Connection
refused: connect; nested exception is java.net.ConnectException:
Connection refused: connect
So, I am using application.yml under src/main/resources and I changed the host value from server ip_address to localhost for testing with Swagger on my PC,
gui:
protocol: http
host: localhost
port: 8280
Hope any bit of the information with help someone.

Sending Emails with attachment of less than 10 MB from AWS SES

We are using AWS SES to send Emails from our C# application. We have an attachment(PDF File) of size 9.28MB and when we try to send the Email with the attachment, it throws the following exception:
System.Xml.XmlException: Root element is missing. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at Amazon.Runtime.Internal.Transform.UnmarshallerContext.Read() at Amazon.Runtime.Internal.Transform.ErrorResponseUnmarshaller.Unmarshall(UnmarshallerContext context) at Amazon.SimpleEmail.Model.Transform.SendRawEmailResponseUnmarshaller.UnmarshallException(UnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) at Amazon.Runtime.AmazonWebServiceClient.processWebException[X,Y](String requestName, WebException we, HttpWebRequest webRequest, IResponseUnmarshaller`2 unmarshaller, IRequest`1 request, Int32 retries) at Amazon.Runtime.AmazonWebServiceClient.Invoke[X,Y](IRequest`1 request, AbstractAWSSigner signer, IResponseUnmarshaller`2 unmarshaller) at Amazon.SimpleEmail.AmazonSimpleEmailServiceClient.SendRawEmail(SendRawEmailRequest sendRawEmailRequest) at MyApp.AmazonSESWrapper.SendRawEmail(String awsAccessKey, String awsSecretKey, List`1 to, List`1 cc, List`1 bcc, String senderEmailAddress, String replyToEmailAddress, String subject, String body, String text, String filePath, String exceptionDetails)
But when we send a 7.50MB word document as attachment, we are getting the following exception:
Amazon.SimpleEmail.AmazonSimpleEmailServiceException: Message length is more than 10485760 bytes long: '10788624'. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.GetResponse() at Amazon.Runtime.AmazonWebServiceClient.Invoke[X,Y](IRequest`1 request, AbstractAWSSigner signer, IResponseUnmarshaller`2 unmarshaller) --- End of inner exception stack trace --- at Amazon.Runtime.AmazonWebServiceClient.processWebException[X,Y](String requestName, WebException we, HttpWebRequest webRequest, IResponseUnmarshaller`2 unmarshaller, IRequest`1 request, Int32 retries) at Amazon.Runtime.AmazonWebServiceClient.Invoke[X,Y](IRequest`1 request, AbstractAWSSigner signer, IResponseUnmarshaller`2 unmarshaller) at Amazon.SimpleEmail.AmazonSimpleEmailServiceClient.SendRawEmail(SendRawEmailRequest sendRawEmailRequest) at
From the Discussion Forum and FAQ, it says the maximum attachment size is 10MB, but the error occurs for less than 10MB attachments also.
https://forums.aws.amazon.com/thread.jspa?messageID=346305
http://aws.amazon.com/ses/faqs/#49
Please suggest on this.
There is also overall message size limit, which is also 10M. As per http://aws.amazon.com/ses/faqs/:
Amazon SES will accept email messages up to 10 MB in size. This
includes any attachments that are part of the message.
So you have to ensure your request fits in these limits.
(I personally think its a bug that Amazon API throws "XmlException: Root element is missing." in case when the message size considerably exceeded the limit. It's totally misleading.)