How can I change this code to handle recurringpayment? - c#

I am trying to implement Direct payment method as I have user's credit card information etc in my database. This is the sample that I am referring:
using System;
using System.Collections.Generic;
using System.Text;
using com.paypal.sdk.services;
using com.paypal.sdk.profiles;
using com.paypal.sdk.util;
using com.paypal.soap.api;
namespace ASPDotNetSamples
{
public class DoDirectPayment
{
public DoDirectPayment()
{
}
public string DoDirectPaymentCode(string paymentAction, string amount, string creditCardType, string creditCardNumber, string expdate_month, string cvv2Number, string firstName, string lastName, string address1, string city, string state, string zip, string countryCode, string currencyCode)
{
com.paypal.soap.api.DoDirectPaymentReq req = new com.paypal.soap.api.DoDirectPaymentReq();
NVPCallerServices caller = new NVPCallerServices();
IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
/*
WARNING: Do not embed plaintext credentials in your application code.
Doing so is insecure and against best practices.
Your API credentials must be handled securely. Please consider
encrypting them for use in any production environment, and ensure
that only authorized individuals may view or modify them.
*/
// Set up your API credentials, PayPal end point, API operation and version.
profile.APIUsername = "sdk-three_api1.sdk.com";
profile.APIPassword = "QFZCWN5HZM8VBG7Q";
profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
profile.Environment = "sandbox";
caller.APIProfile = profile;
NVPCodec encoder = new NVPCodec();
encoder["VERSION"] = "51.0";
encoder["METHOD"] = "DoDirectPayment";
// Add request-specific fields to the request.
encoder["PAYMENTACTION"] = paymentAction;
encoder["AMT"] = amount;
encoder["CREDITCARDTYPE"] = creditCardType;
encoder["ACCT"] = creditCardNumber;
encoder["EXPDATE"] = expdate_month;
encoder["CVV2"] = cvv2Number;
encoder["FIRSTNAME"] = firstName;
encoder["LASTNAME"] = lastName;
encoder["STREET"] = address1;
encoder["CITY"] = city;
encoder["STATE"] = state;
encoder["ZIP"] = zip;
encoder["COUNTRYCODE"] = countryCode;
encoder["CURRENCYCODE"] = currencyCode;
// Execute the API operation and obtain the response.
string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = caller.Call(pStrrequestforNvp);
NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);
return decoder["ACK"];
}
}
}
This is the link:
https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_DoDirectPayment_cs.txt
This works fine but my only question is how do I handle recurringpayment with this? What changes should I make in the sample?
Thanks in advance :)

Check the PayPal API Reference.
There is a method named CreateRecurringPaymentsProfile
Also read Handling Recurring Payments

Related

Number 1 is randomly appended to the end of my JWT secret after URL encoding

I have searched every nook and cranny for a solution to my problem but I cannot seem to find one.
I have a class that utilizes methods to create a JSON Web Token. The web token I create needs match the following (notice there is not a number 1 on the far right of my secret):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBrZXkiOiIxMjMtNDU2LTc4OS0wIiwicmVzb3VyY2UiOiJnZXRfZ2VvY29kZSJ9.xGLb92d6yVLqLf5TnrahMCxm-OGTHmXiXLvnRUqLWYM
The token I generate matches the token above, except for the fact that a number 1 is randomly appended on the far right end of my token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBrZXkiOiIxMjMtNDU2LTc4OS0wIiwicmVzb3VyY2UiOiJnZXRfZ2VvY29kZSJ9.xGLb92d6yVLqLf5TnrahMCxm-OGTHmXiXLvnRUqLWYM1
As you can see, that is the section of the JWT that holds the secret. Let me demonstrate how I am generating and encrypting the token so you can help with diagnosing the issue. I will show you the entire class then walk you through the methods.
Here is the entire class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Security.Cryptography;
namespace Project.JWT
{
public class Token
{
public string CreateToken(string resource, string appkey, string secret, string algorithm)
{
if (algorithm != "HS256")
return "Algorithm not supported";
JwtPayload payload = new JwtPayload
{
appkey = appkey,
resource = resource
};
return EncodeToken(payload, secret);
}
public static string EncodeToken(JwtPayload jwtPayload, string secret)
{
const string algorithm = "HS256";
var header = new Header
{
typ = "JWT",
alg = algorithm
};
var jwt = Base64Encode(JsonConvert.SerializeObject(header)) + "." + Base64Encode(JsonConvert.SerializeObject(jwtPayload));
jwt += "." + Sign(jwt, secret);
return jwt;
}
public static string Base64Encode(dynamic obj)
{
Type strType = obj.GetType();
var base64EncodedValue = Convert.ToBase64String(strType.Name.ToLower() == "string" ? Encoding.UTF8.GetBytes(obj) : obj);
return base64EncodedValue;
}
private static string Sign(string str, string key)
{
byte[] signature;
using (var crypto = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
signature = crypto.ComputeHash(Encoding.UTF8.GetBytes(str));
}
return System.Web.HttpServerUtility.UrlTokenEncode(signature);
}
}
public class Header
{
public string alg { get; set; }
public string typ { get; set; }
}
public class JwtPayload
{
public string appkey { get; set; }
public string resource { get; set; }
}
}
First, The CreateToken method is passed the credentials to create the payload. It then calls the EncodeToken method that takes the payload and secret as a parameter. Keep in mind that my secret is a hard-coded string that never changes throughout the lifetime of the app; So I know that is not randomly generating the number 1.
Line 39, The header and payload are converted into a base 64 string and joined together by a dot which generates the first two parts of my token perfectly:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBrZXkiOiIxMjMtNDU2LTc4OS0wIiwicmVzb3VyY2UiOiJnZXRfZ2VvY29kZSJ9
Then, I call the Sign method on line 41 which request the signing of my token using the SHA256 algorithm.
The Sign method accepts the combined header and payload as str then the secret is passed through as key.
On line 62, I begin the creation of the signature using my custom key, which is "testsecret".
Then I URL encode the signature on line 67, just before returning it. When I return it, line 41 combines the three parts of the token together, thus leaving me with a perfect JWT...... except for the number "1" at the far right end of the secret.
please help.
It's to do with the way that HttpServerUtility.UrlTokenEncode works, emphasis mine:
Encodes a byte array into its equivalent string representation using base 64 digits, which is usable for transmission on the URL
You'll know that depending on its length a Base64 string will be padded with = appended to the end. The = is not considered URL safe and so is replaced with an integer denoting the count, in this case 1.
You can test this by debugging and replace the line below...
return System.Web.HttpServerUtility.UrlTokenEncode(signature);
...with this...
return Convert.ToBase64String(signature);
...and inspecting the return value.
You'll see that it ends with a = so HttpServerUtility.UrlTokenEncode replaces it with a 1.

C# Save Data To Database and Exit Program

Hey Guys i have a script written in c# that generates some encryption keys that i want to save into my database my code looks like this:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.WindowsAzure.MediaServices.Client;
using Microsoft.WindowsAzure.MediaServices.Client.ContentKeyAuthorization;
using Microsoft.WindowsAzure.MediaServices.Client.DynamicEncryption;
using Microsoft.WindowsAzure.MediaServices.Client.Widevine;
using Newtonsoft.Json;
namespace DeliverDRMLicenses
{
class Program
{
// Read values from the App.config file.
private static readonly string _mediaServicesAccountName =
ConfigurationManager.AppSettings["MediaServicesAccountName"];
private static readonly string _mediaServicesAccountKey =
ConfigurationManager.AppSettings["MediaServicesAccountKey"];
private static readonly Uri _sampleIssuer =
new Uri(ConfigurationManager.AppSettings["Issuer"]);
private static readonly Uri _sampleAudience =
new Uri(ConfigurationManager.AppSettings["Audience"]);
// Field for service context.
private static CloudMediaContext _context = null;
private static MediaServicesCredentials _cachedCredentials = null;
static void Main(string[] args)
{
// Create and cache the Media Services credentials in a static class variable.
_cachedCredentials = new MediaServicesCredentials(
_mediaServicesAccountName,
_mediaServicesAccountKey);
// Used the cached credentials to create CloudMediaContext.
_context = new CloudMediaContext(_cachedCredentials);
bool tokenRestriction = true;
string tokenTemplateString = null;
string drm_key_id = null;
IContentKey key = CreateCommonTypeContentKey();
// Print out the key ID and Key in base64 string format
drm_key_id = key.Id;
Console.WriteLine(" key:{0}",
key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));
Console.WriteLine(" key value:{1} ",
key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));
sbasedrmdataDataSetTableAdapters.sbase_drm_keysTableAdapter sbasedrmTableAdapter =
new sbasedrmdataDataSetTableAdapters.sbase_drm_keysTableAdapter();
sbasedrmTableAdapter.Insert(drm_key_id);
Console.WriteLine("Protection key: {0} ",
key.ProtectionKeyId, System.Convert.ToBase64String(key.GetClearKeyValue()));
Console.WriteLine("PlayReady URL: {0}",
key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));
Console.WriteLine("Widevin URL: {0}",
key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine));
if (tokenRestriction)
tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);
else
AddOpenAuthorizationPolicy(key);
Console.WriteLine("Auth policy: {0}",
key.AuthorizationPolicyId);
Console.WriteLine();
Console.ReadLine();
Environment.Exit(0);
}
static public void AddOpenAuthorizationPolicy(IContentKey contentKey)
{
// Create ContentKeyAuthorizationPolicy with Open restrictions
// and create authorization policy
List<ContentKeyAuthorizationPolicyRestriction> restrictions =
new List<ContentKeyAuthorizationPolicyRestriction>
{
new ContentKeyAuthorizationPolicyRestriction
{
Name = "Open",
KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
Requirements = null
}
};
// Configure PlayReady and Widevine license templates.
string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();
string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();
IContentKeyAuthorizationPolicyOption PlayReadyPolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("",
ContentKeyDeliveryType.PlayReadyLicense,
restrictions, PlayReadyLicenseTemplate);
IContentKeyAuthorizationPolicyOption WidevinePolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("",
ContentKeyDeliveryType.Widevine,
restrictions, WidevineLicenseTemplate);
IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
ContentKeyAuthorizationPolicies.
CreateAsync("Deliver Common Content Key with no restrictions").
Result;
contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);
// Associate the content key authorization policy with the content key.
contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
contentKey = contentKey.UpdateAsync().Result;
}
public static string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
{
string tokenTemplateString = GenerateTokenRequirements();
List<ContentKeyAuthorizationPolicyRestriction> restrictions =
new List<ContentKeyAuthorizationPolicyRestriction>
{
new ContentKeyAuthorizationPolicyRestriction
{
Name = "Token Authorization Policy",
KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
Requirements = tokenTemplateString,
}
};
// Configure PlayReady and Widevine license templates.
string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();
string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();
IContentKeyAuthorizationPolicyOption PlayReadyPolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
ContentKeyDeliveryType.PlayReadyLicense,
restrictions, PlayReadyLicenseTemplate);
IContentKeyAuthorizationPolicyOption WidevinePolicy =
_context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
ContentKeyDeliveryType.Widevine,
restrictions, WidevineLicenseTemplate);
IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
ContentKeyAuthorizationPolicies.
CreateAsync("Deliver Common Content Key with token restrictions").
Result;
contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);
// Associate the content key authorization policy with the content key
contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
contentKey = contentKey.UpdateAsync().Result;
return tokenTemplateString;
}
static private string GenerateTokenRequirements()
{
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);
template.PrimaryVerificationKey = new SymmetricVerificationKey();
template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
template.Audience = _sampleAudience.ToString();
template.Issuer = _sampleIssuer.ToString();
template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
return TokenRestrictionTemplateSerializer.Serialize(template);
}
static private string ConfigurePlayReadyLicenseTemplate()
{
// The following code configures PlayReady License Template using .NET classes
// and returns the XML string.
//The PlayReadyLicenseResponseTemplate class represents the template
//for the response sent back to the end user.
//It contains a field for a custom data string between the license server
//and the application (may be useful for custom app logic)
//as well as a list of one or more license templates.
PlayReadyLicenseResponseTemplate responseTemplate =
new PlayReadyLicenseResponseTemplate();
// The PlayReadyLicenseTemplate class represents a license template
// for creating PlayReady licenses
// to be returned to the end users.
// It contains the data on the content key in the license
// and any rights or restrictions to be
// enforced by the PlayReady DRM runtime when using the content key.
PlayReadyLicenseTemplate licenseTemplate = new PlayReadyLicenseTemplate();
// Configure whether the license is persistent
// (saved in persistent storage on the client)
// or non-persistent (only held in memory while the player is using the license).
licenseTemplate.LicenseType = PlayReadyLicenseType.Nonpersistent;
// AllowTestDevices controls whether test devices can use the license or not.
// If true, the MinimumSecurityLevel property of the license
// is set to 150. If false (the default),
// the MinimumSecurityLevel property of the license is set to 2000.
licenseTemplate.AllowTestDevices = true;
// You can also configure the Play Right in the PlayReady license by using the PlayReadyPlayRight class.
// It grants the user the ability to playback the content subject to the zero or more restrictions
// configured in the license and on the PlayRight itself (for playback specific policy).
// Much of the policy on the PlayRight has to do with output restrictions
// which control the types of outputs that the content can be played over and
// any restrictions that must be put in place when using a given output.
// For example, if the DigitalVideoOnlyContentRestriction is enabled,
//then the DRM runtime will only allow the video to be displayed over digital outputs
//(analog video outputs won’t be allowed to pass the content).
// IMPORTANT: These types of restrictions can be very powerful
// but can also affect the consumer experience.
// If the output protections are configured too restrictive,
// the content might be unplayable on some clients.
// For more information, see the PlayReady Compliance Rules document.
// For example:
//licenseTemplate.PlayRight.AgcAndColorStripeRestriction = new AgcAndColorStripeRestriction(1);
responseTemplate.LicenseTemplates.Add(licenseTemplate);
return MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
}
private static string ConfigureWidevineLicenseTemplate()
{
var template = new WidevineMessage
{
allowed_track_types = AllowedTrackTypes.SD_HD,
content_key_specs = new[]
{
new ContentKeySpecs
{
required_output_protection =
new RequiredOutputProtection { hdcp = Hdcp.HDCP_NONE},
security_level = 1,
track_type = "SD"
}
},
policy_overrides = new
{
can_play = true,
can_persist = true,
can_renew = false
}
};
string configuration = JsonConvert.SerializeObject(template);
return configuration;
}
static public IContentKey CreateCommonTypeContentKey()
{
// Create envelope encryption content key
Guid keyId = Guid.NewGuid();
byte[] contentKey = GetRandomBuffer(16);
IContentKey key = _context.ContentKeys.Create(
keyId,
contentKey,
"ContentKey",
ContentKeyType.CommonEncryption);
return key;
}
static private byte[] GetRandomBuffer(int length)
{
var returnValue = new byte[length];
using (var rng =
new System.Security.Cryptography.RNGCryptoServiceProvider())
{
rng.GetBytes(returnValue);
}
return returnValue;
}
}
}
So the issue im having is when i try to run the program i get an error at this line
sbasedrmTableAdapter.Insert(drm_key_id);
and the error i receive is:
Error CS7036 There is no argument given that corresponds to the
required formal parameter 'drm_key' of
'sbase_drm_keysTableAdapter.Insert(string, string, string, string)'
How can i solve this error
It looks like you are trying to call a method that requires 4 strings as parameters with just one parameter. Try supplying the correct parameters to the method.
Your problem looks quite similar to: OOP inheritance and default constructor

How to check EU VAT using VIES SOAP service in C#

I have an ASP.NET website that needs to check a user-supplied VAT. The VIES Service can be used for that which exposes a SOAP API.
I need a dead-simple example on how to validate a VAT using this service. In PHP, it's these 4 lines: https://stackoverflow.com/a/14340495. For C#, I have found some articles from 2010 that do not work or are tens or even hundreds lines of "wrappers", "helper services" etc.
I don't need any of that, can someone provide PHP-like four-liner that would check VAT in C#? Thank you.
The simplest way I found is just to send an XML and parse it when it comes back:
var wc = new WebClient();
var request = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:urn=""urn:ec.europa.eu:taxud:vies:services:checkVat:types"">
<soapenv:Header/>
<soapenv:Body>
<urn:checkVat>
<urn:countryCode>COUNTRY</urn:countryCode>
<urn:vatNumber>VATNUMBER</urn:vatNumber>
</urn:checkVat>
</soapenv:Body>
</soapenv:Envelope>";
request = request.Replace("COUNTRY", countryCode);
request = request.Replace("VATNUMBER", theRest);
String response;
try
{
response = wc.UploadString("http://ec.europa.eu/taxation_customs/vies/services/checkVatService", request);
}
catch
{
// service throws WebException e.g. when non-EU VAT is supplied
}
var isValid = response.Contains("<valid>true</valid>");
Here is a self-sufficient (no WCF, no WSDL, ...) utility class that will check the VAT number and get information on the company (name and address). It will return null if the VAT number is invalid or if any error occurred.
Update 2022/10/17 : I have added namespace handling to parse the response as it seems the EU web service was modified. If you need the old version, just look at the history
// sample calling code
Console.WriteLine(EuropeanVatInformation.Get("FR89831948815"));
...
public class EuropeanVatInformation
{
private EuropeanVatInformation() { }
public string CountryCode { get; private set; }
public string VatNumber { get; private set; }
public string Address { get; private set; }
public string Name { get; private set; }
public override string ToString() => CountryCode + " " + VatNumber + ": " + Name + ", " + Address.Replace("\n", ", ");
public static EuropeanVatInformation Get(string countryCodeAndVatNumber)
{
if (countryCodeAndVatNumber == null)
throw new ArgumentNullException(nameof(countryCodeAndVatNumber));
if (countryCodeAndVatNumber.Length < 3)
return null;
return Get(countryCodeAndVatNumber.Substring(0, 2), countryCodeAndVatNumber.Substring(2));
}
public static EuropeanVatInformation Get(string countryCode, string vatNumber)
{
if (countryCode == null)
throw new ArgumentNullException(nameof(countryCode));
if (vatNumber == null)
throw new ArgumentNullException(nameof(vatNumber));
countryCode = countryCode.Trim();
vatNumber = vatNumber.Trim().Replace(" ", string.Empty);
const string ns = "urn:ec.europa.eu:taxud:vies:services:checkVat:types";
const string url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService";
const string xml = #"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><checkVat xmlns='" + ns + "'><countryCode>{0}</countryCode><vatNumber>{1}</vatNumber></checkVat></s:Body></s:Envelope>";
try
{
using (var client = new WebClient())
{
var doc = new XmlDocument();
doc.LoadXml(client.UploadString(url, string.Format(xml, countryCode, vatNumber)));
var response = doc.SelectSingleNode("//*[local-name()='checkVatResponse']") as XmlElement;
if (response == null || response["valid", ns]?.InnerText != "true")
return null;
var info = new EuropeanVatInformation
{
CountryCode = response["countryCode", ns].InnerText,
VatNumber = response["vatNumber", ns].InnerText,
Name = response["name", ns]?.InnerText,
Address = response["address", ns]?.InnerText
};
return info;
}
}
catch
{
return null;
}
}
}
On .NET platform it is common to consume a Web service so that we generate a proxy class. This can usually be done using Visual Studio "Add Web Reference" where you just fill in a path to the WSDL. An alternative is to generate source classes using wsdl.exe or svcutil.exe.
Then just consume this class and verifying VAT becomes a one-liner:
DateTime date = new checkVatPortTypeClient().checkVat(ref countryCode, ref vatNumber, out isValid, out name, out address);
Generating proxy provides strongly typed API to consume whole service and we don't need to manually create soap envelope and parse output text. It is much more easier, safer and generic solution than yours.
Updated: I've published this as a NuGet library.
https://github.com/TriggerMe/CSharpVatChecker
var vatQuery = new VATQuery();
var vatResult = await vatQuery.CheckVATNumberAsync("IE", "3041081MH"); // The Squarespace VAT Number
Console.WriteLine(vatResult.Valid); // Is the VAT Number valid?
Console.WriteLine(vatResult.Name); // Name of the organisation
Based on Pavel Hodek's:
Make sure you have the Microsoft WCF Web Service Reference
Provide extension installed for visual studio (I'm using VS 2017
Community).
In the solution explorer right click on Connected Services > Add Connected Service
Select the WCF extension.
Type in the URL provided by VIES
http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl to generate the Service class from the wsdl.
Press Go and select the service, give a proper name for the namespace e.g. Services.VATCheck
Press Finish, which will create a new folder and a file called reference.cs in the Connected Services rename the file to VATCheck which will also rename the Class.
In a controller use the following code to invoke the call, make sure it's async (it can take awhile to eventually load all the data)
public async Task<IActionResult> CheckVAT()
{
var countryCode = "BE";
var vatNumber = "123456789";
try
{
checkVatPortType test = new checkVatPortTypeClient(checkVatPortTypeClient.EndpointConfiguration.checkVatPort, "http://ec.europa.eu/taxation_customs/vies/services/checkVatService");
checkVatResponse response = await test.checkVatAsync(new checkVatRequest { countryCode = countryCode, vatNumber = vatNumber });
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return Ok();
}
Please note that you can clean-up this call, but that's totally up to you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BTWCheck.eu.europa.ec;
namespace BTWCheck
{
class Program
{
static void Main(string[] args)
{
// VS 2017
// add service reference -> button "Advanced" -> button "Add Web Reference" ->
// URL = http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
string Landcode = "NL";
string BTWNummer = "820471616B01"; // VAT nr BOL.COM
checkVatService test = new checkVatService();
test.checkVat(ref Landcode, ref BTWNummer, out bool GeldigBTWNr, out string Naam, out string Adres);
Console.WriteLine(Landcode + BTWNummer + " " + GeldigBTWNr);
Console.WriteLine(Naam+Adres);
Console.ReadKey();
}
}
}

How to get the facebook signed request in c#

I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse

Cannot find com.apiconnector.API in the dotMailer API for C#

I am trying to make sense of the dotMailer API for C#.
I have a class library where I intend to store the functionality that will consume the dotMailer API which references version 1.5 of the API. I also have a Service Reference set up from this WSDL
I was looking through the C# examples, but already I'm stumped! The following was pulled directly from here
Example of use in C#
/// <summary>
/// Adds a contact to an address book
/// </summary>
public void AddContactToAddressBook()
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
Console.WriteLine("AddContactToAddressBook");
Console.WriteLine("-----------------------");
// Get an instance to the web reference
com.apiconnector.API api = new com.apiconnector.API();
try
{
// we need a new contact
com.apiconnector.APIContact contact = new com.apiconnector.APIContact();
// populate the contact
contact.AudienceType = com.apiconnector.ContactAudienceTypes.B2B;
// populate the data fields
contact.DataFields = new com.apiconnector.ContactDataFields();
contact.DataFields.Keys = new string[3];
contact.DataFields.Values = new object[3];
contact.DataFields.Keys[0] = "FIRSTNAME";
contact.DataFields.Values[0] = "John";
contact.DataFields.Keys[1] = "LASTNAME";
contact.DataFields.Values[1] = "Smith";
contact.DataFields.Keys[2] = "POSTCODE";
contact.DataFields.Values[2] = "IP4 1XU";
// email address
contact.Email = "joe.smith#example.com";
contact.EmailType = com.apiconnector.ContactEmailTypes.PlainText;
contact.Notes = "This is a test only email";
contact.OptInType = com.apiconnector.ContactOptInTypes.Single;
// This method will create the contact required if it doesn't already exist within the dotMailer system,
// so we don't have to call CreateContact as a prerequisite.
//
// This method will also overwrite an existing contact, with the information provided here.
//
// This method will fail if you try to add a contact to the "Test" or "All Contacts" address books.
//
com.apiconnector.APIContact newContact = api.AddContactToAddressBook(username, password, contact, addressBookId);
// Did we get something back from the API ?
if (newContact != null)
{
Console.WriteLine("Contact added to address book {0} -> {1}", newContact.ID, addressBookId);
}
}
catch (SoapException ex) // catch any soap issues/errors from the web service
{
Console.WriteLine("Error -> {0}", ex.Message);
}
Console.WriteLine();
}
My problem is that the following line does not resolve.
com.apiconnector.API api = new com.apiconnector.API();
I have looked in namespace dotMailer.Sdk.com.apiconnector for API but it does not exist, so where is it?
Am I missing something?
Add the wsdl as a service reference. In the example below I've called it "ServiceReference1" (because that's the default and I was lazy). You then use the reference to the APISoapClient (I've called it Client) instead of "api" that you're having trouble declaring.
All compiles fine, I'm not going to execute it because I've no idea what shenanigans my random code snippet is going to cause for the server! Should point you in the right direction?
using WindowsFormsApplication1.ServiceReference1;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddContactToAddressBook();
}
private void AddContactToAddressBook()
{
using (ServiceReference1.APISoapClient Client = new ServiceReference1.APISoapClient())
{
APIContact Contact = new APIContact();
Contact.AudienceType = ContactAudienceTypes.B2B;
APIContact NewContact = Client.AddContactToAddressBook(username, password, Contact, addressBookId); // etc. etc.
}
}
}
}

Categories