I am currently working with the Braintree API to try and upload a database of users as customers to their server using their gateway functions. Right now I can create a customer through our C# code.
But any time I try and call the request a second time when we get to the next stage of the loop I get an unhandled web exception on this line :
Result<Customer> result = gateway.Customer.Create(request);
An unhandled exception of type 'System.Net.WebException' occurred in Braintree-2.59.0.dll
Additional information: The request was aborted: Could not create SSL/TLS secure channel.
I've changed the code so that we are setting up our gateway connection each time inside our foreach loop but still it errors out. We speculated that we might need to tear down the connection and reinitialize but I can't find any documentation regarding this.
Any ideas?
EDIT: Here is a test case that reproduces the error, you will need to have a sandbox account with your own MerchantId, PublicKey, and PrivateKey to test. I've also already tested creating customers who have the identical Company name and that works fine, Braintree will still create a new account with a unique ID for me so that isn't the issue.
using Braintree;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace BraintreeFailExample
{
class Program
{
static void Main(string[] args)
{
string companyName = "Test Company";
for (int i = 0; i < 3; i++)
{
// Initialization information (Replace with AppConfig settings)
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "Insert Sandbox MerchantId here",
PublicKey = "Insert Sandbox PublicKey here",
PrivateKey = "Insert Sandbox PrivateKey here"
};
// setup data for a customer request object
var request = new CustomerRequest
{
Company = companyName
};
// send the request to the Braintree gateway
// Braintree doesn't care about duplicate company requests for new customer
Result<Customer> result = gateway.Customer.Create(request);
}
}
}
}
I was able to resolve this issue. It turns out we had firewall issues that were preventing us from receiving further responses after the first.
Related
I need to connect to EWS. I am using Microsoft.Exchange.WebServices.NETStandard NuGet package for that. On the Windows machine everything is ok, but on Mac OS I'm getting the error "The remote server returned an error: (401) Unauthorized." Also, if I use just Microsoft.Exchange.WebServices it works fine, but whole my project is based on .Net Core. Maybe, somebody has encountered this problem.
using System;
using System.Linq;
using Microsoft.Exchange.WebServices.Data;
namespace testExchange
{
class Program
{
static void Main(string[] args)
{
var exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP2, TimeZoneInfo.Utc);
string userLogin = "userLogin";
string userPass = "userPassword";
string exchangeDomain = "icx";
string userEmail = "userEmail#domain.com";
string webmail = "https://domain/ews/Exchange.asmx";
exchangeService.Credentials = new WebCredentials(userLogin, userPass, exchangeDomain);
exchangeService.Url = new Uri(webmail);
string name = exchangeService.ResolveName(userEmail, ResolveNameSearchLocation.DirectoryOnly, true).Result.First().Contact.DisplayName;
Console.WriteLine(name);
}
}
}
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
It helped. Just add this.
Thanks so much to Ahh Bui
Post where I found the answer
My teammate uses the above code in C# (.NET) to extract email details from his inbox. If you notice it does not require any credential.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange.WebServices.Data;
namespace ConsoleApplication1 {
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.AutodiscoverUrl("FirstName.LastName#company.com", RedirectionUrlValidationCallback);
if (service != null)
{
FindItemsResults<Item> resultout = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
foreach (Item item in resultout.Items)
{
EmailMessage message = EmailMessage.Bind(service, item.Id);
String subject = message.Subject.ToString();
Console.Write(subject);
String fromwhom = message.From.Address.ToString();
Console.Write(fromwhom);
}
}
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
}
I need to perform the same steps but in Python. i.e read email details.
My attempt
from exchangelib import Account, Configuration, Credentials, DELEGATE, IMPERSONATION, NTLM
email = 'FirstName.LastName#company.com'
creds = Credentials(email, "")
account = Account(email, autodiscover=True, credentials = creds)
Error:
AutoDiscoverFailed: All steps in the autodiscover protocol failed
With Autodiscover false
from exchangelib import Account, Configuration, Credentials, DELEGATE, IMPERSONATION, NTLM
email = 'FirstName.LastName#company.com'
creds = Credentials(email, "")
config = Configuration(server = "domain.com", credentials=creds)
account = Account(email, autodiscover=False, config = config)
Error:
Wrong username or password for https;//domain.com/EWS/Exchange.asmx
I can access the https;//domain.com/EWS/Exchange.asmx via url, without entering any credential.
Note: I am fairly good in Python with no knowledge of C#.
I believe there are different ways of approaching authentication in Python; here's one.
I've worked on a similar project, where I try to print out an email [web automation], for which I used selenium and a webdriver to access a yahoo mail. This project included page inspection -- another approach. The code isn't optimised and the final output is not what I intended yet, but you could understand the idea at least.
Good Luck!
I tried to get all members/users of TFS with the REST API and the .NET client libraries.
It works, but I get a maximum number of 50 identitys. Does anyone know, how I get all users, not only 50? (I prefer avoiding to use the old API, how it is suggested in this question)
Here is my code:
VssCredentials credentials = new VssCredentials();
VssConnection connection = new VssConnection(new Uri(url), credentials);
IdentityMruHttpClient identityMruHttpClient = connection.GetClient<IdentityMruHttpClient>();
List<IdentityRef> members = identityMruHttpClient.GetIdentityMruAsync(ProjectName).Result;
There is a REST API User Entitlements - List which can retrieve the user list from VSTS (Visual Studio Team Services), but it's only available for VSTS.
There isn't such a REST API to retrieve the user list from on-premise TFS (TFS 2017 in your scenario).
So, for now you can use the client API you mentioned above to retrieve the user list. Tested on my side, I can retrieve all the identities (more than 50 ) with below code:
You can also check the user list from userlist.txt file which under ..\..\ \bin\Debug\
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Linq;
using System.IO;
namespace Getuserlist
{
class Program
{
static void Main(string[] args)
{
TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://server:8080/tfs"));
IIdentityManagementService ims = tcs.GetService<IIdentityManagementService>();
TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);
TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);
using (StreamWriter file = new StreamWriter("userlist.txt"))
foreach (TeamFoundationIdentity id in ids)
{
if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity")
{ Console.WriteLine(id.DisplayName); }
//{ Console.WriteLine(id.UniqueName); }
file.WriteLine("[{0}]", id.DisplayName);
}
var count = ids.Count(x => ids.Contains(x));
Console.WriteLine(count);
Console.ReadLine();
}
}
}
Let me start by saying I am new to C# and SOAP services. I need to wring a program that will read data from a flat file and make a call to a SOAP web service to insert the data into that system.
My network is behind a proxy server that I have to authenticate with a username and password in order to access anything external to our network or on the internet. I can not figure out how to do this. I have been searching for answers and trying the results I have found, but I have had no luck. The error message I get is
"The request failed with an empty response"
I have set up the service in SOAPUI, and if I supply my proxy settings to the SOAPUI preferences, it is able to leave our network and get a response.
The username and password I have in the example below are not real, but the response doesn't change either way. It seems to me like it never attempts to access or authenticate through the proxy server.
Can anyone help me out? Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
ConsoleApp6.ASC.Service1 soap = new ConsoleApp6.ASC.Service1();
ConsoleApp6.ASC.UserCredentialsSoapHeader credential = new ConsoleApp6.ASC.UserCredentialsSoapHeader();
credential.UserName = "soap_user_name";
credential.Password = "soap_password";
soap.UserCredentialsSoapHeaderValue = credential;
soap.Proxy = new WebProxy("http://gateway.zscalertwo.net:80/", true);
soap.Proxy.Credentials = new NetworkCredential("username", "password", "domain");
try
{
ASC.AppraiserLicense licenceInfo = soap.GetLicenseByLicenseNumber("46000049784", 1, "NY");
Console.WriteLine(licenceInfo);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
}
}
Console Output
System.Net.WebException: The request failed with an empty response.
at
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClie
ntMessage message, WebResponse response, Stream responseStream,
Boolean asyncCal l) at
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodN ame, Object[] parameters) at
ConsoleApp6.ASC.Service1.GetLicenseByLicenseNumber(String
LicenseNumber, B yte LicType, String st_abbr) in
C:\Users\mkurick\Documents\Visual Studio 2017\Pr
ojects\ConsoleApp6\ConsoleApp6\Web References\ASC\Reference.cs:line
120 at ConsoleApp6.Program.Main(String[] args) in
C:\Users\mkurick\Documents\Visu al Studio
2017\Projects\ConsoleApp6\ConsoleApp6\Program.cs:line 26
I am writing an App server application in C# that needs to access Firebase Database. It uses REST protocol. To authentication i want to use an service account.
Unfortunately there is no library written in C#, so i am trying to put the bellow http Request to work.
I follow this steps:
To get the accesstoken i follow the https://github.com/google/google-api-dotnet-client-samples. The code prints the token so should be ok to that point.
Invoke GET web request passing the token in the access_token query parameter as documented at https://firebase.google.com/docs/reference/rest/database/user-auth.
I tried all variations i could remember, in headers, with apostrophe, APN request style, but always got 401 error or 403. Error code 403 should mean that the API recognize the user but denys access to the resource, but i am not sure if this works this way in this case.
The account is defined in the API console and it has project edit and owner profile, for the Firebase app.
The rules are set like this:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Can't figure out were i went wrong. I don't think i need to go written an JWT token if i use google API library. Rules should not apply to this account so i guess i am not passing the token correctly. By inspecting the token retrieved i can see that it is of type Bear, so i tried to pass it on header with no success too.
Test code:
using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace FirebaseAppServer
{
/// </summary>
public class Program
{
public static void Main(string[] args)
{
accessFirebase();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public async static Task accessFirebase()
{
String serviceAccountEmail = "serviceaccount1#myapp.iam.gserviceaccount.com";
var certificate = new X509Certificate2(#"App.p12", "notasecret", X509KeyStorageFlags.Exportable); //App2 is the certificate i downloaded from API console
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://www.googleapis.com/auth/firebase.database" //from https://developers.google.com/identity/protocols/googlescopes
,"https://www.googleapis.com/auth/firebase"
,"https://www.googleapis.com/auth/cloud-platform"}
}.FromCertificate(certificate));
var task = await credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None);
Console.WriteLine("AccessToken " + credential.Token.AccessToken); //accessToken has a value, so guess is all good so far.
var request = (HttpWebRequest)WebRequest.Create("https://<Myapp>.firebaseio.com/.json?access_token=" + credential.Token.AccessToken);
request.Method = "GET";
request.ContentType = "application/json";
using (var response = (HttpWebResponse)request.GetResponse()) //Throw error 403 - forbidden
{
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine("responseString " + responseString);
}
}