/// <summary>
        /// Try to update an IPA on the mobile device (it must have already been copied to the PublicStaging directory, with the same filename as the path passed in)
        /// </summary>
        public bool TryUpgrade(string IPASourcePathOnPC)
        {
            DateTime StartTime = DateTime.Now;

            ReconnectWithInstallProxy();

            IntPtr LiveConnection = IntPtr.Zero;
            IntPtr ClientOptions  = IntPtr.Zero;

            TypedPtr <CFURL> UrlPath         = MobileDevice.CreateFileUrlHelper(IPASourcePathOnPC, false);
            string           UrlPathAsString = MobileDevice.GetStringForUrl(UrlPath);

            int Result = MobileDevice.AMDeviceMethods.SecureUpgradeApplication(LiveConnection, iPhoneHandle, UrlPath, ClientOptions, InstallProgressCallback, IntPtr.Zero);

            if (Result == 0)
            {
                Console.WriteLine("Install \\ Update of \"{0}\" finished in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), Result, (DateTime.Now - StartTime).TotalSeconds);
            }
            else
            {
                Console.WriteLine("Install \\ Update of \"{0}\" failed with {1} in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), MobileDevice.GetErrorString(Result), (DateTime.Now - StartTime).TotalSeconds);
            }

            return(Result == 0);
        }
        public static byte[] StringToFileSystemRepresentation(string InString)
        {
            byte[] BString = StringToUTF32LEString(InString);
            TypedPtr <CFString> cfString = CoreImpl.CFStringCreateWithBytes(kCFAllocatorDefault, BString, BString.Length, CFStringBuiltInEncodings.kCFStringEncodingUTF32LE, false);

            return(CFStringGetFileSystemRepresentation(cfString));
        }
        /// <summary>
        /// Converts a CFDictionary into a Dictionary (keys and values are object)
        /// </summary>
        public static Dictionary <object, object> ConvertCFDictionaryToDictionary(TypedPtr <CFDictionary> Dict)
        {
            // Get the raw key-value pairs
            int NumPairs = CFDictionaryGetCount(Dict);

            IntPtr [] Keys   = new IntPtr[NumPairs];
            IntPtr [] Values = new IntPtr[NumPairs];

            CoreImpl.CFDictionaryGetKeysAndValues((IntPtr)Dict, Keys, Values);

            // Convert each key and value to a managed type
            Dictionary <object, object> Result = new Dictionary <object, object>();

            for (int i = 0; i < NumPairs; ++i)
            {
                try
                {
                    Result.Add(ConvertArbitraryCFType(Keys[i]), ConvertArbitraryCFType(Values[i]));
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to properly convert dictionary");
                }
            }

            return(Result);
        }
        /// <summary>
        /// Generic progress callback implementation (used for install/uninstall/etc...)
        /// </summary>
        void HandleProgressCallback(string OuterFunction, TypedPtr <CFDictionary> SourceDict)
        {
            Dictionary <string, object> Dict = MobileDevice.ConvertCFDictionaryToDictionaryStringy(SourceDict);

            // Expecting:
            // string,string -> "Status",PhaseOfInstaller
            // string,number -> "PercentComplete",%Done
            try
            {
                string Phase       = Dict["Status"] as string;
                int    PercentDone = (int)((Double)(Dict["PercentComplete"]));

                if (OnGenericProgress != null)
                {
                    string Msg = String.Format("{0} is {1}% complete at phase '{2}'", OuterFunction, PercentDone, Phase);
                    OnGenericProgress(Msg, PercentDone);
                }
                else
                {
                    Console.WriteLine(" ... {0} {1}% complete (phase '{2}')", OuterFunction, PercentDone, Phase);
                }
            }
            catch (System.Exception)
            {
            }
        }
        public bool TryUninstall(string ApplicationIdentifier)
        {
            DateTime StartTime = DateTime.Now;

            ReconnectWithInstallProxy();

            TypedPtr <CFString> CF_ApplicationIdentifier = MobileDevice.CFStringMakeConstantString(ApplicationIdentifier);

            IntPtr CF_ClientOptions = IntPtr.Zero;
            IntPtr ExtraKey         = IntPtr.Zero;
            IntPtr ExtraValue       = IntPtr.Zero;
            IntPtr ConnectionHandle = IntPtr.Zero;

            int Result = MobileDevice.AMDeviceMethods.SecureUninstallApplication(ConnectionHandle, iPhoneHandle, CF_ApplicationIdentifier, CF_ClientOptions, UninstallProgressCallback, IntPtr.Zero);

            if (Result == 0)
            {
                Console.WriteLine("Uninstall of \"{0}\" completed successfully in {2:0.00} seconds", ApplicationIdentifier, Result, (DateTime.Now - StartTime).TotalSeconds);
            }
            else
            {
                Console.WriteLine("Uninstall of \"{0}\" failed with {1} in {2:0.00} seconds", ApplicationIdentifier, MobileDevice.GetErrorString(Result), (DateTime.Now - StartTime).TotalSeconds);
            }

            return(Result == 0);
        }
            public static int ConnectionOpen(IntPtr handle, uint io_timeout, out TypedPtr <AFCCommConnection> OutConn)
            {
                IntPtr Conn;
                int    Result = AFCConnectionOpen(handle, io_timeout, out Conn);

                OutConn = Conn;
                return(Result);
            }
            public static int LookupApplications(TypedPtr <AppleMobileDeviceConnection> device, IntPtr options, out Dictionary <string, object> AppBundles)
            {
                IntPtr UntypedDict = IntPtr.Zero;
                int    Result      = AMDeviceLookupApplications((IntPtr)device, options, ref UntypedDict);

                AppBundles = MobileDevice.ConvertCFDictionaryToDictionaryStringy(new TypedPtr <CFDictionary>(UntypedDict));

                return(Result);
            }
 public static int TransferApplication(
     TypedPtr <AppleMobileDeviceConnection> device,
     TypedPtr <CFString> InPackagePath,
     IntPtr UnknownButUnused,
     DeviceInstallationCallback ProgressCallback,
     IntPtr UserData)
 {
     return(AMDeviceTransferApplication((IntPtr)device, (IntPtr)InPackagePath, UnknownButUnused, ProgressCallback, UserData));
 }
 public static int InstallApplication(
     TypedPtr <AppleMobileDeviceConnection> device,
     TypedPtr <CFString> FilePath,
     TypedPtr <CFDictionary> ClientOptions,
     DeviceInstallationCallback ProgressCallback,
     IntPtr UserData)
 {
     return(AMDeviceInstallApplication((IntPtr)device, (IntPtr)FilePath, (IntPtr)ClientOptions, ProgressCallback, UserData));
 }
            public static int FileInfoOpen(TypedPtr <AFCCommConnection> conn, string path, out TypedPtr <AFCDictionary> OutDict)
            {
                IntPtr UntypedDict;
                int    Result = AFCFileInfoOpen((IntPtr)conn, path, out UntypedDict);

                OutDict = UntypedDict;

                return(Result);
            }
 public static int SecureUninstallApplication(
     IntPtr serviceConnection,
     TypedPtr <AppleMobileDeviceConnection> DeviceIfConnIsNull,
     TypedPtr <CFString> ApplicationIdentifer,
     TypedPtr <CFDictionary> ClientOptions,
     DeviceInstallationCallback ProgressCallback,
     IntPtr UserData)
 {
     return(AMDeviceSecureUninstallApplication(serviceConnection, (IntPtr)DeviceIfConnIsNull, (IntPtr)ApplicationIdentifer, (IntPtr)ClientOptions, ProgressCallback, UserData));
 }
 public static int SecureUpgradeApplication(
     IntPtr ServiceConnection,
     TypedPtr <AppleMobileDeviceConnection> DeviceIfConnIsNull,
     TypedPtr <CFURL> UrlPath,
     TypedPtr <CFDictionary> ClientOptions,
     DeviceInstallationCallback ProgressCallback,
     IntPtr UserData)
 {
     return(AMDeviceSecureUpgradeApplication(ServiceConnection, (IntPtr)DeviceIfConnIsNull, (IntPtr)UrlPath, (IntPtr)ClientOptions, ProgressCallback, UserData));
 }
        static void InitializeCoreFoundation()
        {
            IntPtr CoreFoundation = RequiredWinAPI.GetModuleHandle("CoreFoundation.dll");

            kCFAllocatorDefault             = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFAllocatorDefault");
            kCFTypeDictionaryKeyCallBacks   = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryKeyCallBacks");
            kCFTypeDictionaryValueCallBacks = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryValueCallBacks");

            kCFBooleanTrue  = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanTrue");
            kCFBooleanFalse = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanFalse");
        }
        /// <summary>
        /// Close the AFC connection
        /// </summary>
        public void Disconnect()
        {
            if (AFCCommsHandle.Handle != IntPtr.Zero)
            {
                int ans = MobileDevice.AFC.ConnectionClose(AFCCommsHandle);
                ans = MobileDevice.AMDeviceMethods.StopSession(iPhoneHandle);
                ans = MobileDevice.AMDeviceMethods.Disconnect(iPhoneHandle);
            }

            AFCCommsHandle = IntPtr.Zero;
        }
        /// <summary>
        /// Determines whether the given path refers to an existing file or directory on the phone.
        /// </summary>
        /// <param name="path">The path to test.</param>
        /// <returns><c>true</c> if path refers to an existing file or directory, otherwise <c>false</c>.</returns>
        public bool Exists(string path)
        {
            TypedPtr <AFCDictionary> data = IntPtr.Zero;

            int ret = MobileDevice.AFC.FileInfoOpen(AFCCommsHandle, path, out data);

            if (ret == 0)
            {
                MobileDevice.AFC.KeyValueClose(data);
            }

            return(ret == 0);
        }
        /// <summary>
        /// Converts an arbitrary CFNumber to a double
        /// </summary>
        public static double ConvertCFNumber(TypedPtr <CFNumber> Number)
        {
            CFNumberType TypeID = CoreImpl.CFNumberGetType((IntPtr)Number);

            switch (TypeID)
            {
            case CFNumberType.kCFNumberFloat32Type:
            case CFNumberType.kCFNumberFloatType:
            {
                float Result;
                CoreImpl.CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberFloat32Type, out Result);
                return(Result);
            }

            case CFNumberType.kCFNumberFloat64Type:
            case CFNumberType.kCFNumberDoubleType:
            case CFNumberType.kCFNumberCGFloatType:
            {
                double Result;
                CoreImpl.CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberFloat64Type, out Result);
                return(Result);
            }

            case CFNumberType.kCFNumberSInt8Type:
            case CFNumberType.kCFNumberSInt16Type:
            case CFNumberType.kCFNumberSInt32Type:
            case CFNumberType.kCFNumberCharType:
            case CFNumberType.kCFNumberShortType:
            case CFNumberType.kCFNumberIntType:
            case CFNumberType.kCFNumberLongType:
            case CFNumberType.kCFNumberCFIndexType:
            {
                int Result;
                CoreImpl.CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberIntType, out Result);
                return(Result);
            }

            case CFNumberType.kCFNumberSInt64Type:
            case CFNumberType.kCFNumberLongLongType:
            case CFNumberType.kCFNumberNSIntegerType:
            {
                Int64 Result;
                CoreImpl.CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberSInt64Type, out Result);
                return(Result);
            }

            default:
                return(0.0);
            }
        }
        /*
         * Valid Value Names:
         *  ActivationState
         *  ActivationStateAcknowledged
         *  BasebandBootloaderVersion
         *  BasebandVersion
         *  BluetoothAddress
         *  BuildVersion
         *  DeviceCertificate
         *  DeviceClass
         *  DeviceName
         *  DevicePublicKey
         *  FirmwareVersion
         *  HostAttached
         *  IntegratedCircuitCardIdentity
         *  InternationalMobileEquipmentIdentity
         *  InternationalMobileSubscriberIdentity
         *  ModelNumber
         *  PhoneNumber
         *  ProductType
         *  ProductVersion
         *  ProtocolVersion
         *  RegionInfo
         *  SBLockdownEverRegisteredKey
         *  SIMStatus
         *  SerialNumber
         *  SomebodySetTimeZone
         *  TimeIntervalSince1970
         *  TimeZone
         *  TimeZoneOffsetFromUTC
         *  TrustedHostAttached
         *  UniqueDeviceID
         *  Uses24HourClock
         *  WiFiAddress
         *  iTunesHasConnected
         */

        public static string AMDeviceCopyValue(TypedPtr <AppleMobileDeviceConnection> device, string name)
        {
            IntPtr result = AMDeviceMethods.CopyValue(device, 0, CFStringMakeConstantString(name));

            if (result != IntPtr.Zero)
            {
                return(MobileDevice.CFStringGetCString(result));
            }
            else
            {
                Console.WriteLine("Error: Call to AMDeviceCopyValue failed");
            }
            return(String.Empty);
        }
        public static int AFCDirectoryRead(TypedPtr <AFCCommConnection> conn, IntPtr dir, ref string buffer)
        {
            int ret;

            IntPtr ptr = IntPtr.Zero;

            ret = AFC.DirectoryRead((IntPtr)conn, dir, ref ptr);
            if ((ret == 0) && (ptr != null))
            {
                buffer = Marshal.PtrToStringAnsi(ptr);
            }
            else
            {
                buffer = null;
            }
            return(ret);
        }
        static void InitializeCoreFoundation()
        {
            if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
            {
                CoreImpl = new CoreFoundationOSX();
            }
            else
            {
                CoreImpl = new CoreFoundationWin();

                IntPtr CoreFoundation = RequiredWinAPI.GetModuleHandle("CoreFoundation.dll");

                kCFAllocatorDefault             = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFAllocatorDefault");
                kCFTypeDictionaryKeyCallBacks   = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryKeyCallBacks");
                kCFTypeDictionaryValueCallBacks = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryValueCallBacks");

                kCFBooleanTrue  = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanTrue");
                kCFBooleanFalse = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanFalse");
            }
        }
        public static string CFStringGetCString(TypedPtr <CFString> InString)
        {
            byte[] bytes = new byte[2048];
            CoreImpl.CFStringGetCString(InString.Handle, bytes, 2048, CFStringBuiltInEncodings.kCFStringEncodingUTF8);

            int ValidLength = 0;

            foreach (byte b in bytes)
            {
                if (b == 0)
                {
                    break;
                }
                else
                {
                    ValidLength++;
                }
            }

            return(Encoding.UTF8.GetString(bytes, 0, ValidLength));
        }
        public static byte[] CFStringGetFileSystemRepresentation(TypedPtr <CFString> InString)
        {
            byte[] bytes = new byte[2048];
            CoreImpl.CFStringGetFileSystemRepresentation(InString.Handle, bytes, 2048);

            int ValidLength = 0;

            foreach (byte b in bytes)
            {
                if (b == 0)
                {
                    break;
                }
                else
                {
                    ValidLength++;
                }
            }

//			return Encoding.UTF8.GetString(bytes, 0, ValidLength);
            return(bytes);
        }
        public bool ConnectToBundle(string BundleName)
        {
            Reconnect();

            TypedPtr <CFString> CFBundleName = MobileDevice.CFStringMakeConstantString(BundleName);

            // Open the bundle
            int Result = MobileDevice.AMDeviceMethods.StartHouseArrestService(iPhoneHandle, CFBundleName, IntPtr.Zero, ref hService, 0);

            if (Result != 0)
            {
                Console.WriteLine("Failed to connect to bundle '{0}' with {1}", BundleName, MobileDevice.GetErrorString(Result));
                return(false);
            }

            // Open a file sharing connection
            if (MobileDevice.AFC.ConnectionOpen(hService, 0, out AFCCommsHandle) != 0)
            {
                return(false);
            }

            return(true);
        }
 public static TypedPtr <CFURL> CFURLCreateWithFileSystemPath(IntPtr Allocator, TypedPtr <CFString> FilePath, CFURLPathStyle PathStyle, int isDirectory)
 {
     return((TypedPtr <CFURL>)(CoreImpl.CFURLCreateWithFileSystemPath(Allocator, FilePath.Handle, PathStyle, isDirectory)));
 }
 public Boolean CFStringGetFileSystemRepresentation(TypedPtr <CFString> theString, byte[] buffer, int bufferSize)
 {
     return(CoreFoundation.CFStringGetFileSystemRepresentation((IntPtr)theString, buffer, bufferSize));
 }
 public void CFDictionarySetValue(TypedPtr <CFDictionary> Dict, /*const*/ IntPtr Key, /*const*/ IntPtr Value)
 {
     CoreFoundation.CFDictionarySetValue((IntPtr)Dict, Key, Value);
 }
 /// <summary>
 /// Creates a new iPhone object. If an iPhone is connected to the computer, a connection will automatically be opened.
 /// </summary>
 public MobileDeviceInstance(TypedPtr<AppleMobileDeviceConnection> Connection)
 {
     iPhoneHandle = Connection;
     doConstruction();
 }
 public static void CFDictionaryAddHelper(TypedPtr<CFDictionary> InDict, string Key, string Value)
 {
     CFDictionarySetValue((IntPtr)InDict, (IntPtr)CFStringMakeConstantString(Key), (IntPtr)CFStringMakeConstantString(Value));
 }
			public static int DirectoryRead(TypedPtr<AFCCommConnection> conn, IntPtr dir, ref IntPtr dirent)
			{
				return AFCDirectoryRead((IntPtr)conn, dir, ref dirent);
			}
			public static int FileInfoOpen(TypedPtr<AFCCommConnection> conn, string path, out TypedPtr<AFCDictionary> OutDict)
			{
				IntPtr UntypedDict;
				int Result = AFCFileInfoOpen((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(path), out UntypedDict);
				OutDict = UntypedDict;

				return Result;
			}
			public static int FileRefTell(TypedPtr<AFCCommConnection> conn, Int64 handle, ref uint position)
			{
				return AFCFileRefTell((IntPtr)conn, handle, ref position);
			}
        static void InitializeCoreFoundation()
        {
            IntPtr CoreFoundation = RequiredWinAPI.GetModuleHandle("CoreFoundation.dll");

            kCFAllocatorDefault = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFAllocatorDefault");
            kCFTypeDictionaryKeyCallBacks = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryKeyCallBacks");
            kCFTypeDictionaryValueCallBacks = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFTypeDictionaryValueCallBacks");

            kCFBooleanTrue = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanTrue");
            kCFBooleanFalse = RequiredWinAPI.GetProcAddress(CoreFoundation, "kCFBooleanFalse");
        }
 public static string GetStringForUrl(TypedPtr<CFURL> Url)
 {
     IntPtr cfString = CFURLGetString((IntPtr)Url);
     return CFStringGetCString((IntPtr)cfString);
 }
        /// <summary>
        /// Converts an arbitrary CFNumber to a double
        /// </summary>
        public static double ConvertCFNumber(TypedPtr<CFNumber> Number)
        {
            CFNumberType TypeID = CFNumberGetType((IntPtr)Number);

            switch (TypeID)
            {
                case CFNumberType.kCFNumberFloat32Type:
                case CFNumberType.kCFNumberFloatType:
                    {
                        float Result;
                        CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberFloat32Type, out Result);
                        return Result;
                    }

                case CFNumberType.kCFNumberFloat64Type:
                case CFNumberType.kCFNumberDoubleType:
                case CFNumberType.kCFNumberCGFloatType:
                    {
                        double Result;
                        CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberFloat64Type, out Result);
                        return Result;
                    }

                case CFNumberType.kCFNumberSInt8Type:
                case CFNumberType.kCFNumberSInt16Type:
                case CFNumberType.kCFNumberSInt32Type:
                case CFNumberType.kCFNumberCharType:
                case CFNumberType.kCFNumberShortType:
                case CFNumberType.kCFNumberIntType:
                case CFNumberType.kCFNumberLongType:
                case CFNumberType.kCFNumberCFIndexType:
                    {
                        int Result;
                        CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberIntType, out Result);
                        return Result;
                    }

                case CFNumberType.kCFNumberSInt64Type:
                case CFNumberType.kCFNumberLongLongType:
                case CFNumberType.kCFNumberNSIntegerType:
                    {
                        Int64 Result;
                        CFNumberGetValue((IntPtr)Number, CFNumberType.kCFNumberSInt64Type, out Result);
                        return Result;
                    }

                default:
                    return 0.0;
            }
        }
        public static Dictionary<string, object> ConvertCFDictionaryToDictionaryStringy(TypedPtr<CFDictionary> Dict)
        {
            Dictionary<string, object> Result = new Dictionary<string,object>();
            Dictionary<object, object> Temp = ConvertCFDictionaryToDictionary(Dict);

            foreach (KeyValuePair<object, object> KVP in Temp)
            {
                string Key = (string)KVP.Key;
                Result.Add(Key, KVP.Value);
            }

            return Result;
        }
        /// <summary>
        /// Converts a CFDictionary into a Dictionary (keys and values are object)
        /// </summary>
        public static Dictionary<object, object> ConvertCFDictionaryToDictionary(TypedPtr<CFDictionary> Dict)
        {
            // Get the raw key-value pairs
            int NumPairs = CFDictionaryGetCount(Dict);

            IntPtr [] Keys = new IntPtr[NumPairs];
            IntPtr [] Values = new IntPtr[NumPairs];

            CFDictionaryGetKeysAndValues((IntPtr)Dict, Keys, Values);

            // Convert each key and value to a managed type
            Dictionary<object, object> Result = new Dictionary<object, object>();
            for (int i = 0; i < NumPairs; ++i)
            {
                try
                {
                    Result.Add(ConvertArbitraryCFType(Keys[i]), ConvertArbitraryCFType(Values[i]));
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to properly convert dictionary");
                }
            }

            return Result;
        }
 public static TypedPtr<CFURL> CFURLCreateWithFileSystemPath(IntPtr Allocator, TypedPtr<CFString> FilePath, CFURLPathStyle PathStyle, int isDirectory)
 {
     return (TypedPtr<CFURL>)(CFURLCreateWithFileSystemPath(Allocator, FilePath.Handle, PathStyle, isDirectory));
 }
			public static int FileRefClose(TypedPtr<AFCCommConnection> conn, Int64 handle)
			{
				return AFCFileRefClose((IntPtr)conn, handle);
			}
			public static int FileRefSeek(TypedPtr<AFCCommConnection> conn, Int64 handle, Int64 pos, Int64 origin)
			{
				return AFCFileRefSeek((IntPtr)conn, handle, pos, origin);
			}
 public static int CFDictionaryGetCount(TypedPtr<CFDictionary> Dict)
 {
     return CFDictionaryGetCount((IntPtr)Dict);
 }
			public static int ConnectionOpen(IntPtr handle, uint io_timeout, out TypedPtr<AFCCommConnection> OutConn)
			{
				IntPtr Conn;
				int Result = AFCConnectionOpen(handle, io_timeout, out Conn);
				OutConn = Conn;
				return Result;
			}
			public static int DirectoryOpen(TypedPtr<AFCCommConnection> conn, string path, ref IntPtr dir)
			{
				return AFCDirectoryOpen((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(path), ref dir);
			}
			public static int KeyValueClose(TypedPtr<AFCDictionary> dict)
			{
				return AFCKeyValueClose((IntPtr)dict);
			}
        /// <summary>
        /// Generic progress callback implementation (used for install/uninstall/etc...)
        /// </summary>
        void HandleProgressCallback(string OuterFunction, TypedPtr<CFDictionary> SourceDict)
        {
            Dictionary<string, object> Dict = MobileDevice.ConvertCFDictionaryToDictionaryString(SourceDict);

            // Expecting:
            // string,string -> "Status",PhaseOfInstaller
            // string,number -> "PercentComplete",%Done
            try
            {
                string Phase = Dict["Status"] as string;
                int PercentDone = (int)((Double)(Dict["PercentComplete"]));

                if (OnGenericProgress != null)
                {
                    string Msg = String.Format("{0} is {1}% complete at phase '{2}'", OuterFunction, PercentDone, Phase);
                    OnGenericProgress(Msg, PercentDone);
                }
                else
                {
                    Console.WriteLine(" ... {0} {1}% complete (phase '{2}')", OuterFunction, PercentDone, Phase);
                }
            }
            catch (System.Exception)
            {
            }
        }
        public static string GetStringForUrl(TypedPtr <CFURL> Url)
        {
            TypedPtr <CFString> cfString = CoreImpl.CFURLGetString((IntPtr)Url);

            return(CFStringGetCString((IntPtr)cfString));
        }
        /// <summary>
        /// Close the AFC connection
        /// </summary>
        public void Disconnect()
        {
            if (AFCCommsHandle.Handle != IntPtr.Zero)
            {
				MobileDevice.DeviceImpl.ConnectionClose(AFCCommsHandle);
				MobileDevice.DeviceImpl.StopSession(iPhoneHandle);
				MobileDevice.DeviceImpl.Disconnect(iPhoneHandle);
            }

            AFCCommsHandle = IntPtr.Zero;
        }
			public static int DirectoryCreate(TypedPtr<AFCCommConnection> conn, string path)
			{
				return AFCDirectoryCreate((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(path));
			}
 public void CFDictionaryGetKeysAndValues(TypedPtr <CFDictionary> Dict, /*const*/ IntPtr[] Keys, /*const*/ IntPtr[] Values)
 {
     CoreFoundation.CFDictionaryGetKeysAndValues((IntPtr)Dict, Keys, Values);
 }
			public static int RemovePath(TypedPtr<AFCCommConnection> conn, string path)
			{
				return AFCRemovePath((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(path));
			}
			public static int RenamePath(TypedPtr<AFCCommConnection> conn, string OldPath, string NewPath)
			{
				return AFCRenamePath((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(OldPath), MobileDevice.StringToFileSystemRepresentation(NewPath));
			}
			public static int FlushData(TypedPtr<AFCCommConnection> conn, Int64 handle)
			{
				return AFCFlushData((IntPtr)conn, handle);
			}
			public static int DirectoryClose(TypedPtr<AFCCommConnection> conn, IntPtr dir)
			{
				return AFCDirectoryClose((IntPtr)conn, dir);
			}
        public static string CFStringGetCString(TypedPtr<CFString> InString)
        {
            byte[] bytes = new byte[2048];
            CFStringGetCString(InString.Handle, bytes, 2048, CFStringBuiltInEncodings.kCFStringEncodingUTF8);

            int ValidLength = 0;
            foreach (byte b in bytes)
            {
                if (b == 0)
                {
                    break;
                }
                else
                {
                    ValidLength++;
                }
            }

            return Encoding.UTF8.GetString(bytes, 0, ValidLength);
        }
 public static int CFDictionaryGetCount(TypedPtr <CFDictionary> Dict)
 {
     return(CoreImpl.CFDictionaryGetCount(Dict));
 }
			public static int KeyValueRead(TypedPtr<AFCDictionary> dict, out IntPtr key, out IntPtr val)
			{
				return AFCKeyValueRead((IntPtr)dict, out key, out val);
			}
			public static int FileRefSetFileSize(TypedPtr<AFCCommConnection> conn, Int64 handle, uint size)
			{
				return AFCFileRefSetFileSize((IntPtr)conn, handle, size);
			}
			public static int FileRefRead(TypedPtr<AFCCommConnection> conn, Int64 handle, byte[] buffer, ref uint len)
			{
				return AFCFileRefRead((IntPtr)conn, handle, buffer, ref len);
			}
        public static Dictionary <string, object> ConvertCFDictionaryToDictionaryString(TypedPtr <CFDictionary> Dict)
        {
            Dictionary <string, object> Result = new Dictionary <string, object>();
            Dictionary <object, object> Temp   = ConvertCFDictionaryToDictionary(Dict);

            foreach (KeyValuePair <object, object> KVP in Temp)
            {
                string Key = (string)KVP.Key;
                Result.Add(Key, KVP.Value);
            }

            return(Result);
        }
			public static int FileRefOpen(TypedPtr<AFCCommConnection> conn, string path, Int64 mode, out Int64 handle)
			{
				return AFCFileRefOpen((IntPtr)conn, MobileDevice.StringToFileSystemRepresentation(path), mode, out handle);
			}
 public static void CFDictionaryAddHelper(TypedPtr <CFDictionary> InDict, string Key, string Value)
 {
     CoreImpl.CFDictionarySetValue((IntPtr)InDict, (IntPtr)CFStringMakeConstantString(Key), (IntPtr)CFStringMakeConstantString(Value));
 }
			public static int FileRefWrite(TypedPtr<AFCCommConnection> conn, Int64 handle, byte[] buffer, uint len)
			{
				return AFCFileRefWrite((IntPtr)conn, handle, buffer, len);
			}