Export Registry in C#

I wanted to export registry in C# .Net project. First of all I noticed that the Microsoft.Win32.Registry doesnt’ provide this function.
I’ve searched a web and found VB.NET implementation at http://www.controlled-insanity.com/Forum/viewtopic.php?p=58715&sid=6cb99f5471bc3e916896443cd0f9f26e.


Unfortunately the code calls a few functions that were not included on the page and I wrote  ( or copied from others web sites) them to make the code compilable.


Because my particular project is in C# and I didn’t want to have additional DLL, I used .Net Reflector to convert VB class to C#.
A few disasssembled functions in C# were not compilable and looked very ugly.


I’ve noticed that vb On Error Resume Next  causes  .Net Reflector  to generate not compilable C# code.


So I commented out On Error Resume Next  , which is a good idea anyway, recompile VB code and disaccemble it as C# code, fixed some VB/C# discrepencies and make the C# class working.


At the end I understood that to export the registry the class I just need to Process.Start regedit.exe with corresponding parameters, so I didn’t need most of the code.


However I will post the whole class here. Note that I  tested only ExportKey method of the class.


 


//’http://www.controlled-insanity.com/Forum/viewtopic.php?p=58715&sid=6cb99f5471bc3e916896443cd0f9f26e


namespace ModRegistry


{


    using Microsoft.VisualBasic;


    using Microsoft.VisualBasic.CompilerServices;


    using Microsoft.Win32;


    using System;


    using System.Diagnostics;


    using System.IO;


    using System.Runtime.InteropServices;


    using System.Text;


 


//   [StandardModule]


    public sealed class RegistryHelper


    {


 


            //    ‘Just a wee bit of API to fill the gaps not covered by .NET‘s registry access


            //    ‘Used to determine a value’s type and read/write strings of the type REG_EXPAND_SZ


            [DllImport(“advapi32.dll”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int RegCloseKey(int hKey);


 


            [DllImport(“advapi32.dll”, EntryPoint=”RegCreateKeyA”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int RegCreateKey(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpSubKey, ref int phkResult);


 


            [DllImport(“advapi32.dll”, EntryPoint=”RegOpenKeyA”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int RegOpenKey(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpSubKey, ref int phkResult);


 


            [DllImport(“advapi32.dll”, EntryPoint=”RegQueryValueExA”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int RegQueryValueEx(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName, int lpReserved, ref int lpType, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpData, ref int lpcbData);


 


            [DllImport(“advapi32.dll”, EntryPoint=”RegSetValueExA”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int RegSetValueEx(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName, int Reserved, int dwType, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpData, int cbData);


 


 


            // Methods


 


        public static bool CreateKey(RegistryKey hKey, string strPath, string NewKeyName)


        {


            bool flag1=false;


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                key1.CreateSubKey(NewKeyName);


                key1.Close();


                flag1 = true;


            }


            return flag1;


        }


 


        public static bool DeleteKey(RegistryKey hKey, string strPath)


        {


            bool flag1=false;


            int num1=0;


             int num2=0;


            try


            {


                ProjectData.ClearProjectError();


                num2 = 1;


                hKey.DeleteSubKeyTree(strPath);


                flag1 = true;


            }


            catch (Exception obj1) //when (?)


            {


                Exception exception2 = (Exception) obj1;


                ProjectData.SetProjectError(exception2);


                Exception exception1 = exception2;


                if (num1 == 0)


                {


                    num1 = -1;


                    switch (num2)


                    {


                        case 1:


                        {


                            goto Label_0058;


                        }


                    }


                    throw;


                }


            }


        Label_0058:


            if (num1 != 0)


            {


                ProjectData.ClearProjectError();


            }


            return flag1;


        }


 


        public static bool DeleteValue(RegistryKey hKey, string strPath, string strValue)


        {


            bool flag1=false;


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                key1.DeleteValue(strValue);


                key1.Close();


                flag1 = true;


            }


            return flag1;


        }


 


        public static void ExportKey(RegistryKey rKey, string sfile)


        {


            RegistryHelper.ExportKey(rKey.Name, sfile);


        }


 


        public static void ExportKey(string sRegKeyPath, string sfile)


        {


            string text1 = “”” + sRegKeyPath + “””;


            RegistryHelper.FileAppend(sfile, “”);


            RegistryHelper.ShellFile(“regedit.exe”, “/E ” + RegistryHelper.GetDosPath(sfile) + ” ” + text1, ProcessWindowStyle.Normal);


        }


 


        public static void ExportKey(RegistryKey hKey, string strPath, string sfile)


        {


            string text1=””;


            if (hKey == Registry.ClassesRoot)


            {


                text1 = @”HKEY_CLASSES_ROOT”;


            }


            else if (hKey == Registry.CurrentUser)


            {


                text1 = @”HKEY_CURRENT_USER”;


            }


            else if (hKey == Registry.LocalMachine)


            {


                text1 = @”HKEY_LOCAL_MACHINE”;


            }


            else if (hKey == Registry.Users)


            {


                text1 = @”HKEY_USERS”;


            }


            else if (hKey == Registry.CurrentConfig)


            {


                text1 = @”HKEY_CURRENT_CONFIG”;


            }


            else if (hKey == Registry.DynData)


            {


                text1 = @”HKEY_DYN_DATA“;


            }


            else if (hKey == Registry.PerformanceData)


            {


                text1 = @”HKEY_PERFORMANCE_DATA“;


            }


            RegistryHelper.ExportKey(text1, sfile);


//                FileAppend(sfile, “”)


//        ‘mPath = Microsoft.VisualBasic.ControlChars.Quote & mPath & strPath & Microsoft.VisualBasic.ControlChars.Quote


//        ‘ShellFile(“regedit.exe”, “/E ” & GetDosPath(sfile) & ” ” & mPath, 0)


        }


 


            public static string[] GetAllKeys(RegistryKey hKey, string strPath)


            {


                  string[] textArray1=null;


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 != null)


                  {


                        textArray1 = key1.GetSubKeyNames();


                        key1.Close();


                  }


                  return textArray1;


            }


 


 


 


            public static bool GetAllValues(RegistryKey hKey, string strPath, ref string[] mNames)


            {


                  bool flag1=false;


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 != null)


                  {


                        mNames = key1.GetValueNames();


                        flag1 = true;


                        key1.Close();


                  }


                  return flag1;


            }


 


 


        public static string GetDosPath(string path)


        {


            return RegistryHelper.GetShortFileName(path);


        }


 


        public static void GetRootKeyAndPath(string FullPath, ref RegistryKey Rootkey, ref string strPath)


        {


            if ((FullPath.Length != 0) && (FullPath.IndexOf(@””) != -1))


            {


                string[] textArray1 = Strings.Split(FullPath, @””, -1, CompareMethod.Binary);


                string text1 = RegistryHelper.AddBackslash(FullPath, @””);


//        ‘tmp(0) is “My Computer”


//        ‘tmp(1) is the “Root” key – eg. “HKEY_CLASSES_ROOT”


                strPath = text1.Replace(textArray1[0] + @”” + textArray1[1] + @””, “”);


//        ‘strPath is the path of the subkey


                string text2 = textArray1[1];//Determine the “Root” key


                if (StringType.StrCmp(text2, “HKEY_CLASSES_ROOT”, false) == 0)


                {


                    Rootkey = Registry.ClassesRoot;


                }


                else if (StringType.StrCmp(text2, “HKEY_CURRENT_USER”, false) == 0)


                {


                    Rootkey = Registry.CurrentUser;


                }


                else if (StringType.StrCmp(text2, “HKEY_LOCAL_MACHINE”, false) == 0)


                {


                    Rootkey = Registry.LocalMachine;


                }


                else if (StringType.StrCmp(text2, “HKEY_USERS”, false) == 0)


                {


                    Rootkey = Registry.Users;


                }


                else if (StringType.StrCmp(text2, “HKEY_CURRENT_CONFIG”, false) == 0)


                {


                    Rootkey = Registry.CurrentConfig;


                }


                else if (StringType.StrCmp(text2, “HKEY_DYNDATA”, false) == 0)


                {


                    Rootkey = Registry.DynData;


                }


                else if (StringType.StrCmp(text2, “HKEY_PERFORMANCE_DATA“, false) == 0)


                {


                    Rootkey = Registry.PerformanceData;


                }


                strPath = RegistryHelper.RemoveBackslash(strPath);


            }


        }


 


        public static string GetRootKeyString(string FullPath)


        {


            string[] textArray1 = Strings.Split(FullPath, @””, -1, CompareMethod.Binary);


            return textArray1[1];


        }


            public static string GetSafeKeyName(RegistryKey hKey, string strPath, string NewName, [Optional] bool AsNew /* = false */)


            {


                  string text1=””;


                  int num1 = 1;


                  string text2 = NewName;


                  if (AsNew)


                  {


                        text2 = “New Key”;


                        NewName = “New Key #1”;


                  }


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 == null)


                  {


                        return text1;


                  }


                  if (key1.SubKeyCount > 0)


                  {


                        string[] textArray1 = key1.GetSubKeyNames();


                        while (true)


                        {


                              bool flag1=false;


                              int num3 = key1.SubKeyCount – 1;


                              for (int num2 = 0; num2 <= num3; num2++)


                              {


                                    if (StringType.StrCmp(textArray1[num2], NewName, false) == 0)


                                    {


                                          flag1 = true;


                                          break;


                                    }


                              }


                              if (!flag1)


                              {


                                    text1 = NewName;


                                    goto Label_0096;


                              }


                              num1++;


                              flag1 = false;


                              NewName = text2 + ” #” + StringType.FromInteger(num1);


                        }


                  }


                  text1 = NewName;


                  Label_0096:


                        key1.Close();


                  return text1;


            }


 


 


 


            public static string GetSafeValueName(RegistryKey hKey, string strPath, string NewName, [Optional] bool AsNew /* = false */)


            {


                  string text1=””;


                  int num1 = 1;


                  string text2 = NewName;


                  if (AsNew)


                  {


                        text2 = “New Value”;


                        NewName = “New Value #1”;


                  }


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 == null)


                  {


                        return text1;


                  }


                  if (key1.ValueCount > 0)


                  {


                        string[] textArray1 = key1.GetValueNames();


                        while (true)


                        {


                              bool flag1=false;


                              int num3 = key1.ValueCount – 1;


                              for (int num2 = 0; num2 <= num3; num2++)


                              {


                                    if (StringType.StrCmp(textArray1[num2], NewName, false) == 0)


                                    {


                                          flag1 = true;


                                          break;


                                    }


                              }


                              if (!flag1)


                              {


                                    text1 = NewName;


                                    goto Label_0096;


                              }


                              num1++;


                              flag1 = false;


                              NewName = text2 + ” #” + StringType.FromInteger(num1);


                        }


                  }


                  text1 = NewName;


                  Label_0096:


                        key1.Close();


                  return text1;


            }


 


 


        public static byte[] GetSettingByte(ref RegistryKey hKey, ref string strPath, ref string strValue)


        {


            byte[] buffer1=null;


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                byte[] buffer2 = (byte[]) key1.GetValue(strValue, “”);


                key1.Close();


                return buffer2;


            }


            return buffer1;


        }


 


        public static int GetSettingInteger(ref RegistryKey hKey, ref string strPath, ref string strValue)


        {


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                int num1 = IntegerType.FromObject(key1.GetValue(strValue, 0));


                key1.Close();


                return num1;


            }


            return -1;


        }


 


        public static string GetSettingString(RegistryKey hKey, string strPath, string strValue, [Optional] bool DontExpand /* = false */)


        {


            string text1=””;


            int num6 = RegistryHelper.GetValueType(hKey, strPath, strValue);


            if (DontExpand | (num6 > 2))


            {


                        //            ‘.NET will automatically expand string values of the type REG_EXPAND_SZ


                        //            ‘It always likes to do the work for you ! Trouble is we want to see


                        //            ‘the data in it’s raw form !!!


                        int num1=0;


                int num2=0;


                 int num3=0;


                 int num5=0;


                string text2=””;


                if (hKey == Registry.ClassesRoot)


                {


                    num2 = -2147483648;


                }


                else if (hKey == Registry.CurrentUser)


                {


                    num2 = -2147483647;


                }


                else if (hKey == Registry.LocalMachine)


                {


                    num2 = -2147483646;


                }


                else if (hKey == Registry.Users)


                {


                    num2 = -2147483645;


                }


                else if (hKey == Registry.CurrentConfig)


                {


                    num2 = -2147483643;


                }


                else if (hKey == Registry.DynData)


                {


                    num2 = -2147483642;


                }


                else if (hKey == Registry.PerformanceData)


                {


                    num2 = -2147483644;


                }


                int num4 = RegistryHelper.RegOpenKey(num2, ref strPath, ref num1);


                num4 = RegistryHelper.RegQueryValueEx(num1, ref strValue, 0, ref num5, ref text2, ref num3);


                if (num4 == 0)


                {


                    text2 = new string(‘ ‘, num3);


                    int num7 = 0;


                    num4 = RegistryHelper.RegQueryValueEx(num1, ref strValue, 0, ref num7, ref text2, ref num3);


                    text1 = text2;


                }


                num4 = RegistryHelper.RegCloseKey(num1);


                return text1;


            }


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


//            ‘If you don’t need to see the REG_EXPAND_SZ in it’s raw form


//            ‘then the above code is unneccessary thus the optional DontExpand


                text1 = StringType.FromObject(key1.GetValue(strValue, “”));


                if ((text1.Length == 0) & (strValue.Length == 0))


                {


//                ‘If it’s the Default value and the result is “” then fill it in with “(value not set)”


                    text1 = “(value not set)”;


                }


                key1.Close();


            }


            return text1;


        }


 


        public static int GetValueType(RegistryKey hKey, string strPath, string strValueName)


        {


//       ‘Appears to be a limitation in .NET Registry access – no method to determine value type


//        ‘I couldn’t find any anyway.


//        ‘We have to resort to the API to provide us with the value type


 


                   int num2=0;


             int num3=0;


             int num5=0;


             int num7=0;


            if (hKey == Registry.ClassesRoot)


            {


                num3 = -2147483648;


            }


            else if (hKey == Registry.CurrentUser)


            {


                num3 = -2147483647;


            }


            else if (hKey == Registry.LocalMachine)


            {


                num3 = -2147483646;


            }


            else if (hKey == Registry.Users)


            {


                num3 = -2147483645;


            }


            else if (hKey == Registry.CurrentConfig)


            {


                num3 = -2147483643;


            }


            else if (hKey == Registry.DynData)


            {


                num3 = -2147483642;


            }


            else if (hKey == Registry.PerformanceData)


            {


                num3 = -2147483644;


            }


            strPath = RegistryHelper.RemoveBackslash(strPath);


            int num6 = RegistryHelper.RegOpenKey(num3, ref strPath, ref num2);


            string text2 = StringType.FromLong(0);


            num6 = RegistryHelper.RegQueryValueEx(num2, ref strValueName, 0, ref num7, ref text2, ref num5);


            num6 = RegistryHelper.RegCloseKey(num2);


            return num7;


        }


 


            public static bool HasSubKeys(RegistryKey hKey, string strPath)


            {


                  bool flag1=false;


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 != null)


                  {


                        flag1 = key1.SubKeyCount > 0;


                        key1.Close();


                  }


                  return flag1;


            }


 


 


        public static void ImportKey(string sInFile)


        {


            RegistryHelper.ShellFile(“regedit.exe”, “/I /S ” + RegistryHelper.GetDosPath(sInFile), ProcessWindowStyle.Normal);


        }


 


            public static bool IsKey(RegistryKey hKey, string strPath)


            {


                  bool flag1=false;


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 != null)


                  {


                        flag1 = true;


                        key1.Close();


                  }


                  return flag1;


            }


 


 


            private static void RecurseAllSubKeyValues(RegistryKey hKey, string strPath, ref string[] ValuesColl)


            {


                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);


                  if (key1 != null)


                  {


                        int num1;


                        string[] textArray1;


                        int num4;


                        int num3 = key1.ValueCount;


                        int num2 = key1.SubKeyCount;


                        if (num3 > 0)


                        {


                              textArray1 = key1.GetValueNames();


                              num1 = ValuesColl.GetUpperBound(0);


                              ValuesColl = (string[]) Utils.CopyArray((Array) ValuesColl, new string[(num1 + num3) + 1]);


                              int num6 = num3 – 1;


                              for (num4 = 0; num4 <= num6; num4++)


                              {


                                    ValuesColl[num1] = strPath + @”” + textArray1[num4];


                                    num1++;


                              }


                        }


                        else


                        {


                              num1 = ValuesColl.GetUpperBound(0);


                              ValuesColl = (string[]) Utils.CopyArray((Array) ValuesColl, new string[(num1 + 1) + 1]);


                              ValuesColl[num1] = strPath + @””;


                        }


                        if (num2 > 0)


                        {


                              textArray1 = key1.GetSubKeyNames();


                              int num5 = num3 – 1;


                              for (num4 = 0; num4 <= num5; num4++)


                              {


                                    RegistryHelper.RecurseAllSubKeyValues(hKey, strPath + @”” + textArray1[num4], ref ValuesColl);


                              }


                        }


                        key1.Close();


                  }


            }


 


 


 


        public static bool RenameKey(RegistryKey hKey, string strPath, string NewKeyName)


        {


            bool flag1=false;


            string[] textArray1=null;


            string text4 = RegistryHelper.PathOnly(strPath);


            string text2 = RegistryHelper.FileOnly(strPath);


            string text1 = text4 + @”” + NewKeyName;


            RegistryHelper.CreateKey(hKey, text4, NewKeyName);


            RegistryHelper.RecurseAllSubKeyValues(hKey, strPath, ref textArray1);


            if (textArray1.Length > 0)


            {


                int num5 = textArray1.GetUpperBound(0) – 1;


                for (int num3 = 0; num3 <= num5; num3++)


                {


                    string text7;


                    string text6 = RegistryHelper.FileOnly(textArray1[num3]);


                    string text5 = RegistryHelper.PathOnly(textArray1[num3]);


                    string text3 = text5.Replace(strPath, text1);


                    int num2 = RegistryHelper.GetValueType(hKey, text5, text6);


                    if (StringType.StrCmp(text6, “”, false) == 0)


                    {


                        num2 = 1;


                    }


                    switch (num2)


                    {


                        case 1:


                        {


                            text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);


                            RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_SZ);


                            goto Label_014D;


                        }


                        case 2:


                        {


                            text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);


                            RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_EXPAND_SZ);


                            goto Label_014D;


                        }


                        case 3:


                        {


                            byte[] buffer1 = RegistryHelper.GetSettingByte(ref hKey, ref text5, ref text6);


                            RegistryHelper.SaveSettingByte(hKey, text3, text6, buffer1, false);


                            goto Label_014D;


                        }


                        case 4:


                        {


                            int num1 = RegistryHelper.GetSettingInteger(ref hKey, ref text5, ref text6);


                            RegistryHelper.SaveSettingInteger(hKey, text3, text6, num1);


                            goto Label_014D;


                        }


                        case 5:


                        case 6:


                        {


                            goto Label_014D;


                        }


                        case 7:


                        {


                            break;


                        }


                        default:


                        {


                            goto Label_014D;


                        }


                    }


                    text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);


                    RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_MULTI_SZ);


                Label_014D:;


                }


            }


            RegistryHelper.DeleteKey(hKey, strPath);


            return flag1;


        }


 


        public static bool RenameValue(RegistryKey hKey, string strPath, string strValue, string NewValueName)


        {


            bool flag1=false;


            string text1=””;


            switch (RegistryHelper.GetValueType(hKey, strPath, strValue))


            {


                case 1:


                {


                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);


                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_SZ);


                    break;


                }


                case 2:


                {


                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);


                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_EXPAND_SZ);


                    break;


                }


                case 3:


                {


                    byte[] buffer1 = RegistryHelper.GetSettingByte(ref hKey, ref strPath, ref strValue);


                    RegistryHelper.SaveSettingByte(hKey, strPath, NewValueName, buffer1, false);


                    break;


                }


                case 4:


                {


                    int num1 = RegistryHelper.GetSettingInteger(ref hKey, ref strPath, ref strValue);


                    RegistryHelper.SaveSettingInteger(hKey, strPath, NewValueName, num1);


                    break;


                }


                case 7:


                {


                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);


                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_MULTI_SZ);


                    break;


                }


            }


            RegistryHelper.DeleteValue(hKey, strPath, strValue);


            return flag1;


        }


 


        public static bool SaveSettingByte(RegistryKey hKey, string strPath, string strValue, byte[] byteData, [Optional] bool SetEmpty /* = false */)


        {


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 == null)


            {


                bool flag1=false;


                return flag1;


            }


            if (SetEmpty)


            {


                key1.SetValue(strValue, 0);


            }


            else


            {


                key1.SetValue(strValue, byteData);


            }


            key1.Flush();


            key1.Close();


            return true;


        }


 


        public static void SaveSettingEmptyByte(RegistryKey hKey, string strPath, string strValueName)


        {


            int num1=0;


             int num2=0;


            if (hKey == Registry.ClassesRoot)


            {


                num2 = -2147483648;


            }


            else if (hKey == Registry.CurrentUser)


            {


                num2 = -2147483647;


            }


            else if (hKey == Registry.LocalMachine)


            {


                num2 = -2147483646;


            }


            else if (hKey == Registry.Users)


            {


                num2 = -2147483645;


            }


            else if (hKey == Registry.CurrentConfig)


            {


                num2 = -2147483643;


            }


            else if (hKey == Registry.DynData)


            {


                num2 = -2147483642;


            }


            else if (hKey == Registry.PerformanceData)


            {


                num2 = -2147483644;


            }


            int num3 = RegistryHelper.RegCreateKey(num2, ref strPath, ref num1);


            string text1 = StringType.FromLong(0);


            num3 = RegistryHelper.RegSetValueEx(num1, ref strValueName, 0, 3, ref text1, 0);


            num3 = RegistryHelper.RegCloseKey(num1);


        }


 


        public static bool SaveSettingInteger(RegistryKey hKey, string strPath, string strValue, int intData)


        {


            bool flag1=false;


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                key1.SetValue(strValue, intData);


                key1.Flush();


                key1.Close();


                flag1 = true;


            }


            return flag1;


        }


 


        public static bool SaveSettingString(RegistryKey hKey, string strPath, string strValue, string strData, SaveStringType sType)


        {


            bool flag1=false;


            if (!RegistryHelper.IsKey(hKey, strPath))


            {


                RegistryHelper.CreateKey(hKey, RegistryHelper.PathOnly(strPath), RegistryHelper.FileOnly(strPath));


            }


//        ‘If it’s the Default value and strData is “” then fill it in with “(value not set)”


            if ((strValue.Length == 0) & (strData.Length == 0))


            {


                strData = “(value not set)”;


            }


            if (sType != SaveStringType.REG_SZ)


            {


                int num1=0;


                 int num2=0;


                if (hKey == Registry.ClassesRoot)


                {


                    num1 = -2147483648;


                }


                else if (hKey == Registry.CurrentUser)


                {


                    num1 = -2147483647;


                }


                else if (hKey == Registry.LocalMachine)


                {


                    num1 = -2147483646;


                }


                else if (hKey == Registry.Users)


                {


                    num1 = -2147483645;


                }


                else if (hKey == Registry.CurrentConfig)


                {


                    num1 = -2147483643;


                }


                else if (hKey == Registry.DynData)


                {


                    num1 = -2147483642;


                }


                else if (hKey == Registry.PerformanceData)


                {


                    num1 = -2147483644;


                }


                int num3 = RegistryHelper.RegCreateKey(num1, ref strPath, ref num2);


                num3 = RegistryHelper.RegSetValueEx(num2, ref strValue, 0, (int) sType, ref strData, strData.Length);


                num3 = RegistryHelper.RegCloseKey(num2);


                return flag1;


            }


            RegistryKey key1 = hKey.OpenSubKey(strPath, true);


            if (key1 != null)


            {


                key1.SetValue(strValue, strData);


                key1.Flush();


                key1.Close();


                flag1 = true;


            }


            return flag1;


        }


 


        public static string ShellFile(string path, string arguments, ProcessWindowStyle style)


        {


            string text1=””;


            Process process1 = new Process();


            try


            {


                process1.StartInfo.FileName = path;


                process1.StartInfo.UseShellExecute = false;


                process1 = Process.Start(path, arguments);


                process1.WaitForExit();


            }


            finally


            {


                process1.Dispose();


            }


            return text1;


        }


 


 


        // Nested Types


        public enum SaveStringType


        {


            // Fields


            REG_EXPAND_SZ = 2,


            REG_MULTI_SZ = 7,


            REG_SZ = 1


        }


            #region  “Helper methods”


           


//          ‘ Append a backslash (or any character) at the end of a path


//          ‘ if it isn’t there already


//          ‘http://66.102.7.104/search?q=cache:jfWf2rcyyTgJ:www.devx.com/vb2themax/Tip/18940+AddBackSlash&hl=en


            public static string AddBackslash(string Path, [Optional] string ch /* = @”” */)


            {


                  if (StringType.StrCmp(Strings.Right(Path, 1), ch, false) != 0)


                  {


                        return (Path + ch);


                  }


                  return Path;


            }


//          ‘http://66.102.7.104/search?q=cache:m8ISK7XP3OoJ:vbboshi.diy.myrice.com/preblem/41-60/pr59.htm+RemoveBackSlash&hl=en


//          ‘aLSO http://relib.com/forums/thread847374.aspx


            public static string RemoveBackslash(string s)


            {


                  string text1=””;


                  int num1 = Strings.Len(s);


                  if (num1 != 0)


                  {


                        if (StringType.StrCmp(Strings.Right(s, 1), @””, false) == 0)


                        {


                              text1 = Strings.Left(s, num1 – 1);


                              goto Label_003A;


                        }


                        return s;


                  }


                  text1 = “”;


                  Label_003A:


                        return text1;


            }


            //          ‘http://vb2themax.com/ShowContent.aspx?ID=40fcf8bb-79a0-49e0-b930-422211907215


            //          ‘ this code assumes the following Imports statement


            //               Imports System.Text


            public static string GetShortFileName(string path)


            {


                  StringBuilder builder1 = new StringBuilder(0x400);


                  int num1 = RegistryHelper.GetShortPathName(ref path, builder1, builder1.Capacity);


                  return builder1.ToString(0, num1);


            }


 


            [DllImport(“kernel32″, EntryPoint=”GetShortPathNameA”, CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]


            private static extern int GetShortPathName([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);


 


           


            public static void FileAppend(string path, string text)


            {


                  //object obj1;


                  StreamWriter writer1 = File.AppendText(path);


                  writer1.Write(text);


                  writer1.Close();


                  //return obj1;


            }


 


//          ‘http://translate.google.com/translate?hl=en&sl=de&u=http://www.internet-magazin.de/praxis/cm/page/page.php%3Ftable%3Dpg%26id%3D1690&prev=/search%3Fq%3DPathOnly%2BFileOnly%26start%3D10%26hl%3Den%26lr%3D%26sa%3DN


            public static string FileOnly(string P)


            {


                  int num1 = Strings.InStrRev(StringType.FromInteger(0), P, IntegerType.FromString(“”), CompareMethod.Binary);


                  P = Strings.Mid(P, num1 + 1);


                  return P;


            }


            public static object PathComplete(string P)


            {


                  if (StringType.StrCmp(Strings.Right(P, 1), “”, false) == 0)


                  {


                        P = P + “”;


                  }


                  return P;


            }


 


            //’Also you extract the complete path from a listing structure, by using the InstrRev function. Only, separated in contrast to tap before, the file name. In connection with the procedure shown at the beginning completely PathComplete manufacture you so complete path names.


            public static string PathOnly(string P)


            {


                  int num1 = Strings.InStrRev(StringType.FromInteger(0), P, IntegerType.FromString(“”), CompareMethod.Binary);


                  if (num1 == 0)


                  {


                        num1 = 1;


                  }


                  P = Strings.Left(P, num1 – 1);


                  if (Strings.Len(P) == 2)


                  {


                        P = StringType.FromObject(RegistryHelper.PathComplete(P));


                  }


                  return P;


            }


            #endregion  //”Helper methods”


 


 


      }


}


 


 

Indexing service CreateRecordset error “Access is denied” can be caused by disabled Delegation.

I am using  IXSSO from ASP.NET  to access remote Indexing Services Catalog (See also my posts COM CleanUp when using IXSSO in .Net  and  Fill Dataset with rows in a specified range  http://thespoke.net/blogs/mnf/archive/2005/05/09/92495.aspx) .


When testing it from workstation I started to receive “Access is denied” exception in CreateRecordset call.


According to Hilary Cotter http://groups.google.com.au/group/microsoft.public.inetserver.indexserver/browse_frm/thread/55dbf5119cc898ce/0b992b7127b27062?hl=en#0b992b7127b27062 it is usually can be 

fixed by “giving rights to logon interactively on the remote machine”

It didn’t help me, but finally I found (thanks to http://www.highdots.com/forums/asp-net-security/impersonate-delegate-problem-699124.html ) that


to fix the error is required to set the web server computer to be trusted for delegation as described in  http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/ServerHelp/b207ee9c-a055-43f7-b9be-20599b694a31.mspx.


 


 

To run WebDav queries against Exchange Folders from ASP.NET -use Kerberos .

I am using WebDav query to search e-mails and public folders from Exchange Server 2003. The code is based on the Visual Basic .NET sample  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/e2k3/e2k3/_exch2k_searching_folders_http.asp


However when I started to test the code with impersonation, I ve got a problem.The scenario was the following


I am using client on workstation running IE6 that login to ASP.NET web server using Windows Authentication with impersonation. The server ASP.NET page uses WebDav to access Exchange Server 2003.


The WebDav request failed with “The remote server returned an error: (401) Unauthorized“.


If the client is running IE browser on the Web Server , WebDav queries are succeded.
I’ve changed Web Server to “trust this computer to delegate”, but the error was the same.


The solution is to use “Negotiate” (or “Kerberos”) instead of NTLM when calling MyCredentialCache.Add



CredentialCache cache =new CredentialCache();


NetworkCredential

credential1 = (NetworkCredential) CredentialCache.DefaultCredentials;

// from http://blogs.msdn.com/buckh/archive/2004/07/28/199706.aspx

// Depending upon the IIS configuration, that may be negotiate, NTLM, Kerberos, basic, or digest authentication

//Negotiates with the client to determine the authentication scheme. If both client and server support Kerberos, it is used; otherwise NTLM is used.

string authType =”Negotiate”;//The authentication scheme used by the resource named in uriPrefix.

// if Kerberos is unavailable, it can be 15sec delay (from http://blogs.msdn.com/buckh/archive/2004/07/28/199706.aspx#217098)

cache.Add(

new Uri(strRootURI), authType, credential1);

It also important to ensure that both Web Server and impersonated user account are “Trusted for deilegation” (see ASP.NET and Exchange tips and samples and How To: Implement Kerberos Delegation for Windows 2000)


Related post: Configure Exchange Server 2003 for WebDav queries.

COM CleanUp when using IXSSO in .Net

I am using IXSSO to access Index Server similar to described in  article  Query Index Server with IXSSO in .NET” on  ASP101. (See also my post how to use Fill Dataset with rows in a specified range  http://thespoke.net/blogs/mnf/archive/2005/05/09/92495.aspx).


Recently I found a useful tip to dispose COM objects after the use. I noticed that  it is required to check for null before calling ReleaseComObject. So the finally section should be like this


finally

{

// recommended in http://www.eggheadcafe.com/forumarchives/inetserverindexserver/Aug2005/post23479438.asp

if (rs!=null)Marshal.ReleaseComObject(rs); //Recordset

if (query!=null)Marshal.ReleaseComObject(query); //Query

if (util!=null)Marshal.ReleaseComObject(util); //Utils

query = null;

util =

null;

rs=

null;

}


 

Add SelectedValue property to MetaBuilders’ ComboBox

 I am using  MetaBuilders.ComboBox[^] and recently found that I am not able to specify SelectedValue in Page_OnLoad event.


The html list has “selected“ as expected , but text box is not populated with selected value.


It is required to add SelectedValue  to the MetaBuilders.WebControls.ComboBox.


            ///


            /// Overrides .


            /// Should be overridden to addition to SelectedIndex


            ///


            public override string SelectedValue


            {


                  get


                  {


                        return base.SelectedValue;


                  }


                  set


                  {


                        base.SelectedValue = value;


                        // this.isLoaded is used in  SelectedIndex to ensure special 


                    //processing  when called from LoadPostData


                        // not required in SelectedValue property


                        this.Text = SelectedValue;


                  }


            }


You need to download MetaBuilders.ComboBox[^] from

http://www.metabuilders.com/Tools/ComboBox.aspx

and add the SelectedValue code to the MetaBuilders.WebControls.ComboBox class in ComboBox.cs file.


Then compile the project and use DLL in the same way as original MetaBuilders combo-box can be used.


See here another fix for MetaBuilders.WebControls.ComboBox, which is important if you use SmartNavigation