Skip to content

Instantly share code, notes, and snippets.

@vicentedealencar
Created November 4, 2014 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vicentedealencar/598ecdb1265cfd4874b9 to your computer and use it in GitHub Desktop.
Save vicentedealencar/598ecdb1265cfd4874b9 to your computer and use it in GitHub Desktop.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNamespace
{
public class ProtocolController
{
public static readonly string ExecutingAssemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
public string Protocol { get; set; }
public Dictionary<string, Action<Dictionary<string, string>>> Actions { get; set; }
public ProtocolController(string protocol)
{
this.Protocol = protocol;
this.Actions = new Dictionary<string, Action<Dictionary<string, string>>>();
}
private void RegisterProtocol()
{
try
{
RegistryKey regKey = Registry.ClassesRoot.CreateSubKey(this.Protocol);
regKey.SetValue("", "URL:" + this.Protocol + " Protocol");
regKey.SetValue("URL Protocol", "");
RegistryKey defaultIcon = regKey.CreateSubKey("DefaultIcon");
defaultIcon.SetValue("", Path.GetFileName(ExecutingAssemblyLocation));
regKey.CreateSubKey("shell")
.CreateSubKey("open")
.CreateSubKey("command")
.SetValue("", ExecutingAssemblyLocation + " %1");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("ERRO");
throw;
}
}
private void RunUrl(string url)
{
url = url.ToLower();
var uri = new Uri(url);
var protocol = uri.Scheme;
var action = uri.LocalPath;
var parameters = uri.Query.Remove(0, 1).Split('&').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);
this.Actions[action](parameters);
}
public void Run()
{
Console.WriteLine("running " + this.Protocol);
var arguments = Environment.GetCommandLineArgs();
if (arguments.Length > 1 && arguments[1].Contains(this.Protocol))
{
Console.WriteLine("running " + arguments[1]);
RunUrl(arguments[1]);
}
else
{
Console.WriteLine("Instalando");
RegisterProtocol();
Console.WriteLine("Instalado com sucesso");
}
}
}
}
@vicentedealencar
Copy link
Author

Usage

var controller = new ProtocolController("myprotocol");

//myprotocol:myaction?email=asd@qwe.com
controller.Actions.Add("myaction", p => Console.WriteLine(p["email"])); 

controller.Run();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment