Unregistered SOAP Client 3.0 on Windows Server - asp.net

I've developed a Web Application (web site) using VS 2010 and VB.NET. I'm able to run the application successfully from VS. But when I Publish and upload it on my hosting server this error message occurs.
Retrieving the COM class factory for component with CLSID {7F017F97-9257-11D5-87EA-00B0D0BE6479} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
I've downloaded the SOAP toolkit 3.0 and imported it in my application reference. here is my code:
Imports MSSOAPLib30
Dim objSoapClient As New SoapClient30 '=== Create an instance of SoapClient
'=== Set Client Properties
objSoapClient.ClientProperty("ServerHTTPRequest") = True
'=== Retrieve KWMP web services WSDL
Call objSoapClient.mssoapinit("https://example.com/ReferencePayment?WSDL", "ReferencePayment")
'=== Set connection property to be over SSL
objSoapClient.ConnectorProperty("UseSSL") = False
'=== Now consume the web sevices according to KWMP Specification
Dim output As String = objSoapClient.verifyTransaction(RCode, "00105952-129251")
--Update--
except the method above, I was thinking of using POST web method to consume the SOAP XML.
here is the xml request generated by WCF Test Client:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" />
</s:Header>
<s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<q1:verifyTransaction xmlns:q1="urn:Foo">
<String_1 xsi:type="xsd:string">12345678901234567890</String_1>
<String_2 xsi:type="xsd:string">00109902-129251</String_2>
</q1:verifyTransaction>
</s:Body>
</s:Envelope>
and I have method to consume the SOAP XML which returns Internal Server Error 500 !!!!! You think which part is wrong ?!
Public Function ServiceCall(RefCode As String) As String
Dim resultXml As String
Dim wbrqst As WebRequest = WebRequest.Create("https://modern.enbank.net/ref-payment/ws/ReferencePayment?WSDL")
Dim httpreq As HttpWebRequest = DirectCast(wbrqst, HttpWebRequest)
httpreq.Method = "POST"
httpreq.ContentType = "Content-Type: text/xml; charset=utf-8"
httpreq.Headers.Add("SOAPAction", "https://modern.enbank.net/ref-payment/ws/ReferencePayment")
'httpreq.Headers.Add("<Action s:" + "ReferencePayment>")
httpreq.ProtocolVersion = HttpVersion.Version11
httpreq.Credentials = CredentialCache.DefaultCredentials
Dim requestStream As Stream = httpreq.GetRequestStream()
Dim streamWriter As New StreamWriter(requestStream, Encoding.ASCII)
Dim sb As New StringBuilder()
sb.Append("<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>")
sb.Append("<s:Body s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>")
sb.Append("<q1:verifyTransaction xmlns:q1='urn:Foo'>")
sb.Append("xml:xsd='http://www.w3.org/2001/XMLSchema'")
sb.Append("<verifyTransaction xmlns='urn:Foo'")
sb.Append("<String_1 xsi:type='xsd:string'>12345678901234567890</String_1>")
sb.Append("<String_2 xsi:type='xsd:String'>00109902-129251</String_2>")
sb.Append("</q1:verifyTransaction> </s:Body></s:Envelope>")
streamWriter.Write(sb.ToString())
streamWriter.Close()
Dim wr As HttpWebResponse = DirectCast(httpreq.GetResponse(), HttpWebResponse)
Dim srd As New StreamReader(wr.GetResponseStream())
resultXml = srd.ReadToEnd()
Return resultXml
End Function

There appears to be a problem with that tool, you may want to use the WCFTest Client, which should work with you soap message, thise can be found from within the VS2010 folder
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe
Just add the service you want to open, it should then create a client proxy for you on the fly.
Update:
You may want to use add web reference and create a webservice project as part of a VS project.
Hope this helps.
Cheers

Related

Uploading files to SharePoint OnPremise 2016 using .NET Core 5.0 and HttpWebRequest C#

SharePoint CSOM is not supported in .NET Core 5.0, so I'm trying to use HttpWebRequest to upload files to SharePoint 2016 on-premise.
This code sample shown here works in .NET 4.7, however it throws errors when run on .NET Core.
public async Task<string> UploadFile(string folderName, string fileName, byte[] file)
{
// Url to upload file
string resourceUrl = _sharePointUrl + $"/_api/web/GetFolderByServerRelativeUrl('/opportunity/{folderName}')/Files/add(url='{fileName}',overwrite=true)";
HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.Credentials = _credentials;
wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
// Get formdigest value from site
wreq.Headers.Add("X-RequestDigest", GetFormDigest());
wreq.Headers.Add("binaryStringRequestBody", "true");
wreq.Method = "POST";
wreq.Accept = "application/json; odata=verbose";
wreq.ContentLength = file.Length;
wreq.Timeout = 100000;
await wreq.GetRequestStream().WriteAsync(file, 0, file.Length);
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
return response.StatusDescription;
}
Errors are listed below. The errors are happening on the
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
line.
System.AggregateException: 'One or more errors occurred. (An error occurred while sending the request.)'
Inner Exception 1: WebException: An error occurred while sending the request.
Inner Exception 2: HttpRequestException: An error occurred while sending the request.
Inner Exception 3: IOException: The response ended prematurely.
What am I missing?
Does the HttpWebRequest in .NET Core work differently than the .NET framework version?
Do I need to use different headers or configure the request object differently?
Thanks in advance.

Google Drive authentication in VB.NET to download a file

My goal is to download a file from Google Drive using the Drive API v3 and VB.NET.
I set up my credentials in the Google console: Under "OAuth 2.0 client IDs" I put "http://localhost" in "Authorized redirect URIs" and in "Authorized JavaScript origins" and have my client secret file. I am on ASP.NET 4.0 using NuGet package Google.Apis.Drive.v3.
The error happens on line "credential = GoogleWebAuthorizationBroker.AuthorizeAsync". It pops up a new Chrome tab and says:
That’s an error.
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:9895/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/[MyClientID]?project=[MyProjectNumber]
However each time I get a different port number.
Public Function AuthenticateOauth() As DriveService
' Request authentication from a user using oAuth2
Dim clientSecretJson = "C:\WebApps\PeruvianGuineaPig\App_Data\client_secret.json"
Dim applicationName = "DriveApi"
Try
' Permissions
Dim scopes As String() = New String() {DriveService.Scope.DriveReadonly}
Dim credential As UserCredential
Using stream As New FileStream(clientSecretJson, FileMode.Open, FileAccess.Read)
Dim credPath As String
credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly.GetName.Name)
' Requesting Authentication
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user",
CancellationToken.None,
New FileDataStore(credPath, True)).Result
End Using
' Create Drive API service
Dim Service = New DriveService(New BaseClientService.Initializer() With
{.HttpClientInitializer = credential, .ApplicationName = applicationName})
Return Service
Catch ex As Exception
Return Nothing
End Try
End Function
I didn't realize I needed to open the project as a Web Site (and pick it from my list of Local IIS Sites) and not simply open the Project/Solution file. It now uses the port number I gave it in IIS when I'm debugging.
I have another issue now, but that's for another question...

Windows 10 Universal App - Package doesn't work normally as debug mode

public async Task<List<Tip>> GetTips()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://APIURL ");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = await request.GetResponseAsync();
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd();
List<Tip> tips = JsonConvert.DeserializeObject<List<Tip>>(result);
return tips;
}
I am working on a project which need to consume an enterprise Web API(Https) and display the data on Win 10 live tile, it’s an UWP application.
But I found it only works when I ran it in IDE(Visual Studio 2015 debug mode) .
When I created a package for this app and run it by powershell for installation, request.GetResponseAsync method throws exception “The login request was denied”.
I tried to check Enterprise Authentication and Private Networks(Client & Server) options in Package.appxmanifest. But there was no effect.
Any idea how to make it work normally? Thanks.

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

Getting 400 Bad Request erro calling java web service

I am connecting to a java web service from my asp.net app ,but I am getting a 400 Bad request exception.
I have added a web reference in my project and using that to connect in the code as follows :
client is the web service reference object.
NetworkCredential credentials = new NetworkCredential("", "");
client.Credentials = credentials;
client.PreAuthenticate = true;
client.RequestEncoding = Encoding.UTF8;
object response = client.getmethod(req);
I also tried putting in
client.UnsafeAuthenticatedConnectionSharing = true;
client.AllowAutoRedirect = true;
but it still does not work and gives me the same error. The request is working if i try from Soap-UI from my machine.
To Add, I am getting a ClientProtocol error in SoapUI also if i don't select authentication type as "PreEmptive". Is there a way to set this in asp.net.
Any thoughts would be appreciated.

Resources