Skip to content

Netstandard and Async #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ PublishScripts/

# NuGet Packages
*.nupkg
!**/ReleaseArtifact/*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
Expand Down
19 changes: 19 additions & 0 deletions AuthorizeNET/AuthorizeNET.Tests/AuthorizeNET.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\AuthorizeNET\AuthorizeNET.csproj" />
</ItemGroup>

</Project>
113 changes: 113 additions & 0 deletions AuthorizeNET/AuthorizeNET.Tests/TransactionControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

namespace AuthorizeNET.Tests
{
[TestClass]
public class TransactionControllerTests
{
merchantAuthenticationType MerchantAuthentication => new merchantAuthenticationType()
{
name = "5KP3u95bQpv",
ItemElementName = ItemChoiceType.transactionKey,
Item = "346HZ32z3fP4hTG2",
};


[TestMethod]
public async Task ChargeAsync()
{
var transaction = new transactionRequestType
{
amount = 123.45m,
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
payment = new paymentType
{
Item = new creditCardType
{
cardNumber = "4111111111111111",
expirationDate = "0349",
cardCode = "123"
}
},

billTo = new customerAddressType
{
firstName = "TestName",
lastName = "McTesterson",
address = "123 Here st.",
city = "Springville",
state = "WA",
zip = "00000"
}
};

var fullRequest = new createTransactionRequest
{
merchantAuthentication = MerchantAuthentication,
transactionRequest = transaction,
};

// Send the request.
var controller = new createTransactionController(fullRequest);
var response = await controller.ExecuteWithApiResponseAsync(AuthorizeNet.Environment.SANDBOX);

Assert.IsNotNull(response);
}

[TestMethod]
public void ChargeSync()
{
var transaction = new transactionRequestType
{
amount = 123.45m,
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
payment = new paymentType
{
Item = new creditCardType
{
cardNumber = "4111111111111111",
expirationDate = "0349",
cardCode = "123"
}
},

billTo = new customerAddressType
{
firstName = "TestName",
lastName = "McTesterson",
address = "123 Here st.",
city = "Springville",
state = "WA",
zip = "00000"
}
};

var fullRequest = new createTransactionRequest
{
merchantAuthentication = MerchantAuthentication,
transactionRequest = transaction,
};

// Send the request.
var controller = new createTransactionController(fullRequest);
var response = controller.ExecuteWithApiResponse(AuthorizeNet.Environment.SANDBOX);

Assert.IsNotNull(response);
}

[TestMethod]
public async Task GetMerchangeDetails()
{
var controller = new getMerchantDetailsController(new getMerchantDetailsRequest
{
merchantAuthentication = MerchantAuthentication,
});

var response = await controller.ExecuteWithApiResponseAsync(AuthorizeNet.Environment.SANDBOX);
Assert.IsNotNull(response);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6450,6 +6450,9 @@ public enum paymentMethodsTypeEnum {

/// <remarks/>
AndroidPay,

/// <remarks/>
GooglePay,
}

/// <remarks/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ namespace AuthorizeNet.Api.Controllers.Bases
using Contracts.V1;
using Utilities;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using AuthorizeNET.Utilities;

public abstract class ApiOperationBase<TQ, TS> : IApiOperation<TQ, TS>
where TQ : ANetApiRequest
Expand All @@ -29,7 +31,7 @@ protected ApiOperationBase(TQ apiRequest)
if (null == apiRequest)
{
Logger.LogError("null apiRequest");
throw new ArgumentNullException("apiRequest", "Input request cannot be null");
throw new ArgumentNullException(nameof(apiRequest), "Input request cannot be null");
}
if (null != GetApiResponse())
{
Expand Down Expand Up @@ -81,16 +83,22 @@ public TS ExecuteWithApiResponse(AuthorizeNet.Environment environment = null)
return GetApiResponse();
}

public async Task<TS> ExecuteWithApiResponseAsync(AuthorizeNet.Environment environment = null)
{
await ExecuteAsync(environment).ConfigureAwait(false);
return GetApiResponse();
}

const String NullEnvironmentErrorMessage = "Environment not set. Set environment using setter or use overloaded method to pass appropriate environment";

public void Execute(AuthorizeNet.Environment environment = null)
public async Task ExecuteAsync(AuthorizeNet.Environment environment = null)
{
BeforeExecute();

if (null == environment) { environment = ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment; }
if (null == environment) throw new ArgumentException(NullEnvironmentErrorMessage);

var httpApiResponse = HttpUtility.PostData<TQ, TS>(environment, GetApiRequest());
var httpApiResponse = await HttpUtility.PostDataAsync<TQ, TS>(environment, GetApiRequest()).ConfigureAwait(false);

if (null != httpApiResponse)
{
Expand Down Expand Up @@ -122,6 +130,11 @@ public void Execute(AuthorizeNet.Environment environment = null)
AfterExecute();
}

public void Execute(AuthorizeNet.Environment environment = null)
{
AsyncUtil.RunSync(() => ExecuteAsync(environment));
}

public messageTypeEnum GetResultCode()
{
return ResultCode;
Expand Down Expand Up @@ -171,6 +184,7 @@ private messagesType GetResultMessage()
protected messageTypeEnum ResultCode = messageTypeEnum.Ok;

protected virtual void BeforeExecute() { }

protected virtual void AfterExecute() { }

protected abstract void ValidateRequest();
Expand All @@ -181,7 +195,7 @@ private void Validate()
ValidateAndSetMerchantAuthentication();

//set the client Id
SetClientId();
SetClientId();
ValidateRequest();
}

Expand Down
10 changes: 10 additions & 0 deletions AuthorizeNET/AuthorizeNET/Api/Controllers/Bases/IApiOperation.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace AuthorizeNet.Api.Controllers.Bases
{
using System.Collections.Generic;
using System.Threading.Tasks;

/**
* @author ramittal
Expand All @@ -12,10 +13,19 @@ public interface IApiOperation<TQ, TS>
where TS : AuthorizeNet.Api.Contracts.V1.ANetApiResponse
{
TS GetApiResponse();

AuthorizeNet.Api.Contracts.V1.ANetApiResponse GetErrorResponse();

TS ExecuteWithApiResponse(AuthorizeNet.Environment environment = null);

Task<TS> ExecuteWithApiResponseAsync(AuthorizeNet.Environment environment = null);

void Execute(AuthorizeNet.Environment environment = null);

Task ExecuteAsync(AuthorizeNet.Environment environment = null);

AuthorizeNet.Api.Contracts.V1.messageTypeEnum GetResultCode();

List<string> GetResults();
}
#pragma warning restore 1591
Expand Down
22 changes: 12 additions & 10 deletions AuthorizeNET/AuthorizeNET/AuthorizeNET.csproj
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<Version>1.0.0.0</Version>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>0.1.3-beta</Version>
<PackageId>AuthorizeNet.DotNetCore</PackageId>
<PackageProjectUrl>https://github.com/AuthorizeNet/dotnet-core-sdk-beta</PackageProjectUrl>
<PackageTags>Payments API Authorize.Net</PackageTags>
<Authors>Authorize.Net</Authors>
<Company>Authorize.Net</Company>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Description>Use this SDK to integrate with the Authorize.Net APIs for Payment Transactions, Recurring Billing and Customer Payment Profiles.</Description>
<Copyright>Authorize.Net</Copyright>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DocumentationFile>bin\Release\netcoreapp2.0\AuthorizeNET.xml</DocumentationFile>
<DocumentationFile>bin\Release\netstandard2.0\AuthorizeNET.xml</DocumentationFile>
<OutputPath></OutputPath>
</PropertyGroup>

<ItemGroup>
<Compile Remove="AuthorizeNet.Core\**" />
<EmbeddedResource Remove="AuthorizeNet.Core\**" />
<None Remove="AuthorizeNet.Core\**" />
</ItemGroup>

<ItemGroup>
<Compile Remove="Api\Controllers\createFingerPrintController.cs" />
<Compile Remove="Utilities\Crypto.cs" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="System.ComponentModel.Primitives" Version="4.3.0" />
<PackageReference Include="System.Xml.XmlSerializer" Version="4.3.0" />
</ItemGroup>
Expand Down
25 changes: 25 additions & 0 deletions AuthorizeNET/AuthorizeNET/Utilities/AsyncHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;

namespace AuthorizeNET.Utilities
{
internal static class AsyncUtil
{
private static readonly TaskFactory taskFactory = new
TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);

public static void RunSync(Func<Task> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
taskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}
}
}
23 changes: 12 additions & 11 deletions AuthorizeNET/AuthorizeNET/Utilities/HttpUtility.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
namespace AuthorizeNet.Utilities
{
using Api.Contracts.V1;
using Api.Controllers.Bases;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Net;
using Api.Contracts.V1;
using Api.Controllers.Bases;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public static class HttpUtility
public static class HttpUtility
{

private static readonly ILogger Logger = LogFactory.getLog(typeof(HttpUtility));
Expand All @@ -22,7 +23,7 @@ private static Uri GetPostUrl(AuthorizeNet.Environment env)
return postUrl;
}

public static ANetApiResponse PostData<TQ, TS>(AuthorizeNet.Environment env, TQ request)
public static async Task<ANetApiResponse> PostDataAsync<TQ, TS>(AuthorizeNet.Environment env, TQ request)
where TQ : ANetApiRequest
where TS : ANetApiResponse
{
Expand All @@ -45,12 +46,12 @@ public static ANetApiResponse PostData<TQ, TS>(AuthorizeNet.Environment env, TQ
var httpConnectionTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpConnectionTimeout);
client.Timeout = TimeSpan.FromMilliseconds(httpConnectionTimeout != 0 ? httpConnectionTimeout : Constants.HttpConnectionDefaultTimeout);
var content = new StringContent(XmlUtility.Serialize(request), Encoding.UTF8, "text/xml");
var webResponse = client.PostAsync(postUrl, content).Result;
var webResponse = await client.PostAsync(postUrl, content).ConfigureAwait(false);
Logger.LogDebug("Retrieving Response from Url: '{0}'", postUrl);

// Get the response
Logger.LogDebug("Received Response: '{0}'", webResponse);
responseAsString = webResponse.Content.ReadAsStringAsync().Result;
responseAsString = await webResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Logger.LogDebug("Response from Stream: '{0}'", responseAsString);

}
Expand Down
Loading