Connection via REST API to Azure DevOps fails - vb.net

I am currently working on a REST API to be able to call a WCF service via it. Now I have the problem when I try to call up tasks via Azure DevOps using this method,
<OperationContract()>
<WebGet(UriTemplate:="/todos?user={sUser}&projectID={lProjektID}", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function GetTodos(Optional ByVal sUser As String = "%", Optional ByVal lProjektID As Long = Nothing) As List(Of ProjektToDo)
I get these exceptions after trying to connect to Azure Devops at this:
Dim creds As New VssBasicCredential(String.Empty, _DevOpsPAT)
Dim connection As VssConnection = New VssConnection(New Uri(My.Settings.TFSBasisUrlSSL), creds)
'Create instance of WorkItemTrackingHttpClient using VssConnection
Dim witClient As WorkItemTrackingHttpClient = connection.GetClient(Of WorkItemTrackingHttpClient) 'This connection fails !'
Dim queryHierarchyItems As List(Of QueryHierarchyItem) = witClient.GetQueriesAsync(Projekt,, 2).Result
"System.Net.Sockets.SocketException" in System.dll
"System.IO.IOException" in System.dll
"System.ObjectDisposedException" in System.dll
"System.Net.WebException" in System.dll
"System.Net.Http.HttpRequestException" in Microsoft.VisualStudio.Services.Common.dll
"System.Net.Http.HttpRequestException" in mscorlib.dll.
The InnerException of the ex.Message tells me "An existing connection was closed by the remote host" Message: "Unable to read data from the transfer connection".
I'm currently training in a new company and have no experience in the area of ​​Rest API and WCF Service, please help me I'm desperate about this task because I just don't know where to start.

Related

Access Denied issue when connecting to XERO using oAuth2.0

I am creating an application that will allow a user to send Invoices from a local database application to XERO.
Connection works fine when running on my machine at the office but when I port it to the clients terminal server I get this error.
System.Net.HttpListenerException (0x80004005): Access is denied
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at XeroConnectionTest.clsXeroAuth2.VB$StateMachine_6_oauth2.MoveNext() in Q:\XeroConnectionTest\XeroConnectionTest\clsXeroAuth2.vb:line 21
This is the code where it fails
Private callbackurl As String = "http://localhost:5000/signin/"
Public Async Function oauth2() As Task(Of Boolean)
Dim redirectUri As String = String.Format(callbackurl)
Dim listener = New HttpListener()
listener.Prefixes.Add(redirectUri)
Try
listener.Start()
stopListening = False
Catch hlex As HttpListenerException
'MsgBox(hlex.ToString)
Form1.TextBox1.Text = hlex.ToString
Return False
End Try
and the error occurs on listener.start() line.
Any help would be gratefully received
Thanks
Frostie

WCF Error - An error occurred while receiving the HTTP response to http://localhost:50750/*******.svc

I am receiving the following error while debugging.
An error occurred while receiving the HTTP response to http://localhost:50750/FIGService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Now I have seen many posts where people have had that error, I have cut my WCF down to absolute barebones and I am still getting the error, I am running the following:
Public Function TestXML(ByVal Username As String, ByVal Password As String, ByVal XML As String) As XmlDocument Implements FreshCloud.TestXML
Dim ReturnXMLDoc As New XmlDocument()
If ValidateLogin(Username, Password) <> False Then
ReturnString = "<FreshLead><Result><Message>Failed - XSD Validation</Message><DateTime>" & Date.Now.ToString & "</DateTime></Result></FreshLead>"
ReturnXMLDoc.LoadXml(ReturnString)
Return ReturnXMLDoc
End If
End Function
Don't worry about the uselessness of the code I literally just copy and pasted various bits to run a test, this is than ran with a simple test app with a button:
Dim client As FreshCloudClient = New FreshCloudClient()
Dim strXML = client.TestXML("ABC", "BS", "Doesn't Matter")
Dim strTest = strXML
client.Close()
I receive the error just returning the above, please any light that can be shed would be grateful this is a big project that I have had to sink my teeth into a Microsoft's vague error messages do not help a learner.
Cheers! :)
UPDATE
After digging through the logs for WCF I stumbled across this:
Type 'System.Xml.XmlDocument' is an invalid collection type since it does not have a valid Add method with parameter of type 'System.Object'.
Can anyone share with me why this exception would be thrown up by WCF?
Cheers.
UPDATE 2
OK so following Lerners advice I have now got the following:
Public Function TestXML(ByVal Username As String, ByVal Password As String, ByVal XML As String) As XElement Implements FreshCloud.TestXML
Dim ReturnXMLDoc
If ValidateLogin(Username, Password) <> False Then
ReturnString = "<FreshLead><Result><Message>Failed - XSD Validation</Message><DateTime>" & Date.Now.ToString & "</DateTime></Result></FreshLead>"
ReturnXMLDoc = XElement.Parse(ReturnString)
Return ReturnXMLDoc
End If
End Function
On my client side of have said to put the response to a variable and Console.WriteLine the variable and it just returned System.Object?
Surely this should return the XML as it shows in ReturnXMLDoc variable when I debug on the WCF side of things?
UPDATE 3
WORKING!
Lerner put me in the right ballpark and I just had to update the Service Definitions from within my 'Client' Application.
Cheers.
Return XElement instead of XDocument, XElement is IXmlSerializable.
var xml = XElement.Parse(ReturnString);
return xml;

System.IO.FileLoadException while using Google Calendar 3

I am using the following code to connect to Google Calendar 3.
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "101935195xxxxxx-jm6o24ifgbixxxxxxxxxxxx#developer.gserviceaccount.com".Trim()
scopes.Add("https://www.googleapis.com/auth/calendar")
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = myClientID, _ ' It is saved in the web config
.ClientSecret = ClientSecret _ ' It is saved in the web config
}
Dim flow As GoogleAuthorizationCodeFlow
Try
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes
})
Catch ex As Exception
lblerr.Text = ex.ToString
End Try
It throws:
System.TypeInitializationException: The type initializer for 'Google.Apis.Http.ConfigurableMessageHandler' threw an exception.
System.IO.FileLoadException: Could not load file or assembly 'System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
What am I doing wrong with this coding? Why am I not getting authenticated?
I have seen a similar error when using external libraries (e.g. DLL's) which are downloaded from the internet. Your post doesn't mention this, but I'll post here just in case this applies to you.
Make sure any external libraries used by your project are not blocked by Windows. You can do this by right-clicking the library file (e.g. the DLL) and going to Properties. At the bottom, if this applies, there will be a button to "Unblock". Click it and then try to run your project again.
Additional info and automation options can be found here: http://www.howtogeek.com/70012/what-causes-the-file-downloaded-from-the-internet-warning-and-how-can-i-easily-remove-it/

RetryPolicy.Retrying event not firing during Transient Error Handling for SQL Azure?

I've got website hosted in azure (as a web service) that is using sql azure as it's backend.
My error logs have been heavily populated with what looks to be transient network and sql connection errors.
As such I've implemented the Enterprise Library Transient Error Handling Block. In tests it would seem that its operating correctly.
The issue I'm encountering is that I would like to log instances where this retry logic is occurring. From the documentation RetryPolicy.Retrying looks to be the event I'm after but in tests it doesn't fire. There's plenty of examples in C# that follow the following pattern to fire this event:
var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy);
// Receive notifications about retries.
retryPolicy.Retrying += (sender, args) =>
{
// Log details of the retry.
var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
args.CurrentRetryCount, args.Delay, args.LastException);
Trace.WriteLine(msg, "Information");
};
I thought I'd adapted this correctly but in short, what's wrong with the code below?!
Private RetryManager As RetryManager
Private WithEvents RetryPolicy As RetryPolicy
Private Sub RetryPolicy_Retrying(ByVal sender As Object, ByVal args As RetryingEventArgs)
' Log details of the retry.
Dim msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}", args.CurrentRetryCount, args.Delay, args.LastException)
Trace.TraceInformation(msg)
End Sub
Private Sub SetupRetryPolicy()
'If its already set then lets not do it again
If RetryPolicy Is Nothing Then
RetryManager = EnterpriseLibraryContainer.Current.GetInstance(Of RetryManager)()
RetryPolicy = RetryManager.GetRetryPolicy(Of SqlAzureTransientErrorDetectionStrategy)("Exponential Backoff Retry Strategy")
' connect sub as handler to event when retry occurs
AddHandler RetryPolicy.Retrying, AddressOf RetryPolicy_Retrying
End If
End Sub
Public Sub ExecuteAndDoStuff(ByVal connString As String, ByVal cmdText As String)
SetupRetryPolicy()
'get a connection with retry
Using conn As New ReliableSqlConnection(connString, RetryPolicy, RetryPolicy)
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand
Try
cmd.CommandText = cmdText
' this might be overkill, do I need to pass the retry policy in again for the command?
Dim dr As SqlDataReader = cmd.ExecuteReaderWithRetry(RetryPolicy, RetryPolicy)
'... do something with this datareader
Catch ex As Exception
'log error
Trace.TraceError("Query failed to execute despite retry logic: " & ex.ToString)
'continue to throw the error (picked up higher up the chain)
Throw ex
End Try
End Using
End Using
End Sub
I'm totally new to at least half of what's going on in this block of code but before anyone thows a rtfm at me - I tried!
It's hard to tell if anything is wrong in your code; it could be that there are no transient errors being detected at all. How are you making the determination that there are transient errors? The first thing I would do is to make sure you have a repeatable way of creating a transient error.
The way I would setup the test is to have a 1GB database in Azure SQL Database, fill it up with data up until it has reached its storage limit, and then try to add more data (which will generate a transient error everytime).
There are two things to keep in mind with Azure SQL transient errors:
1) They are very hard to test because many of them depend on variables that are outside of your control; one of the easiest transient error to replicate is out of space (the suggestion above)
2) There are a few other types of errors that can be fired, such as router swicthing conditions in Azure, that are not considered transient; for example IOException errors are not captured by the SQL Transient Strategy. As a result, you either need to account for those kinds of errors seperately, or customize the strategy to include these errors. Your catch block should trap these errors in your current implementation.

Accessing Files On Server By Specifying Credentials

Our company has a share point document server where the UNC looks something like this: \\theserver.ourdomain.com\rootdirectory
Currently this drive is mapped to the Z:\ on my local computer. To access the Z:\ you have to specify (each time you login) credentials (in our case is it our username and password we logged on with) to access the folders and files in the rootdirectory.
I am in a situation where I need to copy files onto the share point server. I want to be able to copy files onto the server without using the mapped network drive (not have to specify Z:\ in the path). How can I supply credentials so that I can perform basic IO functions like GetDirectories(), GetFiles(), IO.File.Copy() etc...?
I have looked into the following things but was unsuccessful in making them work:
LogonUser API call by specifying plain text user name and password, then taking the token from that call and impersonating that user using a new instance of the WindowsIdentity class. Was able to get the token, but the impersonation didn't seem to work. Kept getting access denied errors.
CredUIPromptForCredentials/CredUIPromptForWindowsCredentials API calls, but I realize these are just for a fancy Windows UI where you can enter your credentials into and actually don't do anything.
<DllImport("advapi32.dll", SetLastError:=True)> _
Private Shared Function LogonUser(lpszUsername As String, lpszDomain As String, _
lpszPassword As String, dwLogonType As Integer, _
dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function CloseHandle(handle As IntPtr) As Boolean
End Function
'// logon types
Public Const LOGON32_LOGON_NETWORK As Integer = 3
Public Const LOGON32_LOGON_NEW_CREDENTIALS As Integer = 9
'// logon providers
Public Const LOGON32_PROVIDER_WINNT50 As Integer = 3
Public Const LOGON32_PROVIDER_WINNT40 As Integer = 2
Public Const LOGON32_PROVIDER_WINNT35 As Integer = 1
Public Const LOGON32_PROVIDER_DEFAULT As Integer = 0
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim token = IntPtr.Zero
Dim success = LogonUser("username", "domain", "password", _
LOGON32_LOGON_NEW_CREDENTIALS, _
LOGON32_PROVIDER_DEFAULT, token)
If Not success Then
Me.RaiseLastWin32Error()
End If
Using identity = New WindowsIdentity(token)
Using impersonated = identity.Impersonate()
Try
Dim info = New DirectoryInfo("\\theserver.ourdomain.com\rootdirectory\")
Dim files = info.GetDirectories()
Catch ex As Exception
Finally
impersonated.Undo()
End Try
If Not CloseHandle(token) Then
Me.RaiseLastWin32Error()
End If
End Using
End Using
End Sub
Private Sub RaiseLastWin32Error()
Dim hr = Marshal.GetLastWin32Error()
Dim ex = Marshal.GetExceptionForHR(hr)
If ex IsNot Nothing Then
Throw ex
End If
Throw New SystemException(String.Format("Call resulted in error code {0}", hr))
End Sub
This isn't a direct answer to your question as it is a wildly different approach. If it doesn't work for your situation sorry to bother, but have you considered using the SharePoint web services to load the files and retrieve information?
I suggest this approach for a few reasons:
The issue you are experiencing may be occurring because SharePoint implements WebDav which might not be 100% compatible with System.IO. I'm not an expert on the innards here, I don't know about the compatibility for sure, but it seems plausible.
The UNC location you have could easily be massaged into a URL that the web service requires.
You can set the credentials directly on the proxy and might have an easier time. (though we make these calls from another web server and so the app pool credentials in the example are good enough for us)
Here's some sanitized and simplified code just in case:
// location takes the form http://server.name.com/site/library/folder/document.ext
public string UploadDocument(string location, byte[] fileContents)
{
var result = String.empty;
var destination = new string[1];
destination[0] = location;
var fileName = Path.GetFileName(location);
var fieldInfo = new FieldInformation[0];
CopyResult[] copyResults;
_copyService.Url = "http://server.name.com/_vti_bin/Copy.asmx";
_copyService.Credentials = CredentialCache.DefaultCredentials;
_copyService.CopyIntoItems(fileName, destination, fieldInfo, fileContents, out copyResults);
var errorCode = copyResults[0].ErrorCode;
if (errorCode != CopyErrorCode.Success)
{
if (errorCode == CopyErrorCode.DestinationCheckedOut)
result = "File is currently checked out. Please try again later.";
else
result = "Error uploading content.";
}
return result;
}
_copyService is a dependency we inject where the run-time implementation is the proxy generated by Visual Studio tools from the Copy.asmx SharePoint web service.
You can also get folder contents and document metadata using the Lists.asmx web service. The biggest downsides to this approach are that querying the information requires some CAML knowledge and processing the results is not as easy. But the services are reasonably documented on MSDN and the operations are all working in our application.
Well, I was able to solve this with the help of the WNetAddConnection2 API. This API is used for mapping network drives as well, however you can call this method without specifying a drive letter so that it just adds the connection.
Say for example you had drive X: mapped to \\server\share
Lets also say that it requires username & password to access the files on the server. When you restart Windows 7, you will probably lose that connection (you will get a notification saying that Windows was unable to reconnect some of the network drives). If you have an application that requires access to that server's files and you attempt to access it without supplying your credentials you will get access denied exceptions. If you do a successful call to WNetAddConnection2, not only will it fix your unmapped network drive, you will also be able to access the files/directories via the System.IO namespace.
We use Sharepoint and this worked for me. Thanks to the other guys for replying also.