Monthly Archives: September 2014

Simple PHP Proxy

<?php
    function download($url) {
        $curl = curl_init($url);
        curl_setopt_array($curl, [
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_RETURNTRANSFER => true
        ]);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
    
    function getFileName($url) {
        $fileName = basename(parse_url($url, PHP_URL_PATH));
        return empty($fileName) ? "data" : $fileName;
    }
    
    $url = trim($_GET["url"]);
    if (!empty($url)) {
        $data = gzencode(download($url));
        header("Content-Type: application/gzip");
        header(sprintf("Content-Length: %d", strlen($data)));
        header(sprintf("Content-Disposition: attachment; filename=%s.gz", getFileName($url)));
        print($data);
        return;
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Proxy</title>
    </head>
    <body>
        <form action="<?= $_SERVER["SCRIPT_NAME"] ?>" method="get">
            <label>
                URL:
                <input type="text" name="url" size="50" />
            </label>
            <input type="submit" value="Download" />
        </form>
    </body>
</html>

NoSleep

User32.cs:

using System;
using System.Runtime.InteropServices;

namespace NoSleep
{
    static class User32
    {
        public const uint INPUT_MOUSE = 0;
        public const uint MOUSEEVENTF_MOVE = 0x0001;

        [StructLayout(LayoutKind.Sequential)]
        public struct MOUSEINPUT
        {
            public int dx;
            public int dy;
            public uint mouseData;
            public uint dwFlags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct INPUT
        {
            public uint type;
            public MOUSEINPUT mi;
        }

        [DllImport("user32.dll")]
        public static extern IntPtr GetMessageExtraInfo();

        [DllImport("user32.dll")]
        public static extern uint SendInput(uint cInputs, INPUT[] pInputs, int cbSize);

        public static void MoveMouse(int dx, int dy)
        {
            INPUT[] pInputs = new INPUT[]
            {
                new INPUT
                {
                    type = INPUT_MOUSE,
                    mi = new MOUSEINPUT
                    {
                        dx = dx,
                        dy = dy,
                        mouseData = 0,
                        dwFlags = MOUSEEVENTF_MOVE,
                        time = 0,
                        dwExtraInfo = GetMessageExtraInfo()
                    }
                }
            };
            SendInput(1, pInputs, Marshal.SizeOf(typeof(INPUT)));
        }
    }
}

App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="Distance" value="10" />
    <add key="Timeout" value="1:00" />
  </appSettings>
</configuration>

Configuration.cs:

using System;
using System.Configuration;

namespace NoSleep
{
    static class Configuration
    {
        public static int Distance
        {
            get
            {
                int distance;
                bool valid = int.TryParse(ConfigurationManager.AppSettings["Distance"], out distance);
                return valid ? distance : 10;
            }
        }

        public static TimeSpan Timeout
        {
            get
            {
                TimeSpan timeout;
                bool valid = TimeSpan.TryParseExact(ConfigurationManager.AppSettings["Timeout"], @"m\:s", null, out timeout);
                return valid ? timeout : TimeSpan.FromMinutes(1.0);
            }
        }
    }
}

Program.cs:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace NoSleep
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle done = new ManualResetEvent(false);
            Task.Factory.StartNew(WaitForKeyPress).ContinueWith(task => done.Set());
            JiggleMouse(done);
        }

        private static void WaitForKeyPress()
        {
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(true);
        }

        private static void JiggleMouse(EventWaitHandle done)
        {
            bool moveRight = true;
            while (!done.WaitOne(Configuration.Timeout))
            {
                int dx = (moveRight ? 1 : -1) * Configuration.Distance;
                User32.MoveMouse(dx, 0);
                moveRight = !moveRight;
            }
        }
    }
}

Custom .NET Configuration Sections

App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="presidents1" type="System.Configuration.NameValueSectionHandler" />
    <section name="presidents2" type="CustomConfig.PresidentListSection, Custom Config" />
  </configSections>
  <presidents1>
    <add key="1" value="George Washington" />
    <add key="2" value="John Adams" />
    <add key="3" value="Thomas Jefferson" />
    <add key="4" value="James Madison" />
    <add key="5" value="James Monroe" />
    <add key="6" value="John Quincy Adams" />
    <add key="7" value="Andrew Jackson" />
    <add key="8" value="Martin Van Buren" />
    <add key="9" value="William Henry Harrison" />
    <add key="10" value="John Tyler" />
  </presidents1>
  <presidents2>
    <add order="1" firstName="George" lastName="Washington" />
    <add order="2" firstName="John" lastName="Adams" party="Federalist" />
    <add order="3" firstName="Thomas" lastName="Jefferson" party="Democratic-Republican" />
    <add order="4" firstName="James" lastName="Madison" party="Democratic-Republican" />
    <add order="5" firstName="James" lastName="Monroe" party="Democratic-Republican" />
    <add order="6" firstName="John Quincy" lastName="Adams" party="Democratic-Republican" />
    <add order="7" firstName="Andrew" lastName="Jackson" party="Democratic" />
    <add order="8" firstName="Martin" lastName="Van Buren" party="Democratic" />
    <add order="9" firstName="William Henry" lastName="Harrison" party="Whig" />
    <add order="10" firstName="John" lastName="Tyler" party="Whig" />
  </presidents2>
</configuration>

PresidentListSection.cs:

using System.ComponentModel;
using System.Configuration;

namespace CustomConfig
{
    class PresidentListSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection = true)]
        [ConfigurationCollection(typeof(PresidentList))]
        public PresidentList List
        {
            get { return (PresidentList)base[""]; }
        }
    }

    class PresidentList : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new President();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((President)element).Order;
        }
    }

    class President : ConfigurationElement
    {
        [ConfigurationProperty("order", IsKey = true, IsRequired = true)]
        public int Order
        {
            get { return (int)base["order"]; }
        }

        [ConfigurationProperty("firstName", IsRequired = true)]
        public string FirstName
        {
            get { return (string)base["firstName"]; }
        }

        [ConfigurationProperty("lastName", IsRequired = true)]
        public string LastName
        {
            get { return (string)base["lastName"]; }
        }

        [ConfigurationProperty("party", IsRequired = false)]
        [TypeConverter(typeof(PartyConverter))]
        public Party Party
        {
            get { return (Party)base["party"]; }
        }
    }
}

Party.cs:

using System;
using System.ComponentModel;
using System.Globalization;

namespace CustomConfig
{
    enum Party
    {
        [Description("None")]
        None,

        [Description("Democratic")]
        Democratic,

        [Description("Democratic-Republican")]
        DemocraticRepublican,

        [Description("Federalist")]
        Federalist,

        [Description("Whig")]
        Whig
    }

    class PartyConverter : EnumConverter
    {
        public PartyConverter() : base(typeof(Party)) { }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (!(value is string))
            {
                return base.ConvertFrom(context, culture, value);
            }
            return value == null ? Party.None : EnumExtensions.GetValue(typeof(Party), (string)value);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string) ? true : base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType != typeof(string))
            {
                return base.ConvertTo(context, culture, value, destinationType);
            }
            return EnumExtensions.GetDescription((Party)value);
        }
    }
}

EnumExtensions.cs:

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace CustomConfig
{
    static class EnumExtensions
    {
        private static string GetDescription(FieldInfo field)
        {
            object attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false).First();
            return ((DescriptionAttribute)attribute).Description;
        }

        public static string GetDescription(Enum value)
        {
            return GetDescription(value.GetType().GetField(value.ToString()));
        }

        public static Enum GetValue(Type type, string description)
        {
            return (Enum)type.GetFields(BindingFlags.Public | BindingFlags.Static)
                .First(field => GetDescription(field) == description)
                .GetValue(null);
        }
    }
}

Program.cs:

using System;
using System.Collections.Specialized;
using System.Configuration;

namespace CustomConfig
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadPresidents1();
            ReadPresidents2();
        }

        private static void ReadPresidents1()
        {
            NameValueCollection presidents1 = (NameValueCollection)ConfigurationManager.GetSection("presidents1");
            foreach (string order in presidents1)
            {
                Console.WriteLine("{0}: {1}", order, presidents1[order]);
            }
        }

        private static void ReadPresidents2()
        {
            PresidentListSection presidents2 = (PresidentListSection)ConfigurationManager.GetSection("presidents2");
            foreach (President president in presidents2.List)
            {
                Console.WriteLine(
                    "{0}: {1} {2} ({3})",
                    president.Order,
                    president.FirstName,
                    president.LastName,
                    EnumExtensions.GetDescription(president.Party));
            }
        }
    }
}

Output:

1: George Washington
2: John Adams
3: Thomas Jefferson
4: James Madison
5: James Monroe
6: John Quincy Adams
7: Andrew Jackson
8: Martin Van Buren
9: William Henry Harrison
10: John Tyler
1: George Washington (None)
2: John Adams (Federalist)
3: Thomas Jefferson (Democratic-Republican)
4: James Madison (Democratic-Republican)
5: James Monroe (Democratic-Republican)
6: John Quincy Adams (Democratic-Republican)
7: Andrew Jackson (Democratic)
8: Martin Van Buren (Democratic)
9: William Henry Harrison (Whig)
10: John Tyler (Whig)

Providing an XML schema definition is optional, but it gives you IntelliSense and prevents Visual Studio from complaining about missing schema information.

PresidentListSection1.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="presidents1">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="add" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="key" type="xs:string" use="required" />
            <xs:attribute name="value" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

PresidentListSection2.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="partyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="Democratic" />
      <xs:enumeration value="Democratic-Republican" />
      <xs:enumeration value="Federalist" />
      <xs:enumeration value="Whig" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="presidents2">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="add" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="order" type="xs:int" use="required" />
            <xs:attribute name="firstName" type="xs:string" use="required" />
            <xs:attribute name="lastName" type="xs:string" use="required" />
            <xs:attribute name="party" type="partyType" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>