Archive

Archive for December, 2016

Custom #Email #Autoresponder in c#

December 23, 2016 Leave a comment

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.

Advertisements
Categories: Uncategorized

Build a quick #slack #bot in c#

December 22, 2016 Leave a comment

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

December 21, 2016 Leave a comment

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

December 15, 2016 Leave a comment

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

December 15, 2016 Leave a comment

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

December 12, 2016 Leave a comment

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

December 9, 2016 Leave a comment

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