Archive
Send physical #mail automatically from c#

In a world of email, sometimes a letter caries more weight. It is more likely to be read, and has a nice physical quality to it. Docmail offers an automated service to send PDFs as physical mail to an address automatically, and here’s some C# code to show how it’s done.
- Create a new project, and make a service reference to https://www.cfhdocmail.com/LiveAPI/DMWS.asmx – call the reference ServiceReference2
- Importantly: modify your app.config changing the binding to say maxReceivedMessageSize=”2147483647″ like follows;
<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<startup>
<supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.5″ />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name=”DMWSSoap” maxReceivedMessageSize=”2147483647″ >
<security mode=”Transport” /></binding>
<binding name=”DMWSSoap1″ maxReceivedMessageSize=”2147483647″/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address=”https://www.cfhdocmail.com/LiveAPI/DMWS.asmx”
binding=”basicHttpBinding” bindingConfiguration=”DMWSSoap”
contract=”ServiceReference2.DMWSSoap” name=”DMWSSoap”>
</endpoint>
</client>
</system.serviceModel>
</configuration> - Ensure you’ve got a username and password with Docmail, as I’ve omitted this from the code, and the postal address is obscured.
using System;
using System.IO;namespace Docmail
{
class Program
{
static void Main()
{
// Need reference to https://www.cfhdocmail.com/LiveAPI/DMWS.asmx
// put maxReceivedMessageSize=”2147483647″ into the binding
SendFile(“email@gmail.com”,”password”);
}//(where ServiceReference2 is the root namespace for the web service reference)
private static void SendFile(string sUsr, string sPwd)
{
var bFile = File.ReadAllBytes(@”C:\Users\Fiach\Documents\MBCloud Invoice.pdf”);
var oService = new ServiceReference2.DMWSSoapClient();
var oSAH = new ServiceReference2.ServiceAuthHeader
{
Username = sUsr,
Password = sPwd
};
var oMailing = new ServiceReference2.Mailing();
var oAddress = new ServiceReference2.Address();
oMailing.MailingDescription = “Test mail.”;
oMailing.IsBlackAndWhite = false;
oMailing.IsDuplex = false;
oMailing.AddressNameFormat = “T”;
{
oAddress.Title = “MR”;
oAddress.FirstName = “Bob”;
oAddress.Surname = “Jones”;
oAddress.JobTitle = “”;
oAddress.FullName = “Bon Jones”;
oAddress.Address1 = “10 Main Street”;
oAddress.Address2 = “London”;
oAddress.Address3 = “SW1 444”;
oAddress.Address4 = “England”;
oAddress.Address5 = “(UK)”;
}
//add address to mailing
var oAddresses = new ServiceReference2.Address[1];
oAddresses.SetValue(oAddress, oAddresses.Length – 1);
oMailing.Addresses = oAddresses;
var oTemplate = new ServiceReference2.Template();
{
oTemplate.FileData = bFile;
oTemplate.FileName = “tsftfile.pdf”;
oTemplate.TemplateName = “TemplateName”;
oTemplate.AddressedDocument = true;
}
//add template to mailing
var oTemplates = new ServiceReference2.Template[1];
oTemplates.SetValue(oTemplate, oTemplates.Length – 1);
oMailing.Templates = oTemplates;
//Save mailing
var oMailingResult = oService.SaveMailing(oSAH, oMailing);
if (!oMailingResult.Success) throw new Exception(string.Format(“Mailing error: {0}”, oMailingResult.FailureMessage));
//Create a proof of the mailing
var oProof = oService.GetProof(oSAH, oMailingResult.MailingGUID, true);
var iSecondCount = 0;
//Loop for 3 mins waiting for a proof
while ((iSecondCount < 180) && oProof.Success && !oProof.ProofReady)
{
//Sleep for 5 seconds
System.Threading.Thread.Sleep(1000);
oProof = oService.GetProof(oSAH, oMailingResult.MailingGUID, true);
iSecondCount += 1;
}
if (!oProof.Success | !oProof.ProofReady) throw new Exception(“Proof not ready within 3 mins”);
//Place the order
var oOrderResult = oService.PlaceOrder(oSAH, oMailingResult.MailingGUID, “”);
if (!oOrderResult.Success) throw new Exception(string.Format(“PlaceOrder error: {0}”, oOrderResult.FailureMessage));
}
}
}
Verify #SSL expiry using C#

Need to remember when to renew a SSL cert?, here’s some handy code in c#
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;namespace CheckSSL
{
class Program
{
static void Main(string[] args)
{
//Do webrequest to get info on secure site
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“https://www.avatarapi.com”);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();//retrieve the ssl cert and assign it to an X509Certificate object
X509Certificate cert = request.ServicePoint.Certificate;//convert the X509Certificate to an X509Certificate2 object by passing it into the constructor
X509Certificate2 cert2 = new X509Certificate2(cert);string cn = cert2.GetIssuerName();
string cedate = cert2.GetExpirationDateString();Console.WriteLine(cn);
Console.WriteLine(cedate);Console.ReadLine();
}
}
}
A simple #Watchkit app in #ObjectiveC

Yes, I just got an apple watch, and the first thing I want to do with it, is to learn to program on it. so, apart from a simple “Hello World” app. I wanted to create a very simple companion app for a bitcoin app (https://itunes.apple.com/gb/app/get-bitcoin/id1072062149?mt=8) – which just looks up the BTC / USD exchange rate and shows it on the watch.
So, here’s the code;
@interface InterfaceController()
@property (unsafe_unretained, nonatomic) IBOutlet WKInterfaceLabel *lblHello;
@end
@implementation InterfaceController
– (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Configure interface objects here.
[self.lblHello setText:@”Loading…”];
// make request to https://blockchain.info/tobtc?currency=USD&value=1
NSURL *url = [NSURL URLWithString:@”https://blockchain.info/tobtc?currency=USD&value=1″];
NSError* error;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
// Check for network errors
if (error)
{
[self.lblHello setText:@”Network error”];
return;
}
// Get reciprocal
float fRate = [content floatValue];
float fReciprocal = 1 / fRate;
NSString *str = [NSString stringWithFormat:@”$%.2lf”, fReciprocal];
[self.lblHello setText:str];
}
Custom #Email #Autoresponder in c#

I wanted to set up an autoresponder to my emails so that people would get notified over the christmas holidays that I’d be away. But I had quite specific requirements…
I tried http://www.listwire.com/fiach – but it required me to use a different email address, which wasn’t what I wanted.
So, I just coded my own autoresponder, a console app, that runs once a day, gathers emails via POP3, then replies to them using Amazon SES, then deletes the message again.
I set up my own POP3 server using Mailenable, – finding to my annoyance that the autoresponder in MailEnable didn’t work!, but then I went for this code (passwords removed)
using System;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Text;
using Pop3;namespace Autoresponder
{
class Program
{
static void Main(string[] args)
{Pop3Client pop3Client = new Pop3Client( );
pop3Client.Connect(“mail.xxx.com”, “all@xxxx”, “xxx”, false);
var strResponseFile = AppDomain.CurrentDomain.BaseDirectory + “autoresponder.txt”;
var strResponse = (new StreamReader(strResponseFile)).ReadToEnd();
var messages = pop3Client.List( );
foreach ( Pop3Message message in messages )
{
pop3Client.Retrieve( message );try
{
Send(message.From, “Thank you for sending your CV”, strResponse, “noreply@outsourcetranslation.com”);
}
catch
{
}
Console.WriteLine( “MessageId: {0}”, message.MessageId );
Console.WriteLine( “Date: {0}”, message.Date );
Console.WriteLine( “From: {0}”, message.From );
pop3Client.Delete(message);}
pop3Client.Disconnect( );}
/// <summary>
/// Sends the specified recipient with reply to
/// </summary>
/// <param name=”recipient”>The recipient.</param>
/// <param name=”subject”>The subject.</param>
/// <param name=”body”>The body.</param>
/// <param name=”replyTo”>The reply to.</param>
public static void Send(string recipient, string subject, string body, string replyTo)
{
MailMessage mail = new MailMessage(ConfigurationManager.AppSettings[“FROM_ADDRESS”], recipient);
SmtpClient client = new SmtpClient();
client.Port = 25;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = ConfigurationManager.AppSettings[“MAILSERVER”];
client.Credentials = new System.Net.NetworkCredential(
ConfigurationManager.AppSettings[“EMAIL_USERNAME”],
ConfigurationManager.AppSettings[“EMAIL_PASSWORD”]);
mail.Subject = subject;
mail.Body = body;
mail.ReplyToList.Add(replyTo);
mail.BodyEncoding = Encoding.UTF8;
client.Send(mail);
}
}
}
It uses the Nuget package Install-Package Pop3
And I installed this on my server as a scheduled task.
Build a quick #slack #bot in c#

I’m not actually a big fan of Slack, but personal opinions aside, creating a simple slack bot for notifications is super easy to do in C#. I built a File system watcher slack bot, that could notify a custom channel in Slack whenever a new file was uploaded to my server.
You need to log in to Slack and get a slack incoming webhook url, it should look something like this:
https://hooks.slack.com/services/T04XXX/B3HKKXXXXL/4XXXXXW
You can set the name and icon for the bot too via the Web UI, which is nice.
So, the main class, which I found on Github, is as follows
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace SaleWatcherApp
{
//A simple C# class to post messages to a Slack channel
//Note: This class uses the Newtonsoft Json.NET serializer available via NuGet
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
}
It requires Newtonsoft nuget, which you should install now.
Then, I created a console app, that watches my folder of interest. I installed this on the server using NSSM so that the EXE ran as a service.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
namespace SaleWatcherApp
{
class Program
{
static List<string> newFiles = new List<string>();
private static SlackClient slack = null;
static void Main(string[] args)
{
slack = new SlackClient(ConfigurationManager.AppSettings["slackHook"]);
watch();
Console.ReadLine();
}
private static void watch()
{
var watcher = new FileSystemWatcher
{
Path = ConfigurationManager.AppSettings["watchPath"],
NotifyFilter = NotifyFilters.LastWrite,
Filter = "*.*"
};
watcher.Changed += (sender, args) =>
{
if (newFiles.All(f => f != args.Name))
{
Console.WriteLine(args.Name);
slack.PostMessage(args.Name);
}
newFiles.Add(args.Name);
};
watcher.EnableRaisingEvents = true;
}
}
}
#Outsource #Translation website relaunch

OutsourceTranslation.com – is a website we’ve been running for a good few years now, just got a facelift.
#ReCaptcha #Invisible #beta with #Ajax #Jquery

The Google Recaptcha invisible beta isn’t really invisible… you get a logo down in the bottom left hand corner, and it prompts you to select “images of sushi” (or similar), which is more annoying than “I am not a robot”.
I’ve opted to use Ajax and jQuery with it, for more control, so lets see how that’s done – I’ve omitted my keys and the server side code is C# asp.net
Include the script in the head;
then add this div anywhere on the page
And then on the call to action (i.e. search) call:
grecaptcha.execute();
but don’t perform the ajax post yet, wait for recaptcha_callback to be called. Then in the recaptcha_callback, call your back-end script, passing the captcha reponse
var strUrl = “/ajax.aspx”;
$.post(strUrl, {
captcha: grecaptcha.getResponse()
}, function (data) {
// Display your data here
});
On the server side, you need to validate the captcha data as follows;
var captcha = Request.Form[“captcha”];
var webClient = new WebClient();
const string strSecretKey = “YOUR PRIVATE KEY”;
var strUrl = string.Format(“https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}”, strSecretKey, captcha);
string verification = webClient.DownloadString(strUrl);
var jsSerializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
var isOK = jsSerializer.Deserialize<CaptchaObject>(verification).success;
if (isOK)
{
// go look up your data
Response.Write(strJson);
}
Where CaptchaObject is defined as follows
public class CaptchaObject
{
public bool success { get; set; }
public string challenge_ts { get; set; }
public string hostname { get; set; }
}
Prevent #Clickjacking in c# / #asp.net

Clickjacking is when someone loads your website / content in an iFrame without your consent. This may be part of a simple DDOS attack, or to spoof CPC traffic, or to embed your functionality or content without the visitor actually seeing your website.
Modern browsers offer a facility called CSP or “Content-Security-Policy”, which can be added as a HTTP header to prevent this sort of unauthorised activity.
You have different options, i.e.
To prevent all framing of your content use:
Content-Security-Policy: frame-ancestors 'none'
To allow for your site only, use:
Content-Security-Policy: frame-ancestors 'self'
To allow for trusted domain (my-trusty-site.com), do the following:
Content-Security-Policy: frame-ancestors my-trusty-site.com
and in order to add this to your ASP.NET page, (C#) you add the code
Response.Headers.Add(“Content-Security-Policy”, “frame-ancestors customer.website.com”);
#P2p Website marketing portal #SEO #WebsitePromotion

P2P Marketing explained
Peer 2 Peer marketing is where the middle man is removed from the typical advertiser / publisher relationship.
By joining the P2P marketing portal http://www.freewebsitetraffic.club/, you choose to promote websites that are complementary to your own services or products, and in return you gain visibility, giving your website more chance to be discovered and promoted by other members of the club.
Member websites
Once you have registered your website with http://www.freewebsitetraffic.club/, in order to gain visibility, you will need to select one or more of the websites below to promote. The more unique visitors you send to other member’s websites, the more visible your website will become. To protect the impartiality of this service, we do not accept payment in order to promote yourself in this list, you can only do so by promoting other member’s websites.
#EU Reverse #VAT #API – Find a company’s VAT number #VIES

The VAT API is an API that can look up a VAT number from the name of a company based in Europe, or list VAT registered companies within a town , city, or street. You can also use it to verify known VAT numbers, using the VIES service.
JSON interface
Example: http://www.vatapi.co.uk/api.aspx?Name=Microsoft
Request VAT data via JSON
Parameters:
| Name | Meaning |
| Name | The name of the company being searched
|
| City | The address of the company being searched
|
| Vat | The VAT number to be verified
|
| Country | The ISO3166 Country code, i.e. GB
|
Sample response:
[
{
“VatNumber”: “CZ 47123737”,
“LegalName”: “Microsoft s.r.o.”,
“Address”: “Vysko\u010dilova 1561\/4a, Praha 4 – Michle, 140 00 Praha 4”
},
{
“VatNumber”: “GB 724594615”,
“LegalName”: “Microsoft Limited”,
“Address”: “Fao Carolyn Cheney, Microsoft Limited, Microsoft Campus, Reading, RG6 1WG”
},
{
“VatNumber”: “NL 007747366B01”,
“LegalName”: “Microsoft B.V.”,
“Address”: “Evert Van De Beekstraat 00354, 1118Cz Schiphol”
},
{
“VatNumber”: “IT 08106710158”,
“LegalName”: “Microsoft S.R.L.”,
“Address”: “Via Lombardia 2\/A-1, 20068 Peschiera Borromeo (MI)”
},
{
“VatNumber”: “FI 08974643”,
“LegalName”: “Microsoft Oy”,
“Address”: “FIN-02150 Espoo, Finland, Keilalahdentie 2-4”
},
{
“VatNumber”: “IE 9811916F”,
“LegalName”: “Microsoft Payments”,
“Address”: “Carmanhall Road, Sandyford Industrial Estate, Dublin 18”
},
{
“VatNumber”: “BE 0437910359”,
“LegalName”: “NV Microsoft”,
“Address”: “Da Vincilaan 3, 1930 Zaventem”
},
{
“VatNumber”: “NO 991036156”,
“LegalName”: “Microsoft Domains Norge AS”,
“Address”: “NO-1366 Lysaker, Lysaker torg 45”
},
{
“VatNumber”: “SI 63458756”,
“LegalName”: “Microsoft D.O.O., Ljubljana”,
“Address”: “Ameri\u0161ka Ulica 8, 1000 Ljubljana”
},
{
“VatNumber”: “GB 642353552”,
“LegalName”: “Microsoft Research Limited”,
“Address”: “21 Station Road, Cambridge, CB1 2FB”
}
]
XML interface
Example: http://www.vatapi.co.uk/api.asmx/Search?name=Microsoft&city=
Request VAT data via XML
If you are using a .NET environment, or are more familiar with XML / SOAP, then you can make a web service reference to the WSDL – here http://www.vatapi.co.uk/api.asmx?wsdl
There are two methods
- Search
This is to look up the VAT number of a company when you only know its name, or location.
This works in Austria, Switzerland, Great Britain, Ireland, Italy, France, Belgium, Holland, Luxembourg, Denmark, Norway, Finland, Czech Republic, Hungary, Slovenia, Greece, and Malta - Verify
This is when you want to verify the VAT number of a company, and find it’s legal name and address. This works in all european countries.
Sample response:
<?xml version=”1.0″ encoding=”utf-8″?>
<ArrayOfOrganisation xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://vatapi.co.uk/”>
<Organisation>
<VatNumber>CZ 47123737</VatNumber>
<LegalName>Microsoft s.r.o.</LegalName>
<Address>Vyskočilova 1561/4a, Praha 4 – Michle, 140 00 Praha 4</Address>
</Organisation>
<Organisation>
<VatNumber>GB 724594615</VatNumber>
<LegalName>Microsoft Limited</LegalName>
<Address>Fao Carolyn Cheney, Microsoft Limited, Microsoft Campus, Reading, RG6 1WG</Address>
</Organisation>
<Organisation>
<VatNumber>NL 007747366B01</VatNumber>
<LegalName>Microsoft B.V.</LegalName>
<Address>Evert Van De Beekstraat 00354, 1118Cz Schiphol</Address>
</Organisation>
<Organisation>
<VatNumber>IT 08106710158</VatNumber>
<LegalName>Microsoft S.R.L.</LegalName>
<Address>Via Lombardia 2/A-1, 20068 Peschiera Borromeo (MI)</Address>
</Organisation>
<Organisation>
<VatNumber>FI 08974643</VatNumber>
<LegalName>Microsoft Oy</LegalName>
<Address>FIN-02150 Espoo, Finland, Keilalahdentie 2-4</Address>
</Organisation>
<Organisation>
<VatNumber>IE 9811916F</VatNumber>
<LegalName>Microsoft Payments</LegalName>
<Address>Carmanhall Road, Sandyford Industrial Estate, Dublin 18</Address>
</Organisation>
<Organisation>
<VatNumber>BE 0437910359</VatNumber>
<LegalName>NV Microsoft</LegalName>
<Address>Da Vincilaan 3, 1930 Zaventem</Address>
</Organisation>
<Organisation>
<VatNumber>NO 991036156</VatNumber>
<LegalName>Microsoft Domains Norge AS</LegalName>
<Address>NO-1366 Lysaker, Lysaker torg 45</Address>
</Organisation>
<Organisation>
<VatNumber>SI 63458756</VatNumber>
<LegalName>Microsoft D.O.O., Ljubljana</LegalName>
<Address>Ameriška Ulica 8, 1000 Ljubljana</Address>
</Organisation>
<Organisation>
<VatNumber>GB 642353552</VatNumber>
<LegalName>Microsoft Research Limited</LegalName>
<Address>21 Station Road, Cambridge, CB1 2FB</Address>
</Organisation>
</ArrayOfOrganisation>