How to change web service url dynamically - vb.net

I have one web service reference in my project but it has two url one is live and second one is test,how to switch between these url dynamically in vb.net
http://api.test/test/SOAP.wsdl
http://api.live/live/SOAP.wsdl
'LOGPOINT:
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Start fnHOTELSPROSearchExecute()", "fnHOTELSPROSearchExecute")
Dim objsoap As New b2bHotelSOAPService()
Dim getres As New getAvailableHotelResponse()
QLSearchXML = xmlData
objsoap.Timeout = 20000
objsoap.Url = "http://api.live/live/SOAP.wsdl"
'objsoap.Timeout = TIMEOUT
getres = objsoap.getAvailableHotel(HOTELSPRO_APIKEY.Trim(), strDestinationId, dtmCheckIn, dtmCheckOut, strCurrencyCode, "UK", True, fngetpax(xmlData), getfilter())
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Start DeSerializing the XML Output", "fnHOTELSPROSearchExecute")
lHOTELSPROReturn = fnCustomSerializeObject(GetType(getAvailableHotelResponse), getres)
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "End DeSerializing the XML Output", "fnHOTELSPROSearchExecute")
lTempDOM.LoadXml(lHOTELSPROReturn)
Return lTempDOM
Catch ex As Exception
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.ERROR, ASSEMBLY_ID, "Catch Block Error:" + ex.ToString(), "fnCreateHOTELSPROSearchRequest")
Finally
'LOGPOINT:
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "Response From HotelsPro--->" & lHOTELSPROReturn, "fnHOTELSPROSearchExecute")
Call mobjLogWrite.prWriteLogEntry(clsLogWriter.enuLogEntryType.INFORMATION, ASSEMBLY_ID, "END Finally Block fnHOTELSPROSearchExecute()", "fnHOTELSPROSearchExecute")
End Try
the error response is returned
"I have one web service reference in my project but it has two url one is live and second one is test,how to switch between these url dynamically in vb.net"

Dynamically based on what, exactly?
Assuming you mean based on where the app is running, i.e. Test or Live, how about:
EDIT : Just saw it was meant to be in VB.Net
Dim MyService as String
If HttpContext.Current.Server.MachineName.ToString() = "LIVESERVER" Then
MyService = "http://api.live/live/SOAP.wsdl"
Else
MyService = "http://api.live/test/SOAP.wsdl"
End If
And change
objsoap.Url = "http://api.live/live/SOAP.wsdl"
to
objsoap.Url = MyService

If your Webservice is set to Dynamic, the URL is store in the app.config settings. To make this easier to change at run time (the app.config is readonly unless run with admin privileges), go to the project Settings and change the webservice setting from application scope to user scope.
Now you can change the webservice URL at any time in code using the my.settings.yourwebserviceurl... = "newwebserviceurl"
Next time you call the webservice, it will be from the new location. However, you will need to ensure both webservice call contain an indentical, or at least compatible webservice.

Related

Custom Post function to upload a file in Self Hosted REST API

I have written a VB.Net Visual basic console application for Self hosting a custom file upload service to be consumed by an application. Concept being the end user uses the application to generate data, when completed the file is uploaded to our server without user intervention. I have complete control over both applications. The problem is I can't figure out the POST Upload signature that can accept several params, including the file or how to actually receive the file. The User application is in beta now, testing all other functionality excluding the "Send File" sub's. I've never seen a file larger then 180 KB; I plan on accepting files sizes up to 1 MB. This lets me place some limitations (and filters) to help avoid abuse of the service.
I'm using NuGet packages webapi.client (4.0.30506), webapi.selfhost (4.0.3056) (and their associated required packages) and newtonsoft.json (4.5.11) and PostMan to test/debug the process. I'm using Visual Studio 2019 (Fully patched and up to date). All of the examples and google research point only to C# (not my language of choice), or are for hosted solutions like IIS.
In Postman, the only place where filenames are accepted are in the body, form-data. So, there is where I set up my key/value pairs with matching (including case and order) the params as defined in the FileULRequest class.
Everything that I've tried returns either
'500 internal server error'
or
"Message": "No HTTP resource was found that matches the request URI 'http://10.0.1.102:21212/file/upload/'."
The class object of the request looks like this:
Public Class FileULRequest
Public Property EncToken As String 'Holds an encrypted token for authorization
Public Property Filename As String 'Holds a recommended file name
Public Property AppID As String 'Holds the client/app ID for simpler server actions
Public Property File As Byte() 'Not sure if this is the right type/ should be the encrypted file contents.
End Class
The POST function signature currently looks like this:
Imports System.Web.Http
Namespace Controllers
Public Class FileController
Inherits ApiController
Public Function PostUpload(<FromBody()> ByVal ObjRequest As FileULRequest) As String
Return ""
End Function
End Class
End Namespace
In the Sub Main I have: (note, this is cleaned out)
Sub Main()
API_URL = Dns.GetHostByName(Dns.GetHostName()).AddressList(0).ToString()
Dim ThisConfig As New HttpSelfHostConfiguration("HTTP://" & API_URL & ":" & API_PORT)
ThisConfig.Routes.MapHttpRoute(name:="FileUpload", routeTemplate:="{controller}/{ObjRequest}", defaults:=New With {.id = RouteParameter.Optional})
ThisConfig.MaxConcurrentRequests = API_MaxCon
Dim Config As HttpSelfHostConfiguration = ThisConfig
Using Webserver As New HttpSelfHostServer(Config)
Try
Webserver.OpenAsync().Wait() 'Start the web server
Console.WriteLine("Listening at: " & API_URL & ":" & API_PORT) 'use the URL & port defined
Console.WriteLine("Enter to end")
Catch ex As Exception
Console.WriteLine("Error:{0}", ex.Message.ToString)
Console.WriteLine("Enter to end")
Console.ReadLine()
End
End Try
Dim Cmd As String = UCase(Console.ReadLine())
End
End Using
End Sub
API_Port and API_MaxCon are properties stored in the Appsettings.
What I'm trying to do is set the FileULRequest object params, post this to the service, confirm & validate the data and, if successful, save the file onto a network share. I've tried a large number of different combinations and nothing seems to get close; I cant get inside the Post event in the debugger to figure out or test anything.

How to new a new access token from a refresh token using vb.net?

I don't know if you can help me understand the right way forward with this issue. I need to provide a little bit of background first.
I have a VB.Net Console Utility that uses the Google V3 Calendar API. This utility has the following process to authenticate:
Private Function DoAuthentication(ByRef rStrToken As String, ByRef rParameters As OAuth2Parameters) As Boolean
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
'm_Scopes.Add(CalendarService.Scope.Calendar)
m_Scopes.Add("https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/")
Try
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("PublicTalkSoftware.Calendar.Application")).Result()
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "~~~~~~~~~~"
}
m_Service = New CalendarService(initializer)
rStrToken = credential.Token.AccessToken.ToString()
rParameters.AccessToken = credential.Token.AccessToken
rParameters.RefreshToken = credential.Token.RefreshToken
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
Return False
End Try
Return True
End Function
This part of the application process works fine. The data store file gets created and once the user has authenticated it all seems to just work find from there on. The user will be able to update the calendar without any further authenticating on there part.
Now, I also have a part of my MFC (the main application) project that sends emails for the user. This uses the following CkMainManW library.
For the most part that works too. If the user has correctly set up their credentials it is fine. However, if they are using GMail, then I do things slightly differently. This is to avoid the need to have the "Allow third party apps" option to be ticked in the Google account.
So, for GMail users, we send emails like this:
mailman.put_SmtpUsername(strUsername);
mailman.put_OAuth2AccessToken(strGoogleToken);
As you can see, I use the OAuth2AccessToken. This actual value passed is the credential.Token.AccessToken.ToString() value stored from when the user authenticated. Now, I have since understood that this actual token only lasts for one hour. This would explain why some users have to repeatedly run my calendar authentication again to get a new access token.
Clearly, when I do the calendar authentication which uses the data store file, it does something under the hood the avoid the user being asked all the time to authenticate.
Now, I have read this tutorial about using the Chilkat Library for this. I notice now that in the sample code it has a comment:
// Now that we have the access token, it may be used to send as many emails as desired
// while it remains valid. Once the access token expires, a new access token should be
// retrieved and used.
So, with all the background, how do I resolve my issue? So I have a data store file that contains the original access token from when they authorised and a refresh token. This file was created by the VB.Net command line module.
By the sounds of it, the Chilkat routine needs an access token that is valid. So, what is the right way for me to get an updated access token from the refresh token, so that when I send emails it won't fail after an hour?
Update
I am getting myself confused. I changed my code so that it called the DoAuthentification call above to get the refresh token and access token. But I am finding that the actual data store file is not getting revised. The text file is not being revised.
I have to revoke access and then do the authentication to get the data store file revised. And it is only once it has been revised that the access token will work for sending emails.
I think I have found the solution. I saw this answer:
https://stackoverflow.com/a/33813994/2287576
Based on the answer I added this method:
Private Function RefreshAuthentication(ByRef rStrAccessToken As String, ByRef rStrRefreshToken As String) As Boolean
Dim parameters As New OAuth2Parameters
With parameters
.ClientId = m_strClientID
.ClientSecret = m_strClientSecret
.AccessToken = rStrAccessToken ' Needed?
.RefreshToken = rStrRefreshToken
.AccessType = "offline"
.TokenType = "refresh"
.Scope = "https://www.googleapis.com/auth/calendar https://www.google.com/m8/feeds/ https://mail.google.com/"
End With
Try
Google.GData.Client.OAuthUtil.RefreshAccessToken(parameters)
rStrAccessToken = parameters.AccessToken
rStrRefreshToken = parameters.RefreshToken
RefreshAuthentication = True
Catch ex As Exception
RefreshAuthentication = False
End Try
End Function
I am not sure if I need to pass in the existing access token or not before refreshing. But either way, the tokens get updated and I can proceed with sending emails.
FYI, in the end it became apparent that I did not need any bespoke Refresh at all because the system manages it for you under the hood.
Private Async Function DoAuthenticationAsync() As Task(Of Boolean)
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
Try
credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("xxx.Calendar.Application"))
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "yy"
}
m_Service = New CalendarService(initializer)
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
' Can we isolate that as the exception?
m_logger.Error(ex, "DoAuthenticationAsync")
Return False
End Try
Return True
End Function
I have not required any bespoke Refresh of tokens for a long time now.

How to get the loading time of a web page in Windows Service Application using HttpWebRequest

I'm looking for code that will help me get the loading time of a web page without Using WebBrowser() in a Windows Service Application.
I run through different methods, but I don't quite get it.
Please help me solve this problem.
This function should do the trick:
Public Function WebpageResponseTime(ByVal URL As String) As TimeSpan
Dim sw As New System.Diagnostics.Stopwatch
sw.Start()
Dim wRequest As WebRequest = HttpWebRequest.Create(URL)
Using httpResponse As HttpWebResponse = DirectCast(wRequest.GetResponse(), HttpWebResponse)
If httpResponse.StatusCode = HttpStatusCode.OK Then
sw.Stop()
Return sw.Elapsed
End If
End Using
End Function
This will only take the downloading of the source code into account. If you want to calculate how long time it takes to download the source code AND render the page you'd have to use the WebBrowser class.
How it works:
The function declares and starts a Stopwatch which will be used for calculating how long the operation took, then it creates a web request to the specified URL. It downloads the entire page's source code (via the HttpWebResponse) and after that checks the response's StatusCode.
StatusCode.OK (which is HTTP status code 200) means that the request succeeded and that the requested information (the web page's source code) is in the response, but as we're not gonna use the source code for anything we let the response get disposed later by the Using/End Using block.
And lastly the function stops the Stopwatch and returns the elapsed time (how long it took to download the web page's source) to you.
Example use:
Dim PageLoadTime As TimeSpan = WebpageResponseTime("http://www.microsoft.com/")
MessageBox.Show("Response took: " & PageLoadTime.ToString())

twilio nuget package not sending SMS message in vb.net

Does the twilio asp.net helper library package NOT work in vb.net? I can get it to work in c# web app but not vb.net web app.
In a vb.net web application project the following code doesnt send an sms message and when stepping through with the debugger, errs on the send message line and brings up a file dialog asking for access to core.cs. The twilio library's were installed via nuget.
Public Shared Sub SendAuthCodeViaSms(ByVal number As String)
Dim twilioAccountInfo As Dictionary(Of String, String) = XmlParse.GetAccountInfoFromXmlFile("twilio")
Dim accountSid As String = twilioAccountInfo("username")
Dim authToken As String = twilioAccountInfo("password")
If (Not String.IsNullOrEmpty(accountSid) AndAlso Not String.IsNullOrEmpty(authToken)) Then
Dim client = New TwilioRestClient(accountSid, authToken)
client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
Else
'log error and alert developer
End If
End Sub
But in a C# web API project the same code sends the message as expected.
protected void Page_Load(object sender, EventArgs e)
{
const string AccountSid = "mysid";
const string AuthToken = "mytoken";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage(TwilioSendNumber,ToNumber,"text message from twilio");
}
and all the sid's and tokens and phone number formats are correct, otherwise the c# one wouldnt send and I wouldnt get to the client.SendMessage part of vb.net version (client.SendSMSMessage produces the same result)
Twilio evangelist here.
I tried our your code by creating a simple VB console app and it worked for me.
The only thing I can think of is that either you are not getting your Twilio credentials correctly when parsing the XML, or the phone number you are passing into the function is not formatted correctly.
I'd suggest putting the result of call to SendMessage() into a variable and checking to see if RestException property is null:
Dim result = client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
If (Not IsNothing(result.RestException)) Then
' Something bad happened
Endif
If Twilio returns a status code greater than 400, then that will show up as an exception in the RestException property and will give you a clue as to whats going on.
If that does not work, you can always break out a tool like Fiddler to watch and see if the library is making the property HTTP request and Twilio is returning the proper result.
Hope that helps.

WCF Service Method - Refactoring for Unit Test and Mocking

I've a WCF service with the following method:
Public Function ScheduleEmail(ByVal request As ScheduleEmailRequest) As ScheduleEmailResponse _
Implements EmailProtocol.ISchedulingService.ScheduleEmail
Try
If Not Email.IsValidEmailAddress(request.EmailAddress) Then
EmailSchedulerTrace.Source.WriteError(String.Format("Email with template '{0}' was not sent to '{1}' because it the address is invalid.", request.EmailName, request.EmailAddress))
Else
Dim mgr As New JobManager
Dim job As New EmailJob
Dim suppression As New SuppressionManager
Dim emailItem As Email = Email.GetEmailByName(request.EmailName)
If suppression.CheckSuppresion(emailItem, request.EmailAddress) Then
job.JobGuid = Guid.NewGuid
job.EmailAddress = request.EmailAddress
job.EmailGuid = emailItem.ID
job.ScheduledSendTime = request.ScheduledTime
job.CustomAttributes = request.CustomAttributes
job.ConsumerID = Email.GetConsumerId(request.CustomAttributes)
mgr.ScheduleJob(job)
Else
EmailSchedulerTrace.Source.WriteWarning(String.Format("Email with template '{0}' was not sent to '{1}' because it was suppressed.", request.EmailName, request.EmailAddress))
End If
End If
Catch ex As Exception
EmailSchedulerTrace.Source.WriteError(ex)
Throw
End Try
Return New ScheduleEmailResponse
End Function
I need to write Unit Test for this Method. Please help me out with
Do i need to change anything in my method?
What should I mock?
Your help is greatly appreciated. Thanks in advance.
Regards,
Sachin
You need to be able to swap out any 'services' (classes that you new up in a method or fields in the class) which connect to other systems (database, email server etc) so you need to create interfaces for the classes and inject the correct implementation at runtime and in your unit test, you can create mock or fake implementations for testing purposes.
A good start would be to define an interface for:
JobManager
EmailSchedulerTrace
SuppressionManager
You also might need to move the functionality of your static methods on Email
GetEmailByName
GetConsumerId
if they encapsulate database access or any other service which you cannot isolate.