I use MailKit to send messages, app runs on Win 10.
I wrote my Mailservice, and my project used this service to send infos, warnings or fault notifications to me.
In the case that more messages should be sent within a short periode (loop ?), I get the error 'Too many connections open .."
Ok. I used 'Await' to await the end of each step and so I await the end of the disconnect-operation.
How can I get too many open connections?
Private Shared Async Function TransmitMail(mail As MimeMessage) As Task(Of Boolean)
Try
Using client = New SmtpClient()
With client
Await .ConnectAsync(Host, 587, False)
Await .AuthenticateAsync(UserName, Password)
Await .SendAsync(mail)
Await .DisconnectAsync(True)
Threading.Thread.Sleep(5000) <<<<--
End With |
End Using |
Return True |
``` |
After adding a explicite sleep of about 5 seconds, the problem is gone.
Any explaination?
Thanks for helping.
With best regards
Gerhard
Just because you closed and cleaned up the socket on the local machine doesn't mean that the server has had a chance to close and cleanup the socket at the remote end.
I am trying to get a stock item quantity updated on a magento 2.1 site using REST API.
I am coding in VB.net but I get the error JSON response {"message": "Request does not match any route."}
Dim Access_Token = "XXXXXXXXXXXXX"
Try
Dim VATWebClient = New WebClient()
VATWebClient.Headers(HttpRequestHeader.Accept) = "application/json"
VATWebClient.Headers(HttpRequestHeader.ContentType) = "application/json"
VATWebClient.Headers(HttpRequestHeader.Authorization) = "Authorization Bearer " & Access_Token
Dim Response As String
Response = VATWebClient.UploadString("http://www.xxxxxx.com/rest/V1/products/xxxx/stockItems/1", "{""stockItem"":{""qty"":100}}")
Catch webEx As WebException
Dim errorMessage As String = webEx.Message
Dim errorStack As String = webEx.StackTrace
End Try
I have also tried to setup SoapUI just to test to make sure that I am calling it right and I get the same error.
I read somewhere that the webapi.xml must be updated with the API which is required I am really hoping that's not the case as the host/web developer is not very accessible!
UploadString will create a POST Request, as you can see form the API Docs, this API endpooint is PUT method only.
https://devdocs.magento.com/swagger/index_21.html#!/catalogInventoryStockRegistryV1/catalogInventoryStockRegistryV1UpdateStockItemBySkuPut
I'm not too sure how to change the method in visual basic, but I'm sure it's not too difficult.
This question is to validate the custom error handling implementation here or is there a better workaround possible?
Is there any other best possible way that you could suggest?
I am using Suave with Asp.Net core and kestrel server in F# to build microservices.
I want to add http status code and error message for specific server side errors for the client using the microservices' restful api's.
I have the following code.
Startup.fs code ==>
member this.Configure(app: IApplicationBuilder, env: IHostingEnvironment, loggerFactory: ILoggerFactory) =
app.UseSuaveErrorHandler(ConfigApp.ErrHandler) |> ignore
<TODO>
type ConfigApp () =
static member ErrHandler (ex:exn) (message:string) (httpContext:HttpContext) =
let logRepository =
log4net.LogManager.GetRepository(Assembly.GetEntryAssembly())
log4net.Config.XmlConfigurator.Configure(logRepository,
FileInfo("log4net.config")) |> ignore
FloLogger.debug "Exception= %s" ex.Message
FloLogger.debug "Exception= %s" ex.StackTrace
match ex.Message with
| x -> INTERNAL_ERROR ("Custom Error Handler: " + ex.Message) httpContext
InnerMethod fs file code excerpt
let fnGetManufacturerInfoByIdDAL (manufacturerID:string) =
try
FloLogger.debug "Inside fnGetManufacturerInfoByIdDAL method"
printfn "Inside fnGetManufacturerInfoByIdDAL method - %s" manufacturerID
use session = objSettings.OpenSession()
// Querying database
let manufacturerList = session.Load<Manufacturer>((manufacturerID))
manufacturerList.Etag <- session.Advanced.GetEtagFor(manufacturerList);
// disposing the opened db session
session.Dispose()
manufacturerList
with
| smilie Exception as ex -> FloLogger.debug "%s" ex.Message
FloLogger.debug "%s" ex.StackTrace
let strException = "{\"error occurrred...\":\"error..\"}" + ex.Message
failwith strException
So the exception raised by the code in the inner method file get's handled by the Suave error handler which sends the http status code and the exception message in the response as shown in the screenshot attached.
But the server errors available with Suave are very few and from them Internal_Error suits the code errors the best.
Currently i'm trying to post an image from an vb.net website to pinterest.
I got the key and access token trough the documented way.
nut now i'm trying to send the data to the server to create a pin but i get an 500 internal server error. is there something wrong with my request that caused it or is it all on their side.
Public Function SendMessage(url As String, json As String)
Try
Dim client As New RestClient(url)
Dim request As New RestRequest(Method.POST)
request.RequestFormat = DataFormat.Json
request.AddBody(json)
dim response = client.Execute(request)
Return response
Catch ex As exception
Status = ex
Return Nothing
End Try
End Function
The used URL https://api.pinterest.com/v1/pins/?access_token={mytoken}&fields=board%2Cnote%2Cimage%2Clink
and the json message
{
"board": "{board}",
"note": "test pin2",
"link": "{hyperlink}",
"image_url": "{image url}"
}
Response
{
"message": "'str' object has no attribute 'iteritems'",
"type": "http"
}
status: "Internal Server Error"
I hope someone can point out wat i'm doing wrong.
Thanks in advance
I’m writing a http module to work as a reverse proxy, i.e. receives a request from a browser, sends it on to the target site, receives a response and sends that back to the browser.
Its all working fine, except for a problem with forwarding cookies from the browser request to the target site on a Post. All headers and form data are correct on the outgoing request, but no cookies are included.
I’ve run fiddler on both the request from the browser to IIS and the outgoing httpwebrequest and proven this to be the case. Running the module in debug shows that the cookies are found in the request from the browser and successfully placed in the cookiecontainer of the httpwebrequest, but they just don’t appear in the actual request sent out.
If I hack (in debug) the outgoing request method to a Get, then they go, but they don’t go for a Post.
I’ve also tracked the request/response from a browser direct to the target site using Fiddler, and the request seems identical in all three cases (browser to target, browser to my IIS module, IIS module to target), except that the IIS module to target omits the cookies.
Here’s the code (VB.Net, and tried in 2.0 and 4.5):
' set up the request to the target
Dim reqTarget As System.Net.HttpWebRequest
reqTarget = CType(System.Net.HttpWebRequest.Create(strTargetURL & strTargetPath & qstring), System.Net.HttpWebRequest)
' copy relevant info, cookies etc from the application request to the target request
CopyAppRequest(application.Context.Request, reqTarget)
' send the request and get the response
Dim rspTarget As System.Net.HttpWebResponse = CType(reqTarget.GetResponse(), System.Net.HttpWebResponse)
Private Sub CopyAppRequest(ByRef reqApp As System.Web.HttpRequest, ByRef reqTarget As System.Net.HttpWebRequest)
' copy over the headers
For Each key As String In reqApp.Headers.AllKeys
Select Case key
Case "Host", "Connection", "Content-Length", "Accept-Encoding", "Expect", "Authorization", "If-Modified-Since"
' not sure if we need to process these
Case "Connection"
reqTarget.Connection = reqApp.Headers(key)
Case "Content-Type"
reqTarget.ContentType = reqApp.Headers(key)
Case "Accept"
reqTarget.Accept = reqApp.Headers(key)
Case "Referer"
reqTarget.Referer = reqApp.Headers(key)
Case "User-Agent"
reqTarget.UserAgent = reqApp.Headers(key)
Case "Cookie"
' do nothing, cookies are handled below..
Case Else
reqTarget.Headers.Add(key, reqApp.Headers(key)
End Select
Next
reqTarget.Method = reqApp.HttpMethod
reqTarget.AllowAutoRedirect = False
If reqTarget.Method = "POST" Then
reqTarget.ContentLength = reqApp.ContentLength
Dim datastream() As Byte = System.Text.Encoding.UTF8.GetBytes(reqApp.Form.ToString)
reqTarget.ContentLength = datastream.Length
Dim requestwriter As System.IO.Stream = reqTarget.GetRequestStream
requestwriter.Write(datastream, 0, datastream.Length)
requestwriter.Close()
requestwriter.Dispose()
End If
Dim CookieJar As New System.Net.CookieContainer
reqTarget.CookieContainer = CookieJar
For Each key As String In reqApp.Cookies.AllKeys
Dim tgtCookie As New System.Net.Cookie
With tgtCookie
.Name = reqApp.Cookies.Item(key).Name
.Value = reqApp.Cookies.Item(key).Value
.Domain = ".domain.com"
.Path = "/"
.Expires = DateAdd(DateInterval.Month, 1, System.DateTime.Now)
.HttpOnly = True
End With
CookieJar.Add(tgtCookie)
Next
End Sub
Note: the domain I’m trying to reach is in the form abc.domain.com (i.e. it’s a subdomain, and no www), the reason I’ve tried the .domain.com form is that is the form used in the cookies that are received in the response. I’ve also tried other combinations such as abc.domain.com, .abc.domain.com, etc. Also I’ve tried creating a Uri object and using that method to add the cookie into the cookiecontainer.
I’ve tried everything I can think of and can find on forums…. Anyone got any suggestions? I suspect I’ve missed something obvious!
Of course, any other comments on how the code above can be improved will be appreciated.
Thanks.
Ok, I found the issue...
I was using Fiddler to see what was going on with http, and Fiddler was correct. However, when I used Wireshark, I found that the http request was being sent earlier than I thought, and only on the Post.
It turned out that the requestwriter.write line caused the http request to be sent, not the GetResponse (as is the case with Get). So, anything I changed in the httpwebrequest after the requestwriter.write didn't get sent.
The fix - I just moved all the header and cookie set up above the requestwriter.write and it all worked.
How frustrating, but at least its fixed now :)
If anyone has any feedback on whether I've got something wrong that's causing this to happen, please let me know.