The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,111 other followers

.NET/C# small program that shows you your proxy settings, demonstrates LINQ to Registry, and String.Contains

Posted by jpluimers on 2013/03/05

I’ve been working at a client where they have hardened most of their systems in a not so programmer friendly way. One of the things you cannot to is start RegEdit, not even for viewing. Since I need Fiddler2 to poke through their Internet Proxy in order to get access to an external TFS server, and their machines often reboot due to maintenance cycles, sometimes my proxy settings are dead. This tiny app shows you how to get display your proxy settings, demonstrating:

Enjoy! (Note, you could have done this with PowerShell in a very easy way too, as it access the Registry just like it was a file system).

When using Fiddler, it shows output like this:

AutoConfigProxy=wininet.dll
ProxyEnable=1
MigrateProxy=1
ProxyHttp1.1=1
ProxyOverride=<-loopback>
ProxyServer=http=127.0.0.1:8888;https=127.0.0.1:8888;

LINQ to Registry

One of the drawbacks of Registry work is that you need to dispose of your keys. That is handled inside ReadOnlyAccessToRegistryKey.Run which also handles your Code Access Security. This means that the lambda expression (could just as well have been an anonymous method) can just concentrate on the LINQ stuffreturning an enumeration of anonymous types. You need the ‘let’ portion if you also want to perform ‘where’ on the values.

using System;
using System.Collections.Generic;
using System.Linq;
using BeSharp.Win32;
using Microsoft.Win32;

namespace LinqToRegistryShowProxySettings
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }

        static void run()
        {
            const string internetSettingsKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";

            ReadOnlyAccessToRegistryKey.Run(Registry.CurrentUser, internetSettingsKey,
                registryKey =>
                {
                    var keyValues = from name
                                 in registryKey.GetValueNames()
                                    //let keyValue = new { key = name, value = registryKey.GetValue(name).ToString() } // only if you need the Value in the Where, as it created for all occurences
                                    where
                                    name.Contains("proxy", StringComparison.OrdinalIgnoreCase) ||
                                    name.Contains("autoConfig", StringComparison.OrdinalIgnoreCase)
                                    select new { key = name, value = registryKey.GetValue(name).ToString() };

                    foreach (var keyValue in keyValues)
                    {
                        Console.WriteLine("{0}={1}", keyValue.key, keyValue.value);
                    }
                }
            );

        }
    }
}

ReadOnlyAccessToRegistryKey

This manages the Code Access Security since you will access the registry readonly. It also disposes the RegistryKey instance. The Code Access Security access and revert must be in the same method, so you cannot create a class that does the Assert in the constructor, and the dispose in the Disposer.

using System;
using Microsoft.Win32;
using System.Security.Permissions;
using System.Security;

namespace BeSharp.Win32
{
    public class ReadOnlyAccessToRegistryKey
    {
        public static void Run(RegistryKey hiveRegistryKey, string subKeyName, Action action)
        {
            string fullKeyName = hiveRegistryKey.Combine(subKeyName);
            RegistryPermission readRegistryPermission = new RegistryPermission(RegistryPermissionAccess.Read, fullKeyName);
            readRegistryPermission.Assert();
            try
            {
                using (RegistryKey registryKey = hiveRegistryKey.OpenSubKey(subKeyName))
                {
                    action(registryKey);
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
    }
}

Extensions for the Registry:

  • easy way to get the full names for HKLM, HKCU, etc.
  • Combine key names (and insert \ between them)
  • implements a Contains method for strings (thanks to StackOverflow); should be in a separate class, will do that in the library.
using System;
using Microsoft.Win32;

namespace BeSharp.Win32
{
    public static class RegistryExtensions
    {
        // Hives: http://en.wikipedia.org/wiki/Windows_Registry
        public readonly static string HKCC = Registry.CurrentConfig.Name;
        public readonly static string HKCR = Registry.ClassesRoot.Name;
        public readonly static string HKCU = Registry.CurrentUser.Name;
#if Obsolete
        [Obsolete]
        public readonly static string HKDD = Registry.DynData.Name;
#endif
        public readonly static string HKLM = Registry.LocalMachine.Name;
        public readonly static string HKPD = Registry.PerformanceData.Name;
        public readonly static string HKU = Registry.Users.Name;

        public static string Combine(this string keyName, string subKeyName)
        {
            string result = string.Format(@"{0}\{1}", keyName, subKeyName);
            return result;
        }

        public static string Combine(this RegistryKey registryKey, string subKeyName)
        {
            string result = registryKey.Name.Combine(subKeyName);
            return result;
        }

        public static string Combine(this RegistryKey registryKey, RegistryKey subRegistryKey)
        {
            return registryKey.Combine(subRegistryKey.Name);
        }

        //http://stackoverflow.com/questions/444798/case-insensitive-containsstring/444818#444818

        public static bool Contains(this string value, string substring, StringComparison stringComparison = StringComparison.CurrentCulture)
        {
            int index = value.IndexOf(substring, stringComparison);
            bool result = (index >= 0);
            return result;
        }
    }
}

–jeroen

2 Responses to “.NET/C# small program that shows you your proxy settings, demonstrates LINQ to Registry, and String.Contains”

  1. wsp90 said

    Reblogged this on VB .NET Tutorial .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: