How to pass data to a WebApi Controller from a console application? - asp.net

Using this code I am not able to post data to an api (asp.net MVC latest version).
What could be the problem?
Should I set specific headers?
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("DeviceId", "devicetest")
reqparm.Add("Message", "messagetest")
Dim responsebytes = client.UploadValues("http://xxx.xxx.com/api/notification", "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

Related

How to return a File using Open XML in ASP.NET and VB.NET

I have a legacy ASP.NET 3.5 (NOT ASP.NET MVC )application using VB.NET. I want to download an excel spreadsheet when a user clicks on a button.I am using OpenXML library. I have used the same feature in ASP.NET MVC where you could return a file using OpenXML like this:-
public FileContentResult GetCollectionsExcel()
{
var collections = CurrentBroker.Collections;
var model = new FinancialCollectionsModel(collections);
var package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("Collections");
return File(package.GetAsByteArray(),"application/vnd.openxmlformatsofficedocument.spreadsheet.sheet", "Collections.xlsx");
}
What would be it's equivalent in traditional ASP.NET and VB.NET ? What should be the return type of the method as we don't have a FileContentResult in ASP.NET.
Access the response directly, write the data to the response stream and set the necessary headers
'...code removed for brevity
Dim response = HttpContext.Current.Response
response.ContentType = "application/vnd.openxmlformatsofficedocument.spreadsheet.sheet"
response.AppendHeader("Content-Disposition", "attachment; filename=""Collections.xlsx""")
response.BinaryWrite(package.GetAsByteArray())

Basic Authentication with asmx web service

I'm trying to implement Basic Authorization for an ASMXweb service. I created the client as a service reference in VS2015. I'm using code in Asmx web service basic authentication as an example.
I'm entering login info in ClientCredentials as below
Dim svc As New WebServiceSoapClient()
svc.ClientCredentials.UserName.UserName = "userId"
svc.ClientCredentials.UserName.Password = "i2awTieS0mdO"
My problem is that in the Authorization HttpModule in the web service, these credentials are not being passed to module. Is there an alternate way to do this?
I found the parts answer at How to add HTTP Header to SOAP Client. I had to combine a couple of answers on that page to get it to work.
Dim svc As New WebServiceSoapClient()
Dim responseService As SoapResponseObject
Using (new OperationContextScope(svc.InnerChannel))
Dim auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("userId:i2awTieS0mdO"))
Dim requestMessage = New HttpRequestMessageProperty()
requestMessage.Headers("Authorization") = auth
OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = requestMessage
dim aMessageHeader = MessageHeader.CreateHeader("Authorization", "http://tempuri.org", auth)
OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader)
responseService = svc.ListDistricts(requestService)
End Using
One key thing to be aware of is that the soap client call has to be inside the Using statement. In the above code, this is the next to last line.

How to get the binding address from a WSDL file

I generated a proxy class given a URL to a WSDL.
I need to let the end-user change the service's URL to his specific URL, like this:
ServiceProxy.Url = [URL set by end-user];
The issue is that this URL should not point to the WSDL, it should be the binding address which is found within the WSDL (wsdl:service -> wsdl:port -> wsdl:address) (this is a SAP web service, I understand that is why I must use the binding address).
I am thinking of using the XDocument class to get that value, but I am wondering if there is any "built-in" functionality in WCF or web services to get the binding address. Thank you.
I did a small function in VB.NET (sorry!) based on code at Parse Complex WSDL Parameter Information . Hope it helps.
Public Function GetURLFromWSDL(ByVal wsdl As String) As String
Dim request As HttpWebRequest = WebRequest.Create(wsdl)
request.ContentType = "text/xml;charset=""utf-8"""
request.Method = "GET"
request.Accept = "text/xml"
Using response As WebResponse = request.GetResponse()
Using stream As Stream = response.GetResponseStream()
Dim service As ServiceDescription = ServiceDescription.Read(stream)
Dim binding As SoapAddressBinding = service.Services(0).Ports(0).Extensions(0)
Return binding.Location
End Using
End Using
End Function

Session state lost after HttpWebRequest within AJAX post

I have a bit of strange behaviour in an asp.net web application that involves the session state being lost.
Process
A user logs into the application and the session is set. They then fill out 1 field, and the application then does an AJAX POST to a .asmx web service. Within the web service, I am using a HttpWebRequest to grab data from another server.
This data is then output to the browser.
A few more fields are then filled in, and the data is then again Post to the same web service via an AJAX POST.
Problem
Straight after the HttpWebRequest, I grab the username from a session variable. This works.
On the next AJAX request however, the session no longer exists.
While testing this, I removed the stage at which the HttpWebRequest is called and my session is never lost. So for some reason, the session is removed AFTER my first AJAX POST and before the second AJAX POST only if I am running the HttpWebRequest code.
Code
I am not doing anything fancy in the code. Just doing a simple jQuery AJAX Post
$.ajax({
url: method,
data: params,
type: "POST",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) {
// handle data
},
error: function(xhr,status,error) { }
});
Creating a System.Net.HttpWebRequest and then getting the System.Net.HttpWebResponse out of that.
Then reading a session variable dim username as string = Session(_SESSION_USERNAME).ToString()
I have never noticed this behaviour before when using HttpWebRequest before (not using any AJAX though)
Function Backfill(value As String) As Details
Dim details As Details = Nothing
Dim appSettings As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Dim url As String = appSettings.Settings.BackfillUrl
Dim username As String = appSettings.Settings.BackfillUser
Dim password As String = appSettings.Settings.BackfillPass
Dim expParameters As String = ""
Dim xml As XmlDocument = Nothing
Dim xmlHttp As XMLHTTP = Nothing
Dim nodeList As XmlNodeList = Nothing
Dim node As XmlNode = Nothing
Dim response As String = ""
Dim success As String = ""
'
' REMOVED TO HIDE INFO
expParameters = "<PARAMETERS>" & _
"</PARAMETERS>"
Try
xmlHttp = New XMLHTTP()
xmlHttp.open("POST", url)
xmlHttp.Send(expParameters)
response = xmlHttp.responseText()
xml = New XmlDocument
xml.LoadXml(response)
SaveExperianFile(xml, value)
nodeList = xml.DocumentElement.ChildNodes
node = nodeList.Item(0)
success = node.Attributes.GetNamedItem("success").Value.ToString.Trim
If success.ToLower.Trim = "y" Then
details = SetDetails(xml)
End If
Catch ex As Exception
Finally
If Not xmlHttp Is Nothing Then
xmlHttp.Dispose()
xmlHttp = Nothing
End If
End Try
Return details
End Function
edit
The XMLHTTP Class code can be seen here http://codepaste.net/ymnqsf
edit
Seems as though something strange is happening when I am saving the XMLDocument to my file system.
Private Sub SaveExperianFile(xml As XmlDocument, value As String)
Dim appConfig As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Try
xml.Save(HttpContext.Current.Server.MapPath(appConfig.Settings.SavePath & value & "_backfill.xml"))
Catch ex As Exception
End Try
End Sub
If I don't call this method, then the session is always set.
Question
Do you know what is causing this behaviour?
Can you check if you just loose the session or the whole application is restarted. If you are saving the XML in the virtual directory / web application folder then it might case web application to restart. If many dozen files were added in short succession to each other, that would be a case to restart the App Pool.
just a hunch, but maybe you need to maintain cookies across HttpWebRequests.
have a look at this question for more help.
Http web request doesn't maintaining session

Loading a document in XSLT using BASIC authentication in ASP.net

For development purposes we have a site setup with BASIC authentication in IIS7. One aspect of the site is that it does a lot transformations using XSLT. However this is causing authentication problems when loading documents in XSLT like this:
<xsl:with-param
name="value"
select="document('/mod_cms/xml/fixed/phaedrus_object_menu_display.xml')
/menuDisplay/option[value=$pagingValue]/name"/>
I get the error:
The remote server returned an error:
(401) Unauthorized.
Looking on the web for solutions, I have come across suggestions to use Credentials, eg:
Dim sw As New StringWriter()
Dim xslArg As New XsltArgumentList()
Dim xslt As New XslCompiledTransform()
Dim settings As New XsltSettings
settings.EnableDocumentFunction = True
Dim resolver As New XmlUrlResolver
Dim xml As New XmlDocument
xml.LoadXml(sXml)
Dim myCache As New System.Net.CredentialCache()
myCache.Add(New Uri("http://URL.net/"), "Basic", New System.Net.NetworkCredential("???", "???"))
myCache.Add(New Uri("http://URL.net/mod_cms/xml/fixed/"), "Basic", New System.Net.NetworkCredential("???", "???"))
resolver.Credentials = myCache '
xslt.Load(sXsl, settings, resolver)
xslt.Transform(xml, xslArg, sw)
But this doesn't seem to work.
Has someone else had this problem.
Thanks in advance for any help.
Try using an XmlUrlResolver object.

Resources