Archive

Archive for December, 2016

Custom #Email #Autoresponder in c#

6033_menu_pic_2

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.

Categories: Uncategorized

Build a quick #slack #bot in c#

slackbot-featured1

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;
        }  
    }
}
Categories: Uncategorized

#Outsource #Translation website relaunch

frontpage

OutsourceTranslation.com – is a website we’ve been running for a good few years now, just got a facelift.

Categories: Uncategorized

#ReCaptcha #Invisible #beta with #Ajax #Jquery

invisblerecaptcha

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;

https://www.google.com/recaptcha/api.js

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; }
}

 

Categories: Uncategorized

Prevent #Clickjacking in c# / #asp.net

csp_shield_logo-509x270

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”);

Categories: Uncategorized

#P2p Website marketing portal #SEO #WebsitePromotion

fwc

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.

Categories: Uncategorized

#EU Reverse #VAT #API – Find a company’s VAT number #VIES

vatapi

http://www.vatapi.co.uk

 

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

  • Partial matches are ok
City The address of the company being searched

  • Partial matches are ok
Vat The VAT number to be verified

  • Optional, for verification only
Country The ISO3166 Country code, i.e. GB

  • Required only if VAT is provided

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&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://vatapi.co.uk/”&gt;

 <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>

 

 

Categories: Uncategorized

#Paypal #IPN vulnerability – and how to fix it.

paypal-earnings

The other day, I got a notification of a paypal payment for £0.01, which was odd, but I didn’t realise the significance until a few days later, when I realised that someone had managed to buy 800 euros of credit for only £0.01

The hack was, that the user modified the payment link to change the price, by changing the amount parameter:

https://www.paypal.com/cgi-bin/webscr?…&amount=800

to

https://www.paypal.com/cgi-bin/webscr?…&amount=0.01

But left the “custom” field the same, which typically indicates the basket ID. When the IPN callback was called, it was passed the correct basket ID, but an incorrect mc_gross value. This lead to the user being credited with 800 euros worth, but only paying £0.01

A similar hack could have been done by changing the currency from GBP to JPY.

Simple fix:

In the IPN callback check that the mc_gross and mc_currency matches the expected total in the basket, or include a salted hash of the amount and currency in the custom field

PS: This issue has now been fixed on our website, don’t even bother trying this hack! 🙂

 

Categories: Uncategorized

H4sIAAA What’s so important about this string?

my_tweet

This may be a long shot, but if anyone ever searches for this string, I know exactly what you are looking at – It’s a base64 encoded zipped string.

Want to see what it actually it, base64 decode the sting, and unzip the result, here’s the code you need in c#

public static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];

int cnt;

while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}

public static byte[] Zip(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);

using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
//msi.CopyTo(gs);
CopyTo(msi, gs);
}

return mso.ToArray();
}
}

public static string Unzip(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
//gs.CopyTo(mso);
CopyTo(gs, mso);
}

return Encoding.UTF8.GetString(mso.ToArray());
}
}

Categories: Uncategorized

#Parse #JSON in MS #SQL server @procurios

aaeaaqaaaaaaaacvaaaajdg4mwqwmtbjltayyjitndaxmy1imtq2lwu1ztazmte4nzm0yw

If your application stores data in SQL server as a JSON value, you will find it difficult to read out individual properties on this data. This means that you can’t do joins on fields that are held within the data, or any aggregate queries. It’s just not flexible at all.

So, as the name suggests, I’ve used a C# CLR UDF (User defined function) to do this, where it takes in the string, processes it within the CLR and returns it to SQL server.

To give you a few “anti-patterns” of things that don’t work. You may find that SQL server only supports a limited set of .NET assemblies, so you can’t import Newtonsoft to handle the JSON, nor can you use System.Runtime.Serialization, which is not allowed by SQL server either. So I had to use a home grown JSON parser, by Procurios (http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-(for-json).html) – thanks @procurios

So, creating a new CLR Project in Visual Studio, I added the procurios JSON class, and this code;

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString CLR_ReadJSON(string json, string property)
{
var o = JSON.JsonDecode(json) as Hashtable;
return o[property].ToString();
}

I compiled the DLL, transferred it to the server, and added a new Assembly, which I’ve called CLR_DataTools (The above code was in a namespace called StoredProcedures)

Then I wrote the following SQL code to define the UDF

CREATE FUNCTION [dbo].[CLR_UdfReadJson]
(
@json [nvarchar](4000),
@property [nvarchar](4000)
)
RETURNS nvarchar(max)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [CLR_DataTools].[StoredProcedures].[CLR_ReadJSON]
GO

And that’s all you need! (Although this took me a few hours to figure out)

As an aside, here’s some code I wrote to handle XPath queries on XML within SQL server, but I am aware that there are better ways to do this;

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString CLR_ReadXML(string xml, string xPath)
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
var xn = xdoc.DocumentElement.SelectSingleNode(xPath);
var strXml = xn.InnerXml;
return strXml;
}

and then defined the SQL UDF as follows;

CREATE FUNCTION [dbo].[CLR_UdfReadXML]
(
@xml [nvarchar](4000),
@xPath [nvarchar](4000)
)
RETURNS nvarchar(max)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [CLR_DataTools].[StoredProcedures].[CLR_ReadXML]
GO

 

Categories: Uncategorized