<|start_filename|>Madb.Site/Extensions/UrlHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Camalot.Common.Extensions;
using Camalot.Common.Mvc.Extensions;

namespace Madb.Site.Extensions {
	public static partial class MadbSiteExtensions {
		public static string ParseReferenceUrl(this UrlHelper helper, string url ) {
			if(url.IsMatch("^!:")) {
				return url.Substring(2);
			} else if ( url.IsMatch("^(T|M|P):")) {
				var skipped = url.Substring(2);
				// is it msdn link?
				if(url.IsMatch(@"^T\:System\.")) {
					var baseUrl = "http://msdn.microsoft.com/en-us/library/{0}.aspx";
					return baseUrl.With(skipped.ToLowerInvariant());
				}
				return "#{0}".With(skipped.Slug());
			} else {
				return url;
			}
		}

		public static string ParseReferenceAsText(this UrlHelper helper, string url) {
			if(url.IsMatch("^(!|T|M|P):")) {
				return "{0}".With(url.Substring(2));
			} else {
				return url;
			}
		}

		public static string UrlForType(this UrlHelper helper, Type type) {
			var baseDocumentationNamespace = helper.RequestContext.RouteData.GetRequiredString("id");
			if(type.IsInNamespace(baseDocumentationNamespace) || type.IsInChildNamespace(baseDocumentationNamespace)) {
				// local type
				return "#{0}".With(type.ToSafeFullName().Slug());
			} else {
				// remote type
				if(type.IsGenericType) {
					return "http://social.msdn.microsoft.com/Search/en-US?query={0}&ac=3".With(type.ToSafeFullName());
				} else {
					return "http://msdn.microsoft.com/en-us/library/{0}.aspx".With(type.ToSafeUrlFullName().ToLowerInvariant());
				}
			}
		}
	}
}

<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetPathWithoutFile.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetPathWithoutFile {
		[Fact]
		public void WhenPathIsNull_ShouldReturnNull() {
			Assert.Null ( LinuxPath.GetPathWithoutFile ( null ) );
		}

		[Fact]
		public void WhenPathContainsFile_ShouldReturnPath ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "path1-" );
			var p2 = fixture.Create ( "path2-" );
			var f1 = fixture.Create ( "file-" );
			var p = "/{0}/{1}/{2}".With ( p1, p2, f1 );
			var result = LinuxPath.GetPathWithoutFile ( p );
			Assert.Equal ( "/{0}/{1}/".With ( p1, p2 ), result );
		}

		[Fact]
		public void WhenPathContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.GetPathWithoutFile ( "/{0}-{1}/".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "path1" ) ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}
	}
}


<|start_filename|>Madb.Site/Views/Shared/Paypal.cshtml<|end_filename|>
﻿<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" class="mbn pan mrl">
	<input type="hidden" name="cmd" value="_s-xclick">
	<input type="hidden" name="hosted_button_id" value="UEDUKDNL78GR8">
	<button class="transparent man pan" type="submit" name="submit" title="Donate to EndpointMvc"><img src="//www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" alt="Paypal" /></button>
	<img alt="" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

<|start_filename|>Managed.AndroidDebugBridge/Extensions/ReflectionHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {
		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="type">The type.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this Type type ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( type, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="module">The module.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this Module module ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( module, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="mi">The mi.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this MemberInfo mi ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( mi, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="mi">The mi.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this MethodInfo mi ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( mi, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="pi">The pi.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this PropertyInfo pi ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( pi, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="pi">The pi.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this ParameterInfo pi ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( pi, typeof ( T ) );
		}

		/// <summary>
		/// Gets the custom attributes.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="fi">The fi.</param>
		/// <returns></returns>
		public static IEnumerable<T> GetCustomAttributes<T> ( this FieldInfo fi ) where T : Attribute {
			return (IEnumerable<T>)Attribute.GetCustomAttributes ( fi, typeof ( T ) );
		}
		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="type">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this Type type ) where T : Attribute {
			return GetCustomAttributes<T> ( type ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="module">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this Module module ) where T : Attribute {
			return GetCustomAttributes<T> ( module ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="mi">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this MemberInfo mi ) where T : Attribute {
			return GetCustomAttributes<T> ( mi ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="mi">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this MethodInfo mi ) where T : Attribute {
			return GetCustomAttributes<T> ( mi ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="pi">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this PropertyInfo pi ) where T : Attribute {
			return GetCustomAttributes<T> ( pi ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="pi">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this ParameterInfo pi ) where T : Attribute {
			return GetCustomAttributes<T> ( pi ).FirstOrDefault ( );
		}

		/// <summary>
		/// Gets the custom attribute.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="fi">The type.</param>
		/// <returns></returns>
		public static T GetCustomAttribute<T> ( this FieldInfo fi ) where T : Attribute {
			return GetCustomAttributes<T> ( fi ).FirstOrDefault ( );
		}

		/// <summary>
		/// Determines whether the specified type is nullable.
		/// </summary>
		/// <param name="type">The type.</param>
		/// <returns>
		///   <c>true</c> if the specified type is nullable; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsNullable ( this Type type ) {
			return ( type.IsGenericType && type.GetGenericTypeDefinition ( ).Equals ( typeof ( Nullable<> ) ) );
		}

		/// <summary>
		/// Gets member info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="members">The members.</param>
		/// <returns></returns>
		public static IEnumerable<MemberInfo> WithAttribute<T> ( this IEnumerable<MemberInfo> members ) where T : Attribute {
			return members.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets field info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="fields">The fields.</param>
		/// <returns></returns>
		public static IEnumerable<FieldInfo> WithAttribute<T> ( this IEnumerable<FieldInfo> fields ) where T : Attribute {
			return fields.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets module info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="modules">The modules.</param>
		/// <returns></returns>
		public static IEnumerable<Module> WithAttribute<T> ( this IEnumerable<Module> modules ) where T : Attribute {
			return modules.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets method info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="methods">The methods.</param>
		/// <returns></returns>
		public static IEnumerable<MethodInfo> WithAttribute<T> ( this IEnumerable<MethodInfo> methods ) where T : Attribute {
			return methods.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets parameter info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public static IEnumerable<ParameterInfo> WithAttribute<T> ( this IEnumerable<ParameterInfo> parameters ) where T : Attribute {
			return parameters.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets property info that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="properties">The properties.</param>
		/// <returns></returns>
		public static IEnumerable<PropertyInfo> WithAttribute<T> ( this IEnumerable<PropertyInfo> properties ) where T : Attribute {
			return properties.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets types that have the specified attribute
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="types">The types.</param>
		/// <returns></returns>
		public static IEnumerable<Type> WithAttribute<T> ( this IEnumerable<Type> types ) where T : Attribute {
			return types.Where ( m => m.GetCustomAttribute<T> ( ) != default ( T ) );
		}

		/// <summary>
		/// Gets the methods that have the specified return type.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="type">The type.</param>
		/// <returns></returns>
		public static IEnumerable<MethodInfo> GetMethodsOfReturnType<T> ( this Type type ) {
			return GetMethodsOfReturnType<T> ( type, BindingFlags.Instance | BindingFlags.Public );
		}

		/// <summary>
		/// Gets the methods that have the specified return type.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="type">The type.</param>
		/// <param name="bindingFlags">The binding flags.</param>
		/// <returns></returns>
		public static IEnumerable<MethodInfo> GetMethodsOfReturnType<T> ( this Type type, BindingFlags bindingFlags ) {
			return type.GetMethods ( bindingFlags )
				.Where ( m => m.ReturnType.IsAssignableFrom ( typeof ( T ) ) )
				.Select ( m => m );
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/BatteryInfo.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class BatteryInfo {
		/// <summary>
		/// Battery Status Types
		/// </summary>
		public enum StatusTypes {
			/// <summary>
			/// Unknown Status
			/// </summary>
			Unknown = 1,
			/// <summary>
			/// Charging
			/// </summary>
			Charging = 2,
			/// <summary>
			/// Discharging
			/// </summary>
			Discharging = 3,
			/// <summary>
			/// Discharging
			/// </summary>
			NotCharging = 4,
			/// <summary>
			/// Battery Full
			/// </summary>
			Full = 5
		}

		/// <summary>
		/// Battery Health Types
		/// </summary>
		public enum HealthTypes {
			/// <summary>
			/// Unknown Health
			/// </summary>
			Unknown = 1,
			/// <summary>
			/// Good
			/// </summary>
			Good = 2,
			/// <summary>
			/// Overheating
			/// </summary>
			Overheat = 3,
			/// <summary>
			/// Cold
			/// </summary>
			Cold = 4,
			/// <summary>
			/// Over voltage
			/// </summary>
			OverVoltage = 5,
			/// <summary>
			/// Unspecified Failure
			/// </summary>
			UnspecifiedFailure = 6
		}

		/// <summary>
		/// Gets or sets a value indicating whether AC powered.
		/// </summary>
		/// <value>
		///   <c>true</c> if AC powered; otherwise, <c>false</c>.
		/// </value>
		public bool ACPowered { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether usb powered.
		/// </summary>
		/// <value>
		///   <c>true</c> if usb powered; otherwise, <c>false</c>.
		/// </value>
		public bool UsbPowered { get; set; }
		/// <summary>
		/// Gets or sets the status.
		/// </summary>
		/// <value>
		/// The status.
		/// </value>
		public StatusTypes Status { get; set; }
		/// <summary>
		/// Gets or sets the health.
		/// </summary>
		/// <value>
		/// The health.
		/// </value>
		public HealthTypes Health { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether a battery is present.
		/// </summary>
		/// <value>
		///   <c>true</c> if present; otherwise, <c>false</c>.
		/// </value>
		public bool Present { get; set; }
		/// <summary>
		/// Gets or sets the level.
		/// </summary>
		/// <value>
		/// The level.
		/// </value>
		public int Level { get; set; }
		/// <summary>
		/// Gets or sets the scale.
		/// </summary>
		/// <value>
		/// The scale.
		/// </value>
		public int Scale { get; set; }
		/// <summary>
		/// Gets or sets the voltage.
		/// </summary>
		/// <value>
		/// The voltage.
		/// </value>
		public int Voltage { get; set; }
		/// <summary>
		/// Gets or sets the temperature.
		/// </summary>
		/// <value>
		/// The temperature.
		/// </value>
		public int Temperature { get; set; }
		/// <summary>
		/// Gets or sets the type.
		/// </summary>
		/// <value>
		/// The type.
		/// </value>
		public String Type { get; set; }

		/// <summary>
		/// Gets the calculated battery level.
		/// </summary>
		/// <value>
		/// The calculated level.
		/// </value>
		public int CalculatedLevel {
			get {
				return ( Level * 100 ) / Scale;
			}
		}

		/// <summary>
		/// Returns a <see cref="System.String" /> that represents this instance.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String" /> that represents this instance.
		/// </returns>
		public override string ToString ( ) {
			var sb = new StringBuilder ( );

			this.GetType ( ).GetProperties ( BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.IgnoreCase ).ForEach ( p => {
				var n = p.Name;
				var v = p.GetValue ( this, null );
				sb.AppendLine ( String.Format ( "{0}:{1}", n, v ) );
			} );

			return sb.ToString ( );
		}
	}
}


<|start_filename|>Madb.Site/assets/styles/bootstrap-overrides.css<|end_filename|>
﻿.btn.btn-tiny {
	padding: 3px 3px;
}

.btn.btn-small {
	padding-bottom: 1px;
}


.navbar-brand {
	padding: 1px 0 1px 0;
	height: auto;
}

.nav a:hover .caret.white,
.nav a .caret.white {
	border-top-color: #fff;
	border-bottom-color: #fff;
}

.close {
	line-height: 0.75;
	outline: none;
}

:active, :focus {
	outline: none;
}

.input-lg {
	padding: 6px 16px;
}

.tab-pane.active .table {
	margin-top: -1px;
}




<|start_filename|>Managed.AndroidDebugBridge/FileEntry.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Managed.Adb.IO;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// Represents a file entry on a device
	/// </summary>
	public class FileEntry {

		/// <summary>
		/// Finds the file entry, or creates an empty FileEntry if it does not exist.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="path">The path.</param>
		/// <remarks>This does not create the FileEntry on disk. It only creates the FileEntry object.</remarks>
		/// <returns></returns>
		public static FileEntry FindOrCreate ( Device device, string path ) {
			device.ThrowIfNull ( "device" );
			path.ThrowIfNullOrEmpty ( "path" );

			if ( !device.IsOffline ) {
				try {
					return device.FileListingService.FindFileEntry ( path );
				} catch ( FileNotFoundException ) {
					var fe = new FileEntry ( device, path );
					fe.Create ( );
					return fe;
				}
			} else {
				throw new IOException ( "Device is not online" );
			}
		}

		/// <summary>
		/// Creates the the FileEntry without permissions specified.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public static FileEntry CreateNoPermissions ( Device device, string path ) {
			var fe = new FileEntry ( device, path );
			fe.Permissions = new FilePermissions ( );
			return fe;
		}

		/// <summary>
		/// Gets a file entry from the specified path on the device.
		/// </summary>
		/// <param name="device">The device to check</param>
		/// <param name="path">the path to check</param>
		/// <exception cref="IOException">If the device is not connected.</exception>
		/// <exception cref="ArgumentNullException">If the device or path is null.</exception>
		/// <exception cref="FileNotFoundException">If the entrty is not found.</exception>
		/// <returns></returns>
		public static FileEntry Find ( Device device, string path ) {
			device.ThrowIfNull ( "device" );
			path.ThrowIfNullOrEmpty ( "path" );

			if ( !device.IsOffline ) {
				return device.FileListingService.FindFileEntry ( path );
			} else {
				throw new IOException ( "Device is not online" );
			}
		}



		/// <summary>
		/// Creates a new file entry.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="parent">parent entry or null if entry is root</param>
		/// <param name="name">name of the entry.</param>
		/// <param name="type">entry type.</param>
		/// <param name="isRoot">if set to <c>true</c> [is root].</param>
		internal FileEntry ( Device device, FileEntry parent, string name, FileListingService.FileTypes type, bool isRoot ) {
			this.FetchTime = 0;
			this.Parent = parent;
			this.Name = name;
			this.Type = type;
			this.IsRoot = isRoot;
			Children = new List<FileEntry> ( );
			CheckAppPackageStatus ( );
			this.Exists = true;
			this.Device = device;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FileEntry"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="path">The path.</param>
		internal FileEntry ( Device device, string path ) {
			this.FetchTime = 0;
			this.Parent = null;
			bool isDir = path.EndsWith ( new string ( LinuxPath.DirectorySeparatorChar, 1 ) );
			this.Name = isDir ? LinuxPath.GetDirectoryName ( path ) : LinuxPath.GetFileName ( path );
			this.IsRoot = path.Length == 1 && path[0] == LinuxPath.DirectorySeparatorChar;
			this.Type = isDir ? FileListingService.FileTypes.Directory : FileListingService.FileTypes.File;
			this.Size = 0;
			this.Children = new List<FileEntry> ( );
			this.Exists = false;
			this.Device = device;
		}


		/// <summary>
		/// Gets the device associated with this file entry.
		/// </summary>
		public Device Device { get; private set; }
		/// <summary>
		/// Gets the parent.
		/// </summary>
		public FileEntry Parent { get; private set; }
		/// <summary>
		/// Gets the name.
		/// </summary>
		public string Name { get; private set; }
		/// <summary>
		/// Gets or sets the name of the link.
		/// </summary>
		/// <value>
		/// The name of the link.
		/// </value>
		public string LinkName { get; set; }
		/// <summary>
		/// Gets or sets the info.
		/// </summary>
		/// <value>
		/// The info.
		/// </value>
		public string Info { get; set; }
		/// <summary>
		/// Gets or sets the permissions.
		/// </summary>
		/// <value>
		/// The permissions.
		/// </value>
		public FilePermissions Permissions { get; set; }
		/// <summary>
		/// Gets or sets the size.
		/// </summary>
		/// <value>
		/// The size.
		/// </value>
		public long Size { get; set; }
		/// <summary>
		/// Gets or sets the date.
		/// </summary>
		/// <value>
		/// The date.
		/// </value>
		public DateTime Date { get; set; }
		/// <summary>
		/// Gets or sets the owner.
		/// </summary>
		/// <value>
		/// The owner.
		/// </value>
		public string Owner { get; set; }
		/// <summary>
		/// Gets or sets the group.
		/// </summary>
		/// <value>
		/// The group.
		/// </value>
		public string Group { get; set; }
		/// <summary>
		/// Gets the type.
		/// </summary>
		public FileListingService.FileTypes Type { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance is application package.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is application package; otherwise, <c>false</c>.
		/// </value>
		public bool IsApplicationPackage { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance is root.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance is root; otherwise, <c>false</c>.
		/// </value>
		public bool IsRoot { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance is executable.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is executable; otherwise, <c>false</c>.
		/// </value>
		public bool IsExecutable { get; internal set; }
		/// <summary>
		/// Gets or sets the children.
		/// </summary>
		/// <remarks>Note that this is not populated by default. Use the FileListingService.GetChildren to populate it.</remarks>
		/// <value>
		/// The children.
		/// </value>
		public List<FileEntry> Children { get; set; }
		/// <summary>
		/// Gets a value indicating whether this instance is link.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance is link; otherwise, <c>false</c>.
		/// </value>
		public bool IsLink {
			get {
				return Type == FileListingService.FileTypes.Link || Type == FileListingService.FileTypes.DirectoryLink;
			}
		}



		/// <summary>
		/// Gets a value indicating whether this <see cref="FileEntry"/> is exists.
		/// </summary>
		/// <value>
		///   <c>true</c> if exists; otherwise, <c>false</c>.
		/// </value>
		public bool Exists { get; private set; }


		/// <summary>
		/// Indicates whether the entry content has been fetched yet, or not.
		/// </summary>
		public long FetchTime { get; set; }

		internal bool NeedFetch {
			get {
				if ( FetchTime == 0 ) {
					return true;
				}

				long current = DateTime.Now.CurrentTimeMillis ( );
				if ( current - FetchTime > FileListingService.REFRESH_TEST ) {
					return true;
				}

				return false;
			}
		}

		/// <summary>
		/// Creates the file entry, if it does not exist.
		/// </summary>
		/// <returns></returns>
		public bool Create ( ) {
			try {
				if ( this.Exists ) {
					return true;
				}
				var fe = this.Device.FileSystem.Create ( this );
				return fe.Exists;
			} catch {
				return false;
			}
		}

		/// <summary>
		/// Deletes the file entry from the file system.
		/// </summary>
		/// <returns></returns>
		public bool Delete ( ) {
			try {
				this.Device.FileSystem.Delete ( this.FullEscapedPath );
				return true;
			} catch {
				return false;
			}
		}

		/// <summary>
		/// Adds a child file entry
		/// </summary>
		/// <param name="child">The child file entry</param>
		public void AddChild ( FileEntry child ) {
			Children.Add ( child );
		}


		/// <summary>
		/// Returns the child FileEntry matching the name.
		/// This uses the cached children list.
		/// </summary>
		/// <param name="name">the name of the child to return.</param>
		/// <return>the FileEntry matching the name or null.</return>
		public FileEntry FindChild ( string name ) {
			var entry = Children.Where ( e => string.Compare ( e.Name, name, false ) == 0 ).FirstOrDefault ( );

			return entry;
		}


		/// <summary>
		/// Gets a value indicating whether this instance is directory.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is directory; otherwise, <c>false</c>.
		/// </value>
		public bool IsDirectory {
			get {
				return this.Type == FileListingService.FileTypes.Directory || Type == FileListingService.FileTypes.DirectoryLink;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is application file name.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is application file name; otherwise, <c>false</c>.
		/// </value>
		public bool IsApplicationFileName {
			get {
				Regex regex = new Regex ( FileListingService.APK_FILE_PATTERN, RegexOptions.Compiled );
				return regex.IsMatch ( this.Name );
			}
		}

		/// <summary>
		/// Gets the full path of the entry.
		/// </summary>
		public string FullPath {
			get {
				if ( IsRoot ) {
					return FileListingService.FILE_ROOT;
				}

				StringBuilder pathBuilder = new StringBuilder ( );
				FillPathBuilder ( pathBuilder, false );

				if ( IsDirectory && pathBuilder[pathBuilder.Length - 1] != LinuxPath.DirectorySeparatorChar ) {
					pathBuilder.Append ( LinuxPath.DirectorySeparatorChar );
				}

				return pathBuilder.ToString ( );
			}
		}

		/// <summary>
		/// Gets the full resolved path.
		/// </summary>
		public String FullResolvedPath {
			get {
				if ( IsRoot ) {
					return FileListingService.FILE_ROOT;
				}
				return Device.FileSystem.ResolveLink ( this.FullPath );
			}
		}

		/// <summary>
		/// Gets the fully escaped path of the entry. This path is safe to use in a shell command line.
		/// </summary>
		public string FullEscapedPath {
			get {
				StringBuilder pathBuilder = new StringBuilder ( );
				FillPathBuilder ( pathBuilder, true, true );

				return pathBuilder.ToString ( );
			}
		}

		/// <summary>
		/// Gets the path as a list of segments.
		/// </summary>
		public string[] PathSegments {
			get {
				var list = new List<string> ( );
				FillPathSegments ( list );

				return list.ToArray ( );
			}
		}


		/// <summary>
		/// Sets the internal app package status flag. This checks whether the entry is in an app
		/// directory like /data/app or /system/app or /sd/app or /sd-ext/app. The last two are common for
		/// apps2sd on rooted phones
		/// </summary>
		private void CheckAppPackageStatus ( ) {
			IsApplicationPackage = false;

			string[] segments = PathSegments;
			if ( this.Type == FileListingService.FileTypes.File && segments.Length == 3 && IsApplicationFileName ) {
				IsApplicationPackage = string.Compare ( FileListingService.DIRECTORY_APP, segments[1], false ) == 0 &&
						( string.Compare ( FileListingService.DIRECTORY_SYSTEM, segments[0], false ) == 0 ||
						string.Compare ( FileListingService.DIRECTORY_DATA, segments[0], false ) == 0 ||
						string.Compare ( FileListingService.DIRECTORY_SD, segments[0], false ) == 0 ||
						string.Compare ( FileListingService.DIRECTORY_SDEXT, segments[0], false ) == 0 );
			}
		}

		/// <summary>
		/// Recursively fills the segment list with the full path.
		/// </summary>
		/// <param name="list">The list of segments to fill.</param>
		protected void FillPathSegments ( List<string> list ) {
			if ( IsRoot ) {
				return;
			}

			if ( Parent != null ) {
				Parent.FillPathSegments ( list );
			}

			list.Add ( Name );
		}

		/// <summary>
		/// Recursively fills the pathBuilder with the full path
		/// </summary>
		/// <param name="pathBuilder">a StringBuilder used to create the path.</param>
		/// <param name="escapePath">Whether the path need to be escaped for consumption by a shell command line.</param>
		/// <param name="resolveLinks">if set to <c>true</c> [resolve links].</param>
		protected void FillPathBuilder ( StringBuilder pathBuilder, bool escapePath, bool resolveLinks ) {
			if ( IsRoot ) {
				return;
			}

			if ( Parent != null ) {
				Parent.FillPathBuilder ( pathBuilder, escapePath, resolveLinks );
			}

			string n = resolveLinks && !string.IsNullOrEmpty ( LinkName ) ? LinkName : Name;

			if ( n[0] != LinuxPath.DirectorySeparatorChar ) {
				pathBuilder.Append ( LinuxPath.DirectorySeparatorChar );
			}

			pathBuilder.Append ( escapePath ? LinuxPath.Quote ( n ) : n );
		}

		/// <summary>
		/// Fills the path builder.
		/// </summary>
		/// <param name="pathBuilder">The path builder.</param>
		/// <param name="escapePath">if set to <c>true</c> [escape path].</param>
		protected void FillPathBuilder ( StringBuilder pathBuilder, bool escapePath ) {
			FillPathBuilder ( pathBuilder, escapePath, false );
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public override string ToString ( ) {
			return this.FullResolvedPath;
		}

		/// <summary>
		/// 
		/// </summary>
		public class FileEntryComparer : Comparer<FileEntry> {

			/// <summary>
			/// Compares the specified x.
			/// </summary>
			/// <param name="x">The x.</param>
			/// <param name="y">The y.</param>
			/// <returns></returns>
			public override int Compare ( FileEntry x, FileEntry y ) {
				return x.Name.CompareTo ( y.Name );
			}
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/PackageInstallationException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// An exception while installing a package on the device
	/// </summary>
	[Serializable]
	public class PackageInstallationException : Exception {
		/// <summary>
		/// Initializes a new instance of the <see cref="PackageInstallationException"/> class.
		/// </summary>
		public PackageInstallationException ( ) { }
		/// <summary>
		/// Initializes a new instance of the <see cref="PackageInstallationException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		public PackageInstallationException ( string message ) : base ( message ) { }
		/// <summary>
		/// Initializes a new instance of the <see cref="PackageInstallationException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="inner">The inner.</param>
		public PackageInstallationException ( string message, Exception inner ) : base ( message, inner ) { }
		/// <summary>
		/// Initializes a new instance of the <see cref="PackageInstallationException"/> class.
		/// </summary>
		/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
		/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
		/// <exception cref="T:System.ArgumentNullException">
		/// The <paramref name="info"/> parameter is null.
		///   </exception>
		///   
		/// <exception cref="T:System.Runtime.Serialization.SerializationException">
		/// The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0).
		///   </exception>
		protected PackageInstallationException (
		System.Runtime.Serialization.SerializationInfo info,
		System.Runtime.Serialization.StreamingContext context )
			: base ( info, context ) { }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/FileListingService.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using Managed.Adb.IO;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// Provides Device side file listing service.
	/// </summary>
	public class FileListingService {
		/// <summary>
		/// 
		/// </summary>
		public const string APK_FILE_PATTERN = ".*\\.apk";

		/// <summary>
		/// 
		/// </summary>
		public const String PM_FULL_LISTING = "pm list packages -f";

		/// <summary>
		/// This is the pattern that supports busybox ls and toolbox ls.
		/// Groups
		/// <ol>
		///		<li>Permissions</li>
		///		<li>Group</li>
		///		<li>Owner</li>
		///		<li>Size, if empty or whitespace use 0</li>
		///		<li>Month Name (or year in toolbox ls)</li>
		///		<li>Date (or month number in toolbox ls)</li>
		///		<li>Year, if empty, use current year (or date number in toolbox ls)</li>
		///		<li>Time, if empty, use 00:00</li>
		///		<li>Name</li>
		///		<li>File types (or empty in toolbox ls)</li>
		/// </ol>
		/// 
		/// </summary>
		/// <remarks>
		/// added non-capture "(?:\d{1,},\s+)?" for "blocks"
		/// </remarks>
		public const String LS_PATTERN_EX = @"^([bcdlsp-][-r][-w][-xsS][-r][-w][-xsS][-r][-w][-xstST])\s+(?:\d{0,})?\s*(\S+)\s+(\S+)\s+(?:\d{1,},\s+)?(\d{1,}|\s)\s+(\w{3}|\d{4})[\s-](?:\s?(\d{1,2})\s?)[\s-]\s?(?:(\d{2}|\d{4}|\s)\s*)?(\d{2}:\d{2}|\s)\s*(.*?)([/@=*\|]?)$";

		/// <summary>
		///  Top level data folder.
		/// </summary>
		public const String DIRECTORY_DATA = "data";
		/// <summary>
		/// Top level sdcard folder.
		/// </summary>
		public const String DIRECTORY_SDCARD = "sdcard";
		/// <summary>
		/// Top level mount folder.
		/// </summary>
		public const String DIRECTORY_MNT = "mnt";
		/// <summary>
		/// Top level system folder.
		/// </summary>
		public const String DIRECTORY_SYSTEM = "system";
		/// <summary>
		/// Top level temp folder.
		/// </summary>
		public const String DIRECTORY_TEMP = "tmp";
		/// <summary>
		/// Application folder. 
		/// </summary>
		public const String DIRECTORY_APP = "app";

		/// <summary>
		/// 
		/// </summary>
		public const String DIRECTORY_SD = "sdcard";

		/// <summary>
		/// 
		/// </summary>
		public const String DIRECTORY_SDEXT = "sd-ext";


		/// <summary>
		/// 
		/// </summary>
		public const long REFRESH_RATE = 5000L;
		/// <summary>
		/// 
		/// </summary>
		public const long REFRESH_TEST = (long)( REFRESH_RATE * .8 );

		/// <summary>
		/// 
		/// </summary>
		public const String FILE_SEPARATOR = "/";
		/// <summary>
		/// 
		/// </summary>
		public const String FILE_ROOT = "/";

		/// <summary>
		/// 
		/// </summary>
		public const String BUSYBOX_LS = "busybox ls -lFa --color=never {0}";
		/// <summary>
		/// 
		/// </summary>
		public const String TOOLBOX_LS = "ls -la {0}";

		/// <summary>
		/// 
		/// </summary>
		public static readonly String[] RootLevelApprovedItems = {
				DIRECTORY_DATA,
				DIRECTORY_SDCARD,
				DIRECTORY_SYSTEM,
				DIRECTORY_TEMP,
				DIRECTORY_MNT,
				// ADDED
				DIRECTORY_APP
		};

		/// <summary>
		/// 
		/// </summary>
		public enum FileTypes {
			/// <summary>
			/// 
			/// </summary>
			File = 0,
			/// <summary>
			/// 
			/// </summary>
			Directory = 1,
			/// <summary>
			/// 
			/// </summary>
			DirectoryLink = 2,
			/// <summary>
			/// 
			/// </summary>
			Block = 3,
			/// <summary>
			/// 
			/// </summary>
			Character = 4,
			/// <summary>
			/// 
			/// </summary>
			Link = 5,
			/// <summary>
			/// 
			/// </summary>
			Socket = 6,
			/// <summary>
			/// 
			/// </summary>
			FIFO = 7,
			/// <summary>
			/// 
			/// </summary>
			Other = 8
		}

		/// <summary>
		/// 
		/// </summary>
		private FileEntry _root = null;

		/// <summary>
		/// Initializes a new instance of the <see cref="FileListingService"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="forceBusyBox">if set to <c>true</c> [force busy box].</param>
		public FileListingService ( Device device, bool forceBusyBox ) {
			this.Device = device;
			this.Threads = new List<Thread> ( );
			this.ForceBusyBox = forceBusyBox && device.BusyBox.Available;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FileListingService"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public FileListingService ( Device device )
			: this ( device, device.BusyBox.Available ) {

		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>The device.</value>
		public Device Device { get; private set; }
		/// <summary>
		/// Gets or sets the root.
		/// </summary>
		/// <value>The root.</value>
		public FileEntry Root {
			get {
				if ( Device != null ) {
					if ( _root == null ) {
						_root = new FileEntry ( this.Device, null /* parent */, string.Empty /* name */, FileTypes.Directory, true /* isRoot */ );
					}
					return _root;
				}
				return null;
			}
			private set {
				_root = value;
			}
		}

		/// <summary>
		/// Gets or sets a value indicating whether [force busy box].
		/// </summary>
		/// <value><c>true</c> if [force busy box]; otherwise, <c>false</c>.</value>
		public bool ForceBusyBox { get; set; }


		/// <summary>
		/// Gets the children.
		/// </summary>
		/// <param name="entry">The entry.</param>
		/// <param name="useCache">if set to <c>true</c> [use cache].</param>
		/// <param name="receiver">The receiver.</param>
		/// <returns></returns>
		public FileEntry[] GetChildren ( FileEntry entry, bool useCache, IListingReceiver receiver ) {
			// first thing we do is check the cache, and if we already have a recent
			// enough children list, we just return that.
			if ( useCache && !entry.NeedFetch ) {
				return entry.Children.ToArray ( );
			}

			// if there's no receiver, then this is a synchronous call, and we
			// return the result of ls
			if ( receiver == null ) {
				DoLS ( entry );
				return entry.Children.ToArray ( );
			}

			// this is a asynchronous call.
			// we launch a thread that will do ls and give the listing
			// to the receiver
			Thread t = new Thread ( new ParameterizedThreadStart ( delegate ( object stateData ) {
				var state = stateData as ThreadState;

				DoLS ( entry );

				receiver.SetChildren ( state.Entry, state.Entry.Children.ToArray ( ) );

				FileEntry[] children = state.Entry.Children.ToArray ( );
				if ( children.Length > 0 && children[0].IsApplicationPackage ) {
					var map = new Dictionary<String, FileEntry> ( );

					children.ForEach ( child => {
						map.Add ( child.FullPath, child );
					} );

					// call pm.
					String command = PM_FULL_LISTING;
					try {
						this.Device.ExecuteShellCommand ( command, new PackageManagerListingReceiver ( map, receiver ) );
					} catch ( IOException e ) {
						// adb failed somehow, we do nothing.
						Log.e ( "FileListingService", e );
					}
				}


				// if another thread is pending, launch it
				lock ( Threads ) {
					// first remove ourselves from the list
					Threads.Remove ( state.Thread );

					// then launch the next one if applicable.
					if ( Threads.Count > 0 ) {
						Thread ct = Threads[0];
						ct.Start ( new ThreadState { Thread = ct, Entry = entry } );
					}
				}

			} ) );
			t.Name = "ls " + entry.FullPath;

			// we don't want to run multiple ls on the device at the same time, so we
			// store the thread in a list and launch it only if there's no other thread running.
			// the thread will launch the next one once it's done.
			lock ( Threads ) {
				// add to the list
				Threads.Add ( t );

				// if it's the only one, launch it.
				if ( Threads.Count == 1 ) {
					t.Start ( new ThreadState { Thread = t } );
				}
			}

			// and we return null.
			return null;
		}

		/// <summary>
		/// Gets or sets the threads.
		/// </summary>
		/// <value>The threads.</value>
		private List<Thread> Threads { get; set; }

		/// <summary>
		/// Does the LS.
		/// </summary>
		/// <param name="entry">The entry.</param>
		private void DoLS ( FileEntry entry ) {
			// create a list that will receive the list of the entries
			List<FileEntry> entryList = new List<FileEntry> ( );

			// create a list that will receive the link to compute post ls;
			List<String> linkList = new List<String> ( );

			try {
				// create the command
				String command = String.Format ( ForceBusyBox ? BUSYBOX_LS : TOOLBOX_LS, entry.FullPath );
				// create the receiver object that will parse the result from ls
				ListingServiceReceiver receiver = new ListingServiceReceiver ( entry, entryList, linkList );

				// call ls.
				Device.ExecuteShellCommand ( command, receiver );

				// finish the process of the receiver to handle links
				receiver.FinishLinks ( );
			} catch ( IOException e ) {
				Log.e ( "ddms", e );
				throw;
			}


			// at this point we need to refresh the viewer
			entry.FetchTime = DateTime.Now.CurrentTimeMillis ( );
			// sort the children and set them as the new children
			entryList.Sort ( new FileEntry.FileEntryComparer ( ) );
			entry.Children = entryList;
		}

		/// <summary>
		/// 
		/// </summary>
		private class ThreadState {
			/// <summary>
			/// 
			/// </summary>
			public Thread Thread;
			/// <summary>
			/// 
			/// </summary>
			public FileEntry Entry;

		}

		/// <summary>
		/// Finds an entry from the path.
		/// </summary>
		/// <param name="path">The file path of</param>
		/// <returns>The FileEntry</returns>
		/// <exception cref="FileNotFoundException">Throws if unable to locate the file or directory</exception>
		public FileEntry FindFileEntry ( String path ) {
			return FindFileEntry ( this.Root, path );
		}

		/// <summary>
		/// Finds the file entry.
		/// </summary>
		/// <param name="parent">The parent.</param>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public FileEntry FindFileEntry ( FileEntry parent, String path ) {
			var rpath = Device.FileSystem.ResolveLink ( path );
			var entriesString = rpath.Split ( new char[] { LinuxPath.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries );
			FileEntry current = parent;


			foreach ( var pathItem in entriesString ) {
				FileEntry[] entries = GetChildren ( current, true, null );
				foreach ( var e in entries ) {
					if ( String.Compare ( e.Name, pathItem, false ) == 0 ) {
						current = e;
						break;
					}
				}
			}

			// better checking if the file is the "same" based on the link or the reference
			if ( ( String.Compare ( current.FullPath, path, false ) == 0 ||
				String.Compare ( current.FullResolvedPath, path, false ) == 0 ||
				String.Compare ( current.FullPath, rpath, false ) == 0 ||
				String.Compare ( current.FullResolvedPath, rpath, false ) == 0 ) ) {
				return current;
			} else {
				throw new FileNotFoundException ( String.Format ( "Unable to locate {0}", path ) );
			}
		}
	}
}


<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/ParameterModel.cshtml<|end_filename|>
﻿@using Madb.Site.Models.Documentation;
@using Madb.Site.Extensions;
@using Camalot.Common.Extensions;
@using Camalot.Common.Mvc.Extensions;
@model ParameterModel
<!--
--><span class="parameter @(Model.IsOptional ? "parameter-optional" : "")">
	@Html.DisplayFor(m => Model.Type.BaseType)
	@Html.Icon("fa-forward", Model.IsIn, "In")
	@Html.Icon("fa-reply", Model.IsIn, "Out")
	<span class="parameter-name">@Model.Name</span>
</span>

<|start_filename|>Managed.AndroidDebugBridge/Logs/ILogListener.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Logs {
	/// <summary>
	/// 
	/// </summary>
	public interface ILogListener {
		/// <summary>
		/// Sent when a new LogEntry has been parsed by the LogReceiver.
		/// </summary>
		/// <param name="entry">entry the new log entry.</param>
		void NewEntry ( LogEntry entry );
		/// <summary>
		/// Sent when new raw data is coming from the log service.
		/// </summary>
		/// <param name="data">the raw data buffer.</param>
		/// <param name="offset">the offset into the buffer signaling the beginning of the new data.</param>
		/// <param name="length">the length of the new data.</param>
		void NewData ( byte[] data, int offset, int length );
	}
}


<|start_filename|>Madb.Site/assets/styles/main.css<|end_filename|>
﻿body {
  padding-bottom: 40px;
  padding-top: 40px;
  cursor: default;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.root.container {
  width: auto;
  padding-right: 60px;
  padding-left: 60px;
  margin-right: auto;
  margin-left: auto;
  -moz-transition: margin linear 300ms;
  -o-transition: margin linear 300ms;
  -webkit-transition: margin linear 300ms;
  transition: margin linear 300ms;
}
@media (min-width: 992px) {
  .root.container.epm-nav-expanded.right {
    margin-right: 310px;
  }
  .root.container.epm-nav-expanded.left {
    margin-left: 310px;
  }
}
@media (min-width: 1200px) {
  .root.container.epm-nav-expanded.right {
    margin-right: 310px;
  }
  .root.container.epm-nav-expanded.left {
    margin-left: 310px;
  }
}
.icon-camalotcommon {
  background-image: url("//camalotcommon.bit13.com/assets/images/icon-16.png");
  background-repeat: no-repeat;
  height: 16px;
  width: 16px;
  display: inline-block;
}
.icon-endpointmvc {
  background-image: url("//endpointmvc.bit13.com/assets/images/endpointmvc-16.png");
  background-repeat: no-repeat;
  height: 16px;
  width: 16px;
  display: inline-block;
}
.logo {
  background-image: url(../images/madbee-114.png);
  background-repeat: no-repeat;
  background-position: center center;
  height: 114px;
  width: 114px;
  margin-right: 20px;
  display: inline-block;
  opacity: 1;
  -moz-transition: opacity linear 300ms;
  -o-transition: opacity linear 300ms;
  -webkit-transition: opacity linear 300ms;
  transition: opacity linear 300ms;
}
.logo.small {
  background-image: url(../images/madbee-32.png);
  height: 32px;
  width: 32px;
}
.logo.logo-hidden {
  opacity: 0;
}
.divider-vertical {
  width: 1px;
  border: none;
  border-left: solid 1px #2371f2;
  height: 42px;
  margin: 3px;
}
.transparent {
  background-color: transparent;
  border: 0;
}
.cursor-help {
  cursor: help;
}
.expandable-label {
  position: relative;
  white-space: nowrap;
  display: inline-block;
  -moz-transition: all ease-in-out 300ms;
  -o-transition: all ease-in-out 300ms;
  -webkit-transition: all ease-in-out 300ms;
  transition: all ease-in-out 300ms;
}
.expandable-label:hover .label {
  width: 100%;
  margin-left: 5px;
}
.expandable-label .label {
  position: relative;
  display: inline-block;
  overflow: hidden;
  margin: 0;
  font-weight: normal;
  color: inherit;
  font-size: 1em;
  border-radius: 0;
  text-align: left;
  width: 0;
  padding: 0;
  -moz-transition: all ease-in-out 300ms;
  -o-transition: all ease-in-out 300ms;
  -webkit-transition: all ease-in-out 300ms;
  transition: all ease-in-out 300ms;
}
.go-to-top {
  position: fixed;
  left: 30px;
  bottom: 60px;
  z-index: 9999;
}
.go-to-top a.btn-round {
  box-shadow: 0 0.2em 0.5em 0 rgba(0, 0, 0, 0.258824);
}
.metro-nav {
  margin: 0 0 20px 0;
  padding: 0;
}
.metro-nav > ul.nav > li {
  font-size: 2em;
  margin: 0 0 2px 0;
  padding: 0;
}
.metro-nav > ul.nav > li > .alert {
  margin: 0 3px 0 0;
}
.panel-body > .page-header:first-child {
  margin-top: 0;
}
/*# sourceMappingURL=main.css.map */

<|start_filename|>Madb.Site/Views/Shared/_AddThisCountPartial.cshtml<|end_filename|>
﻿<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
	<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
	<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
	<a class="addthis_button_tweet"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-535d35480aa7de98"></script>
<!-- AddThis Button END -->

<|start_filename|>Madb.Site/assets/Scripts/system.scroll-show.js<|end_filename|>
﻿(function ($, document, window) {
	"use strict";
	$(function () {
		$(document).on("scroll", function () {
			var scrollPosition = $(this).scrollTop();
			$("[data-scroll-show-low]").each(function () {
				var self = $(this);
				var low = parseInt(self.data("scroll-show-low") || "0", 0);
				var high = parseInt(self.data("scroll-show-high") || "-1", 0);
				var toggle = self.data("scroll-toggle") || "hidden";
				if ( (scrollPosition >= low || low < 0 ) && ( scrollPosition <= high || high < 0 )) {
					self.removeClass(toggle);
				} else {
					self.addClass(toggle);
				}
			});
		});
	});
})(window.jQuery, window.document, window);

<|start_filename|>Managed.AndroidDebugBridge/Extensions/StringHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {
		/// <summary>
		/// Gets the bytes from a string.
		/// </summary>
		/// <param name="str">The string.</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns></returns>
		public static byte[] GetBytes ( this string str, string encoding ) {
			Encoding enc = Encoding.GetEncoding ( encoding );

			return enc.GetBytes ( str );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes ) {
			return GetString ( bytes, Encoding.Default );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes, Encoding encoding ) {
			return encoding.GetString ( bytes, 0, bytes.Length );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes, string encoding ) {
			Encoding enc = Encoding.GetEncoding ( encoding );
			return GetString ( bytes, enc );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="index">The index.</param>
		/// <param name="count">The count.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes, int index, int count ) {
			return GetString ( bytes, index, count, Encoding.Default );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="index">The index.</param>
		/// <param name="count">The count.</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes, int index, int count, Encoding encoding ) {
			return encoding.GetString ( bytes, index, count );
		}
		/// <summary>
		/// Gets the string from a byte array.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="index">The index.</param>
		/// <param name="count">The count.</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns></returns>
		public static string GetString ( this byte[] bytes, int index, int count, string encoding ) {
			Encoding enc = Encoding.GetEncoding ( encoding );
			return GetString ( bytes, index, count, enc );
		}


	}
}


<|start_filename|>Managed.AndroidDebugBridge/LogLevel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public static class LogLevel {

		/// <summary>
		/// Initializes the <see cref="LogLevel"/> class.
		/// </summary>
		static LogLevel ( ) {
			Levels = new Dictionary<string, LogLevelInfo> ( );
			Verbose = new LogLevelInfo { Priority = 2, Value = "verbose", Letter = 'V' };
			Debug = new LogLevelInfo { Priority = 3, Value = "debug", Letter = 'D' };
			Info = new LogLevelInfo { Priority = 4, Value = "info", Letter = 'I' };
			Warn = new LogLevelInfo { Priority = 5, Value = "warn", Letter = 'W' };
			Error = new LogLevelInfo { Priority = 6, Value = "error", Letter = 'E' };
			Assert = new LogLevelInfo { Priority = 7, Value = "assert", Letter = 'A' };

			Levels.Add ( Verbose.Value, Verbose );
			Levels.Add ( Debug.Value, Debug );
			Levels.Add ( Info.Value, Info );
			Levels.Add ( Warn.Value, Warn );
			Levels.Add ( Error.Value, Error );
			Levels.Add ( Assert.Value, Assert );

		}

		/// <summary>
		/// Gets or sets the verbose log level.
		/// </summary>
		/// <value>The verbose log level.</value>
		public static LogLevelInfo Verbose { get; private set; }
		/// <summary>
		/// Gets or sets the debug log level.
		/// </summary>
		/// <value>The debug log level.</value>
		public static LogLevelInfo Debug { get; private set; }
		/// <summary>
		/// Gets or sets the info log level.
		/// </summary>
		/// <value>The info log level.</value>
		public static LogLevelInfo Info { get; private set; }
		/// <summary>
		/// Gets or sets the warn log level.
		/// </summary>
		/// <value>The warn log level.</value>
		public static LogLevelInfo Warn { get; private set; }
		/// <summary>
		/// Gets or sets the error log level.
		/// </summary>
		/// <value>The error log level.</value>
		public static LogLevelInfo Error { get; private set; }
		/// <summary>
		/// Gets or sets the assert log level.
		/// </summary>
		/// <value>The assert log level.</value>
		public static LogLevelInfo Assert { get; private set; }

		/// <summary>
		/// Gets or sets the levels.
		/// </summary>
		/// <value>The levels.</value>
		public static Dictionary<String, LogLevelInfo> Levels { get; private set; }

		/// <summary>
		/// Gets the by string.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static LogLevelInfo GetByString ( String value ) {

			foreach ( LogLevelInfo item in Values ) {
				if ( String.Compare ( item.Value, value, true ) == 0 ) {
					return item;
				}
			}
			return null;
		}

		/// <summary>
		/// Gets the by letter.
		/// </summary>
		/// <param name="letter">The letter.</param>
		/// <returns></returns>
		public static LogLevelInfo GetByLetter ( String letter ) {
			return GetByLetter ( letter[0] );
		}

		/// <summary>
		/// Gets the by letter.
		/// </summary>
		/// <param name="letter">The letter.</param>
		/// <returns></returns>
		public static LogLevelInfo GetByLetter ( char letter ) {
			foreach ( LogLevelInfo item in Values ) {
				if ( item.Letter == letter ) {
					return item;
				}
			}

			return null;
		}

		/// <summary>
		/// Gets the values.
		/// </summary>
		/// <value>The values.</value>
		public static Dictionary<string, LogLevelInfo>.ValueCollection Values {
			get {
				return Levels.Values;
			}
		}

		/// <summary>
		/// Gets the keys.
		/// </summary>
		/// <value>The keys.</value>
		public static Dictionary<string, LogLevelInfo>.KeyCollection Keys {
			get {
				return Levels.Keys;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public class LogLevelInfo {
			/// <summary>
			/// Initializes a new instance of the <see cref="LogLevelInfo"/> class.
			/// </summary>
			public LogLevelInfo ( ) {

			}

			/// <summary>
			/// Initializes a new instance of the <see cref="LogLevelInfo"/> class.
			/// </summary>
			/// <param name="priority">The priority.</param>
			/// <param name="value">The value.</param>
			/// <param name="letter">The letter.</param>
			public LogLevelInfo ( int priority, String value, Char letter ) {
				Priority = priority;
				Value = value;
				Letter = letter;
			}

			/// <summary>
			/// Gets or sets the priority.
			/// </summary>
			/// <value>The priority.</value>
			public int Priority { get; set; }
			/// <summary>
			/// Gets or sets the value.
			/// </summary>
			/// <value>The value.</value>
			public String Value { get; set; }
			/// <summary>
			/// Gets or sets the letter.
			/// </summary>
			/// <value>The letter.</value>
			public Char Letter { get; set; }
		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetDirectoryNameTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetDirectoryNameTests {
		[Fact]
		public void WhenPathIsNull_ShouldReturnNull ( ) {
			var result = LinuxPath.GetDirectoryName ( null );
			Assert.Null ( result );
		}


		[Fact]
		public void WhenPathContainsInvalidCharacters_ShouldThrowException ( ) {
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.GetDirectoryName ( "/my-invalid-path/f-{0}".With ( LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );
		}

		[Fact]
		public void WhenPathLengthIs1_ShouldReturnRelativePath ( ) {
			string result = LinuxPath.GetDirectoryName ( "a" );
			Assert.Equal ( "./a/", result );
		}

		[Fact]
		public void WhenPathLengthIsRoot_ShouldReturnRootPath ( ) {
			string result = LinuxPath.GetDirectoryName ( "/" );
			Assert.Equal ( "/", result );
		}

		[Fact]
		public void WhenPathRelative_ShouldReturnRelativePath ( ) {
			var fixture = new Fixture ( );
			var p = fixture.Create ( "path" );
			string result = LinuxPath.GetDirectoryName ( p );
			Assert.Equal ( "./{0}/".With ( p ), result );
		}

		[Fact]
		public void WhenPathRelativeWithFileWithExtension_ShouldReturnDirectoryRelativePath ( ) {
			var fixture = new Fixture ( );
			var p = fixture.Create ( "path" );
			var pf = "{0}/file.ext".With ( p );
			string result = LinuxPath.GetDirectoryName ( pf );
			Assert.Equal ( "./{0}/".With ( p ), result );
		}


		[Fact]
		public void WhenPathRelativeWithFileWithoutExtension_ShouldReturnDirectoryRelativePath ( ) {
			var fixture = new Fixture ( );
			var p = fixture.Create ( "path" );
			var pf = "{0}/file".With ( p );
			string result = LinuxPath.GetDirectoryName ( pf );
			Assert.Equal ( "./{0}/".With ( p ), result );
		}

		[Fact]
		public void WhenPathRootedWithFileWithExtension_ShouldReturnDirectoryRootedPath ( ) {
			var fixture = new Fixture ( );
			var p = fixture.Create ( "path" );
			var pf = "/{0}/file.ext".With ( p );
			string result = LinuxPath.GetDirectoryName ( pf );
			Assert.Equal ( "/{0}/".With ( p ), result );
		}


		[Fact]
		public void WhenPathRootedWithFileWithoutExtension_ShouldReturnDirectoryRootedPath ( ) {
			var fixture = new Fixture ( );
			var p = fixture.Create ( "path" );
			var pf = "/{0}/file".With ( p );
			string result = LinuxPath.GetDirectoryName ( pf );
			Assert.Equal ( "/{0}/".With ( p ), result );
		}

		[Fact]
		public void WhenPathRooted_ShouldReturnRootPath ( ) {
			var fixture = new Fixture ( );
			var p = "/{0}/".With ( fixture.Create ( "path" ) );
			string result = LinuxPath.GetDirectoryName ( p );
			Assert.Equal ( p, result );
		}

		[Fact]
		public void WhenPathIsLevels_ShouldReturnRootPath ( ) {
			var fixture = new Fixture ( );
			var pname = fixture.Create ( "path" );
			var p = "/some/path/deep/{0}/".With ( pname );
			string result = LinuxPath.GetDirectoryName ( p );
			Assert.Equal ( "{0}".With ( p ), result );
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/PropertyModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Camalot.Common.Extensions;
using Madb.Site.Extensions;

namespace Madb.Site.Models.Documentation {
	public class PropertyModel {
		public string Name { get; set; }
		public Xml.Member Documentation { get; set; }
		public string XmlName { get; set; }
		public bool Ignore { get { return Documentation != null && Documentation.Ignore; } }
		public Type ReturnType { get; set; }
		public Type Parent { get; set; }
		public bool IsStatic { get; set; }
		public bool IsReadOnly { get; set; }
		public string Id {
			get {
				return "{0}.{1}".With(Parent.ToSafeFullName(), Name).Slug();
			}
		}

		public override string ToString() {
			return Name;
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/ColorData.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <ignore>true</ignore>
	public class ColorData {
		/// <summary>
		/// Gets or sets the length.
		/// </summary>
		/// <value>
		/// The length.
		/// </value>
		public int Length { get; set; }
		/// <summary>
		/// Gets or sets the offset.
		/// </summary>
		/// <value>
		/// The offset.
		/// </value>
		public int Offset { get; set; }

		
	}
}


<|start_filename|>Madb.Site/assets/Scripts/system.floating-label.js<|end_filename|>
﻿(function ($, document, window) {
	"use strict";

	/*<div class="form-group">
				<label for="exampleInputEmail1">Disabled</label>
				<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Disabled" disabled>
			</div>
	*/
	$(function () {
		$(".form-group .form-control").each(function (i, item) {
			var self = $(this);
			if (self.data("floating-label-setup")) { return; }
			self.data("floating-label-setup", true);

			//// init

			__initLabel(self);

			//__getLabel(self);

			//self.on("focus", function (event, data) {
			//	__getLabel($(this)).addClass("active");
			//}).on("blur", function (event, data) {
			//	__getLabel($(this)).removeClass("active");
			//});
		});
	});
	var __initLabel = function (input) {
		var form = input.closest("form");
		if(form.hasClass("form-horizontal")) {
			return;
		}
		var label = $(input).siblings("label").first();
		if (!label || label.length === 0) {
			label = $("<label />").append(input.attr("placeholder") || input.attr("name"));
			label.insertAfter(input);
		}
	};
	//var __getLabel = function (input) {
	//	var selfId = input.attr("id") || "ID-NOT-FOUND-FLOATING-LABEL";
	//	// what about this? <label>foo<input /></label> - should it be handled?

	//	var label = input.data("floating-label") || $("[for='" + selfId + "']", input.parent()).first() || null;
	//	if (!label || label.length === 0) {
	//		label = $("<label />").append(input.attr("placeholder") || input.attr("name"));
	//		input.insertBefore(input);
	//	}
	//	input.data("floating-label", label);

	//	return __setupLabel(label);
	//};
	//var __setupLabel = function (label) {
	//	if (!label.hasClass("floating-label")) {
	//		label.addClass("floating-label");
	//	}
	//	return label;
	//};
})(window.jQuery, window.document, window);

<|start_filename|>Managed.AndroidDebugBridge/Receivers/EnvironmentVariablesReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class EnvironmentVariablesReceiver : MultiLineReceiver {
		/// <summary>
		/// 
		/// </summary>
		public const String ENV_COMMAND = "printenv";
		/// <summary>
		/// 
		/// </summary>
		private const String ENV_PATTERN = @"^([^=\s]+)\s*=\s*(.*)$";
		/// <summary>
		/// Initializes a new instance of the <see cref="EnvironmentVariablesReceiver"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public EnvironmentVariablesReceiver ( Device device ) {
			Device = device;
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>The device.</value>
		public Device Device { get; private set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			foreach ( string line in lines ) {
				if ( string.IsNullOrWhiteSpace ( line ) || line.StartsWith ( "#" ) || line.StartsWith ( "$" ) ) {
					continue;
				}

				var m = Regex.Match ( line, ENV_PATTERN );
				if ( m.Success ) {
					var label = m.Groups[1].Value.Trim ( );
					var value = m.Groups[2].Value.Trim ( );

					if ( label.Length > 0 ) {
						if ( Device.EnvironmentVariables.ContainsKey ( label ) ) {
							Device.EnvironmentVariables[label] = value;
						} else {
							Device.EnvironmentVariables.Add ( label, value );
						}
					}
				}

			}
		}

		/// <summary>
		/// Finishes the receiver
		/// </summary>
		protected override void Done ( ) {
			this.Device.OnBuildInfoChanged ( EventArgs.Empty );
			base.Done ( );
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/Xml/Document.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	[XmlRoot("doc")]
	public class Document {
		[XmlArrayItem("member")]
		[XmlArray("members")]
		public IList<Member> Members { get; set; }
	}
}

<|start_filename|>Madb.Site/assets/styles/nuget.css<|end_filename|>
﻿.nuget-badge {
  background-color: #607d8b;
  padding: 15px 0 15px 0;
  border: 4px solid #b7c6cd;
  border-radius: 5px;
}
.nuget-badge code {
  color: #00bcd4;
  background-color: transparent;
  font-size: 1.5em;
  font-family: 'andale mono', 'lucida console', monospace;
}
/*# sourceMappingURL=nuget.css.map */

<|start_filename|>Managed.AndroidDebugBridge/JdwpPacket.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class JdwpPacket {
		public const int JDWP_HEADER_LEN = 11;

		// results from findHandshake
		public const int HANDSHAKE_GOOD = 1;
		public const int HANDSHAKE_NOTYET = 2;
		public const int HANDSHAKE_BAD = 3;

		// our cmdSet/cmd
		private const int DDMS_CMD_SET = 0xc7;       // 'G' + 128
		private const int DDMS_CMD = 0x01;

		// "flags" field
		private const int REPLY_PACKET = 0x80;

		// this is sent and expected at the start of a JDWP connection
		private const String HANDSHAKE = "JDWP-Handshake";

		public const int HANDSHAKE_LEN = HANDSHAKE.Length;

		public JdwpPacket ( BinaryWriter buf ) {
			Buffer = buf;
			IsNew = true;
			SerialID = 0x40000000;
		}

		private int SerialID { get; set; }

		private BinaryWriter Buffer { get; private set; }
		public int Length { get; private set; }
		public int ID { get; private set; }
		public int Flags { get; private set; }
		public int CommandSet { get; private set; }
		public int Command { get; private set; }
		public int ErrorCode { get; private set; }
		private bool IsNew { get; set; }

		/// <summary>
		/// Finish a packet created with newPacket().
		/// This always creates a command packet, with the next serial number
		/// in sequence.
		/// We have to take "payloadLength" as an argument because we can't
		/// see the position in the "slice" returned by getPayload().  We could
		/// fish it out of the chunk header, but it's legal for there to be
		/// more than one chunk in a JDWP packet.
		/// On exit, "position" points to the end of the data.		
		/// </summary>
		/// <param name="payloadLength">Length of the payload.</param>
		void finishPacket ( int payloadLength ) {
			System.Diagnostics.Debug.Assert ( IsNew );

			if ( ChunkHandler.CHUNK_ORDER == ChunkHandler.ByteOrder.LittleEndian ) {
				if ( Buffer.BitConverter != EndianBitConverter.Little ) {
					Buffer = new EndianBinaryWriter ( EndianBitConverter.Little, Buffer.BaseStream );
				}
			}

			Length = JDWP_HEADER_LEN + payloadLength;
			ID = GetNextSerial ( );
			Flags = 0;
			CommandSet = DDMS_CMD_SET;
			Command = DDMS_CMD;

			Buffer.Write ( Length );
			Buffer.Write ( ID );
			Buffer.Write ( Flags );
			Buffer.Write ( CommandSet );
			Buffer.Write ( Command );

			if ( oldOrder == EndianBitConverter.Little ) {
				if ( Buffer.BitConverter != EndianBitConverter.Little ) {
					Buffer = new EndianBinaryWriter ( EndianBitConverter.Little, Buffer.BaseStream );
				}
			} else {
				if ( Buffer.BitConverter != EndianBitConverter.Big ) {
					Buffer = new EndianBinaryWriter ( EndianBitConverter.Big, Buffer.BaseStream );
				}
			}

			// move to end
			Buffer.BaseStream.Position = Length;
		}


		/// <summary>
		/// Get the next serial number.  This creates a unique serial number
		/// across all connections, not just for the current connection.  This
		/// is a useful property when debugging, but isn't necessary.
		/// We can't synchronize on an int, so we use a sync method.
		/// </summary>
		/// <returns></returns>
		private int GetNextSerial ( ) {
			lock ( this ) {
				return SerialID++;
			}
		}

		public EndianBinaryReader GetPayload ( ) {
			MemoryStream buf;
			long oldPosn = Buffer.BaseStream.Position;

			Buffer.BaseStream.Position = JDWP_HEADER_LEN;
			byte[] data = ( Buffer.BaseStream as MemoryStream ).ToArray ( );
			byte[] sdata = new byte[data.Length - JDWP_HEADER_LEN];
			data.CopyTo ( sdata, JDWP_HEADER_LEN );


			Buffer.BaseStream.Position = oldPosn;

			if ( Length > 0 ) {
				buf = new MemoryStream ( Length - JDWP_HEADER_LEN );
				buf.Write ( sdata, 0, Length - JDWP_HEADER_LEN );
			} else {
				System.Diagnostics.Debug.Assert ( IsNew );
			}

			EndianBinaryReader ebr;
			if ( ChunkHandler.CHUNK_ORDER == ChunkHandler.ByteOrder.LittleEndian ) {
				ebr = new EndianBinaryReader ( EndianBitConverter.Little, buf );
			} else {
				ebr = new EndianBinaryReader ( EndianBitConverter.Big, buf );
			}

			return ebr;
		}

		/**
     * Returns "true" if this JDWP packet has a JDWP command type.
     *
     * This never returns "true" for reply packets.
     */
		public bool IsDdmPacket {
			get {
				return ( Flags & REPLY_PACKET ) == 0 &&
							 CommandSet == DDMS_CMD_SET &&
							 Command == DDMS_CMD;
			}
		}

		/**
		 * Returns "true" if this JDWP packet is tagged as a reply.
		 */
		public bool IsReply {
			get {
				return ( Flags & REPLY_PACKET ) != 0;
			}
		}

		/**
     * Returns "true" if this JDWP packet is a reply with a nonzero
     * error code.
     */
		public bool IsError {
			get {
				return IsReply && ErrorCode != 0;
			}
		}

		/**
		 * Returns "true" if this JDWP packet has no data.
		 */
		public bool IsEmpty {
			get {
				return ( Length == JDWP_HEADER_LEN );
			}
		}

		void WriteAndConsume ( Socket chan ) {
			System.Diagnostics.Debug.Assert ( Length > 0 );

			MemoryStream tms = new MemoryStream ( (int)Buffer.BaseStream.Position );
			byte[] tdata = new byte[Buffer.BaseStream.Position];
			int oldLimit = Length;
			byte[] fdata = ( Buffer.BaseStream as MemoryStream ).ToArray ( );
			for ( int i = 0; i < tdata.Length; i++ ) {
				tdata[i] = fdata[i];
			}

			chan.Send ( tdata );

		}

		/**
		 * "Move" the packet data out of the buffer we're sitting on and into
		 * buf at the current position.
		 */
		void MovePacket ( EndianBinaryWriter buf ) {
			Log.v ( "ddms", "moving " + Length + " bytes" );
			int oldPosn = (int)Buffer.BaseStream.Position;
			Buffer.BaseStream.Position = 0;


			byte[] tdata = new byte[oldPosn];
			byte[] fdata = ( Buffer.BaseStream as MemoryStream ).ToArray ( );
			for ( int i = 0; i < tdata.Length; i++ ) {
				tdata[i] = fdata[i];
			}

			buf.Write ( tdata );
			Buffer.BaseStream.Position = Length;
		}

		void consume ( ) {
			//Log.d("ddms", "consuming " + mLength + " bytes");
			//Log.d("ddms", "  posn=" + mBuffer.position()
			//    + ", limit=" + mBuffer.limit());

			/*
			 * The "flip" call sets "limit" equal to the position (usually the
			 * end of data) and "position" equal to zero.
			 *
			 * compact() copies everything from "position" and "limit" to the
			 * start of the buffer, sets "position" to the end of data, and
			 * sets "limit" to the capacity.
			 *
			 * On entry, "position" is set to the amount of data in the buffer
			 * and "limit" is set to the capacity.  We want to call flip()
			 * so that position..limit spans our data, advance "position" past
			 * the current packet, then compact.
			 */

			byte[] tdata = new byte[Buffer.BaseStream.Position];
			byte[] fdata = ( Buffer.BaseStream as MemoryStream ).ToArray ( );
			for ( int i = 0; i < tdata.Length; i++ ) {
				tdata[i] = fdata[i];
			}

			mBuffer.flip ( );         // limit<-posn, posn<-0
			mBuffer.position ( mLength );
			mBuffer.compact ( );      // shift posn...limit, posn<-pending data
			mLength = 0;
			//Log.d("ddms", "  after compact, posn=" + mBuffer.position()
			//    + ", limit=" + mBuffer.limit());
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/IClient.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	[Flags]
		public enum ClientChangeState {
		/// <summary>
		/// The name
		/// </summary>
		Name = 0x0001,
		/// <summary>
		/// The debugger status
		/// </summary>
		DebuggerStatus = 0x0002,
		/// <summary>
		/// The port
		/// </summary>
		Port = 0x0004,
		/// <summary>
		/// The thread mode
		/// </summary>
		ThreadMode = 0x0008,
		/// <summary>
		/// The thread data
		/// </summary>
		ThreadData = 0x0010,
		/// <summary>
		/// The heap mode
		/// </summary>
		HeapMode = 0x0020,
		/// <summary>
		/// The heap data
		/// </summary>
		HeapData = 0x0040,
		/// <summary>
		/// The native heap data
		/// </summary>
		NativeHeapData = 0x0080,
		/// <summary>
		/// The thread stack trace
		/// </summary>
		ThreadStackTrace = 0x0100,
		/// <summary>
		/// The heap allocations
		/// </summary>
		HeapAllocations = 0x0200,
		/// <summary>
		/// The heap allocation status
		/// </summary>
		HeapAllocationStatus = 0x0400,
		/// <summary>
		/// The method profiling status
		/// </summary>
		MethodProfilingStatus = 0x0800,
		/// <summary>
		/// The information
		/// </summary>
		Info = Name | DebuggerStatus | Port,
		}

	/// <summary>
	/// 
	/// </summary>
	public enum ClientConnectionState {
		/// <summary>
		/// The initialize
		/// </summary>
		Init = 1,
		/// <summary>
		/// The not JDWP
		/// </summary>
		NotJDWP = 2,
		/// <summary>
		/// The await shake
		/// </summary>
		AwaitShake = 10,
		/// <summary>
		/// The need DDM packet
		/// </summary>
		NeedDDMPacket = 11,
		/// <summary>
		/// The not DDM
		/// </summary>
		NotDDM = 12,
		/// <summary>
		/// The ready
		/// </summary>
		Ready = 13,
		/// <summary>
		/// The error
		/// </summary>
		Error = 20,
		/// <summary>
		/// The disconnected
		/// </summary>
		Disconnected = 21,
		}

	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="Managed.Adb.IPacketConsumer" />
	public interface IClient : IPacketConsumer {


		/// <summary>
		/// Gets the state of the connection.
		/// </summary>
		/// <value>
		/// The state of the connection.
		/// </value>
		ClientConnectionState ConnectionState { get; }
		/// <summary>
		/// Gets the state of the change.
		/// </summary>
		/// <value>
		/// The state of the change.
		/// </value>
		ClientChangeState ChangeState { get; }
		/// <summary>
		/// Gets or sets the channel.
		/// </summary>
		/// <value>
		/// The channel.
		/// </value>
		Socket Channel { get; set; }

		/// <summary>
		/// Gets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		IDevice Device { get; }
		/// <summary>
		/// Gets the device implementation.
		/// </summary>
		/// <value>
		/// The device implementation.
		/// </value>
		Device DeviceImplementation { get; }
		/// <summary>
		/// Gets the debugger listen port.
		/// </summary>
		/// <value>
		/// The debugger listen port.
		/// </value>
		int DebuggerListenPort { get; }
		/// <summary>
		/// Gets a value indicating whether this instance is DDM aware.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is DDM aware; otherwise, <c>false</c>.
		/// </value>
		bool IsDdmAware { get; }
		/// <summary>
		/// Gets a value indicating whether this instance is debugger attached.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is debugger attached; otherwise, <c>false</c>.
		/// </value>
		bool IsDebuggerAttached { get; }
		/// <summary>
		/// Gets the debugger.
		/// </summary>
		/// <value>
		/// The debugger.
		/// </value>
		Debugger Debugger { get; }
		/// <summary>
		/// Gets the client data.
		/// </summary>
		/// <value>
		/// The client data.
		/// </value>
		ClientData ClientData { get; }
		/// <summary>
		/// Gets or sets a value indicating whether this instance is thread update enabled.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is thread update enabled; otherwise, <c>false</c>.
		/// </value>
		bool IsThreadUpdateEnabled { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether this instance is heap update enabled.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is heap update enabled; otherwise, <c>false</c>.
		/// </value>
		bool IsHeapUpdateEnabled { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether this instance is selected client.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is selected client; otherwise, <c>false</c>.
		/// </value>
		bool IsSelectedClient { get; set; }
		/// <summary>
		/// Returns true if ... is valid.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance is valid; otherwise, <c>false</c>.
		/// </value>
		bool IsValid { get; }

		/// <summary>
		/// Executes the garbage collector.
		/// </summary>
		void ExecuteGarbageCollector ( );
		/// <summary>
		/// Dumps the hprof.
		/// </summary>
		void DumpHprof ( );
		/// <summary>
		/// Toggles the method profiling.
		/// </summary>
		void ToggleMethodProfiling ( );
		/// <summary>
		/// Requests the method profiling status.
		/// </summary>
		void RequestMethodProfilingStatus ( );
		/// <summary>
		/// Requests the thread update.
		/// </summary>
		void RequestThreadUpdate ( );
		/// <summary>
		/// Requests the thread stack trace.
		/// </summary>
		/// <param name="threadID">The thread identifier.</param>
		void RequestThreadStackTrace ( int threadID );
		/// <summary>
		/// Requests the native heap information.
		/// </summary>
		/// <returns></returns>
		bool RequestNativeHeapInformation ( );
		/// <summary>
		/// Enables the allocation tracker.
		/// </summary>
		/// <param name="enable">if set to <c>true</c> [enable].</param>
		void EnableAllocationTracker ( bool enable );
		/// <summary>
		/// Requests the allocation status.
		/// </summary>
		void RequestAllocationStatus ( );
		/// <summary>
		/// Requests the allocation details.
		/// </summary>
		void RequestAllocationDetails ( );
		/// <summary>
		/// Kills this instance.
		/// </summary>
		void Kill ( );
		// TODO: Define Selector
		/// <summary>
		/// Registers the specified selector.
		/// </summary>
		/// <param name="selector">The selector.</param>
		void Register ( /*Selector*/ Object selector );
		/// <summary>
		/// Listens for debugger.
		/// </summary>
		/// <param name="listenPort">The listen port.</param>
		void ListenForDebugger ( int listenPort );
		// TODO: JdwpPacket
		/// <summary>
		/// Sends the and consume.
		/// </summary>
		/// <param name="packet">The packet.</param>
		/// <param name="replyHandler">The reply handler.</param>
		void SendAndConsume ( /*JdwpPacket*/ Object packet, ChunkHandler replyHandler );
		/// <summary>
		/// Adds the request identifier.
		/// </summary>
		/// <param name="id">The identifier.</param>
		/// <param name="handler">The handler.</param>
		void AddRequestId ( int id, ChunkHandler handler );
		/// <summary>
		/// Removes the request identifier.
		/// </summary>
		/// <param name="id">The identifier.</param>
		void RemoveRequestId ( int id );
		/// <summary>
		/// Determines whether [is response to us] [the specified identifier].
		/// </summary>
		/// <param name="id">The identifier.</param>
		/// <returns></returns>
		ChunkHandler IsResponseToUs ( int id );
		// TODO: JdwpPacket
		/// <summary>
		/// Packets the failed.
		/// </summary>
		/// <param name="packet">The packet.</param>
		void PacketFailed ( /*JdwpPacket*/ Object packet );
		/// <summary>
		/// DDMs the seen.
		/// </summary>
		/// <returns></returns>
		bool DdmSeen ( );
		/// <summary>
		/// Closes the specified notify.
		/// </summary>
		/// <param name="notify">if set to <c>true</c> [notify].</param>
		void Close ( bool notify );
		/// <summary>
		/// Updates the specified change mask.
		/// </summary>
		/// <param name="changeMask">The change mask.</param>
		void Update ( ClientChangeMask changeMask );
	}
}


<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/PropertyModel.cshtml<|end_filename|>
﻿@using Camalot.Common.Extensions;
@using Camalot.Common.Mvc.Extensions;
@using Madb.Site.Extensions;

@model Madb.Site.Models.Documentation.PropertyModel

<div id="@Model.Id" data-xml-name="@Model.XmlName">
	<div class="page-header">
		<h4 class="zero">
			<i class="fa fa-certificate mrm"></i>
			<span class="method">
				<span class="method-returntype">@Html.DisplayFor(m => Model.ReturnType)</span>
				<span class="method-name">@Model.Name</span>
			</span>
			<small class="mll text-muted pull-right">
				@Html.StaticIcon(Model.IsStatic)
				@Html.ReadonlyIcon(Model.IsReadOnly)
				@Html.DirectLink(Model.Id)
			</small>
		</h4>

	</div>
	@if(Model.Documentation != null) {
		@Html.DisplayFor(x => Model.Documentation)
	}
</div>


<|start_filename|>Madb.Site/Views/Shared/AdSense.cshtml<|end_filename|>
﻿@model Madb.Site.Models.AdSenseModel
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- @Model.Name -->
<ins class="adsbygoogle @(Model.Name.ToLower())"
		 style="display:inline-block;"
		 data-ad-client="@Model.PublisherId"
		 data-ad-slot="@Model.Slot"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

<|start_filename|>Madb.Site/Views/Shared/_NavBar.cshtml<|end_filename|>
﻿@{
	var scrollTopOffset = -50;
}
<nav class="navbar navbar-default navbar-fixed-top">
	
	@*<div class="pull-left mtm mlm">
		@(Html.Partial("_AddThisCountPartial"))
	</div>*@

	<div class="container">
		<div class="pull-right mtm">
			@(Html.Partial("Paypal"))
		</div>
		<div class="pull-right mtm mrl">
			<span class="logo small logo-hidden" data-scroll-show-low="200" data-scroll-toggle="logo-hidden"></span>
			<a class="pull-right navbar-brand uppercase bold" href="@(Url.Action("",""))">@(Html.SiteName())</a>
		</div>
		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
		</div>
		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav">
				<li><a href="@Url.Action("","")#home" data-scroll="click" data-scroll-offset="@(scrollTopOffset)"><i class="mrs fa fa-home"></i><span>Home</span></a></li>
				<li><a href="@Url.Action("","")#about" data-scroll="click" data-scroll-offset="@(scrollTopOffset)" class="track"><i class="mrs fa fa-question-circle"></i><span>About</span></a></li>
				<li><a href="@Url.Action("","")#nuget" data-scroll="click" data-scroll-offset="@(scrollTopOffset)" class="track"><i class="mrs fa fa-download"></i><span>Nuget</span></a></li>
				<li class="divider-vertical"></li>
				<li class="expandable-label hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"><a href="https://madb.codeplex.com/" target="_blank"><i class="fa fa-external-link" title="Project"></i><span class="label">Project</span></a></li>
				<li class="expandable-label hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"><a href="https://madb.codeplex.com/SourceControl/latest#trunk/Managed.AndroidDebugBridge/" target="_blank"><i class="fa fa-code-fork" title="Source"></i><span class="label">Source</span></a></li>
				<li class="expandable-label hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"><a href="https://madb.codeplex.com/releases" target="_blank"><i class="fa fa-download" title="Download"></i><span class="label">Download</span></a></li>
				<li class="expandable-label hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"><a href="https://madb.codeplex.com/workitem/list/basic" target="_blank"><i class="fa fa-bug" title="Issues"></i><span class="label">Issues</span></a></li>
				<li class="expandable-label hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"><a href="https://madb.codeplex.com/discussions" target="_blank"><i class="fa fa-quote-left" title="Discussions"></i><span class="label">Discussions</span></a></li>
				<li class="divider-vertical hidden" data-scroll-show-low="265" data-scroll-toggle="hidden"></li>
				<li><a href="@Url.Action("","")#license" data-scroll="click" data-scroll-offset="@(scrollTopOffset)" class="track"><i class="mrs fa fa-certificate text-white"></i><span>License</span></a></li>
				<li class="divider-vertical"></li>
				<li class="dropdown">
					<a href="#" data-toggle="dropdown"><i class="mrs fa fa-bookmark text-white"></i><span class="mrs">Other Projects</span><b class="caret caret-white"></b></a>
					<ul class="dropdown-menu">
						<li><a href="http://endpointmvc.bit13.com/"><i class="mrs icon-endpointmvc"></i><span>EndpointMvc</span></a></li>
						<li><a href="http://camalotcommon.bit13.com/"><i class="mrs icon-camalotcommon"></i><span>Camalot.Common</span></a></li>
					</ul>
				</li>
			</ul>
		</div>
	</div>


</nav>

<|start_filename|>Managed.AndroidDebugBridge/RawImage.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Managed.Adb.Conversion;

namespace Managed.Adb {
	/// <summary>
	/// Data representing an image taken from a device frame buffer.
	/// </summary>
	public class RawImage {
		/// <summary>
		/// Initializes a new instance of the <see cref="RawImage"/> class.
		/// </summary>
		public RawImage ( ) {
			this.Red = new ColorData ( );
			this.Blue = new ColorData ( );
			this.Green = new ColorData ( );
			this.Alpha = new ColorData ( );
		}

		/// <summary>
		/// Gets or sets the version.
		/// </summary>
		/// <value>
		/// The version.
		/// </value>
		public int Version { get; set; }
		/// <summary>
		/// Gets or sets the BPP.
		/// </summary>
		/// <value>
		/// The BPP.
		/// </value>
		public int Bpp { get; set; }
		/// <summary>
		/// Gets or sets the size.
		/// </summary>
		/// <value>
		/// The size.
		/// </value>
		public int Size { get; set; }
		/// <summary>
		/// Gets or sets the width.
		/// </summary>
		/// <value>
		/// The width.
		/// </value>
		public int Width { get; set; }
		/// <summary>
		/// Gets or sets the height.
		/// </summary>
		/// <value>
		/// The height.
		/// </value>
		public int Height { get; set; }
		/// <summary>
		/// Gets or sets the red.
		/// </summary>
		/// <value>
		/// The red.
		/// </value>
		public ColorData Red { get; set; }
		/// <summary>
		/// Gets or sets the blue.
		/// </summary>
		/// <value>
		/// The blue.
		/// </value>
		public ColorData Blue { get; set; }
		/// <summary>
		/// Gets or sets the green.
		/// </summary>
		/// <value>
		/// The green.
		/// </value>
		public ColorData Green { get; set; }
		/// <summary>
		/// Gets or sets the alpha.
		/// </summary>
		/// <value>
		/// The alpha.
		/// </value>
		public ColorData Alpha { get; set; }

		/// <summary>
		/// Gets or sets the data.
		/// </summary>
		/// <value>
		/// The data.
		/// </value>
		public byte[] Data { get; set; }

		/**
		 * Reads the header of a RawImage from a {@link ByteBuffer}.
		 * <p/>The way the data is sent over adb is defined in system/core/adb/framebuffer_service.c
		 * @param version the version of the protocol.
		 * @param buf the buffer to read from.
		 * @return true if success
		 */
		/// <summary>
		/// Reads the header.
		/// </summary>
		/// <param name="version">The version.</param>
		/// <param name="buf">The buf.</param>
		/// <returns></returns>
		public bool ReadHeader ( int version, BinaryReader buf ) {
			this.Version = version;
			// https://github.com/android/platform_system_core/blob/master/adb/framebuffer_service.c
			switch ( version ) {
				case 1: /* RGBA_8888 */
				case 2: /* RGBX_8888 */
				case 3: /* RGB_888 */
				case 4: /* RGB_565 */
				case 5: /* BGRA_8888 */
					this.Bpp = (int)buf.ReadInt32 ( );
					this.Size = (int)buf.ReadInt32 ( );
					this.Width = (int)buf.ReadInt32 ( ); // 480
					this.Height = (int)buf.ReadInt32 ( ); // 800
					this.Red.Offset = (int)buf.ReadInt32 ( ); // 8
					this.Red.Length = (int)buf.ReadInt32 ( ); // 8
					this.Blue.Offset = (int)buf.ReadInt32 ( );  // 0
					this.Blue.Length = (int)buf.ReadInt32 ( ); // 8
					this.Green.Offset = (int)buf.ReadInt32 ( ); // 16
					this.Green.Length = (int)buf.ReadInt32 ( ); // 8
					this.Alpha.Offset = (int)buf.ReadInt32 ( ); // 24
					this.Alpha.Length = (int)buf.ReadInt32 ( ); // 8
					break;
				default:
					// compatibility mode with original protocol
					this.Bpp = 16;

					// read actual values.
					this.Size = buf.ReadInt32 ( );
					this.Width = buf.ReadInt32 ( );
					this.Height = buf.ReadInt32 ( );
					// create default values for the rest. Format is 565
					this.Red.Offset = 11;
					this.Red.Length = 5;
					this.Green.Offset = 5;
					this.Green.Length = 6;
					this.Blue.Offset = 0;
					this.Blue.Length = 5;
					this.Alpha.Offset = 0;
					this.Alpha.Length = 0;
					break;
			}
			return true;
		}

		/// <summary>
		/// Returns the size of the header for a specific version of the framebuffer adb protocol.
		/// </summary>
		/// <param name="version">the version of the protocol.</param>
		/// <returns>the number of int that makes up the header.</returns>
		public static int GetHeaderSize ( int version ) {
			switch ( version ) {
				case 16: // compatibility mode
					return 3; // size, width, height
				case 1:
				case 2:
				case 3:
				case 4:
				case 5:
					return 12; // bpp, size, width, height, 4*(length, offset)
			}

			return 0;
		}

		/// <summary>
		/// Returns a rotated version of the image
		/// The image is rotated counter-clockwise.
		/// </summary>
		/// <returns></returns>
		public RawImage GetRotated ( ) {
			RawImage rotated = new RawImage ( );
			rotated.Version = this.Version;
			rotated.Bpp = this.Bpp;
			rotated.Size = this.Size;
			rotated.Red.Offset = this.Red.Offset;
			rotated.Red.Length = this.Red.Length;
			rotated.Green.Offset = this.Green.Offset;
			rotated.Green.Length = this.Green.Length;
			rotated.Blue.Offset = this.Blue.Offset;
			rotated.Blue.Length = this.Blue.Length;
			rotated.Alpha.Offset = this.Alpha.Offset;
			rotated.Alpha.Length = this.Alpha.Length;

			rotated.Width = this.Height;
			rotated.Height = this.Width;

			int count = this.Data.Length;
			rotated.Data = new byte[count];

			int byteCount = this.Bpp >> 3; // bpp is in bits, we want bytes to match our array
			int w = this.Width;
			int h = this.Height;
			for ( int y = 0; y < h; y++ ) {
				for ( int x = 0; x < w; x++ ) {
					Array.Copy ( this.Data, ( y * w + x ) * byteCount,
						rotated.Data, ( ( w - x - 1 ) * h + y ) * byteCount,
										byteCount );
				}
			}

			return rotated;
		}

		/// <summary>
		/// Returns a <see cref="System.String"/> that represents this instance.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String"/> that represents this instance.
		/// </returns>
		public override string ToString ( ) {
			return String.Format ( "height: {0}\nwidth: {1}\nbpp: {2}\nro: {3}\nrl: {4}\ngo: {5}\ngl: {6}\nbo: {7}\nbl: {8}\nao: {9}\nal: {10}\ns: {11}",
				this.Height, this.Width, this.Bpp,
				this.Red.Offset, this.Red.Length,
				this.Green.Offset, this.Green.Length,
				this.Blue.Offset, this.Blue.Length,
				this.Alpha.Offset, this.Alpha.Length, this.Size );
		}



		/// <summary>
		/// Converts this raw image to an Image
		/// </summary>
		/// <param name="format">The format.</param>
		/// <returns></returns>
		public Image ToImage ( PixelFormat format ) {
			Bitmap bitmap = null;
			Bitmap image = null;
			BitmapData bitmapdata = null;
			try {
				bitmap = new Bitmap ( this.Width, this.Height, format );
				bitmapdata = bitmap.LockBits ( new Rectangle ( 0, 0, this.Width, this.Height ), ImageLockMode.WriteOnly, format );
				image = new Bitmap ( this.Width, this.Height, format );
				var tdata = Data;
				if ( Bpp == 32 ) {
					tdata = Swap ( tdata );
				}
				Marshal.Copy ( tdata, 0, bitmapdata.Scan0, this.Size );
				bitmap.UnlockBits ( bitmapdata );
				using ( Graphics g = Graphics.FromImage ( image ) ) {
					g.DrawImage ( bitmap, new Point ( 0, 0 ) );
					return image;
				}

			} catch ( Exception ) {
				throw;
			}
		}

		/// <summary>
		/// Converts this raw image to an Image
		/// </summary>
		/// <returns></returns>
		public Image ToImage ( ) {
			return ToImage ( this.Bpp == 32 ? PixelFormat.Format32bppArgb : PixelFormat.Format16bppRgb565 );
		}

		/// <summary>
		/// Swaps the specified b.
		/// </summary>
		/// <param name="b">The b.</param>
		/// <returns></returns>
		private byte[] Swap ( byte[] b ) {
			var clone = new List<byte> ( );
			b.IntReverseForRawImage ( bitem => {
				clone.AddRange ( bitem );
			} );
			return clone.ToArray ( );
		}


	}
}


<|start_filename|>Managed.AndroidDebugBridge/SyncResult.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class SyncResult {
		/// <summary>
		/// Initializes a new SyncResult
		/// </summary>
		/// <param name="code">The error code</param>
		/// <param name="message">The error message</param>
		public SyncResult ( int code, String message ) {

			this.Message = message ?? ErrorCodeHelper.ErrorCodeToString ( code );
			this.Code = code;
		}

		/// <summary>
		/// Initializes a new SyncResult
		/// </summary>
		/// <param name="code">The error code</param>
		/// <param name="ex">The exception</param>
		public SyncResult ( int code, Exception ex )
			: this ( code, ex.Message ) {

		}

		/// <summary>
		/// Initializes a new SyncResult
		/// </summary>
		/// <param name="code">The error code</param>
		public SyncResult ( int code )
			: this ( code, (string)null ) {

		}

		/// <summary>
		/// Gets the error message
		/// </summary>
		public String Message { get; private set; }
		/// <summary>
		/// Gets the error code
		/// </summary>
		public int Code { get; private set; }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/AdbException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// Represents an exception with communicating with ADB
	/// </summary>
	public class AdbException : Exception {
		/// <summary>
		/// Initializes a new instance of the <see cref="AdbException"/> class.
		/// </summary>
		public AdbException( )
			: base ( "An error occurred with ADB" ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AdbException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		public AdbException( String message )
			: base ( message ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AdbException"/> class.
		/// </summary>
		/// <param name="serializationInfo">The serialization info.</param>
		/// <param name="context">The context.</param>
		public AdbException( SerializationInfo serializationInfo,StreamingContext context) : base(serializationInfo,context) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AdbException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="innerException">The inner exception.</param>
		public AdbException( String message, Exception innerException )
			: base ( message, innerException ) {

		}
	}
}


<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/ClassModel.cshtml<|end_filename|>
﻿@using Madb.Site.Extensions;

@model Madb.Site.Models.Documentation.ClassModel

<div id="@Model.Id" data-xml-name="@Model.XmlName">
	<div class="page-header">
		<h3 class="zero">
			<i class="fa fa-bolt mrm"></i>
			<span>@Model.Name</span>
			<small class="mll text-muted pull-right">
				@Html.StaticIcon(Model.IsStatic)
				@Html.DirectLink(Model.Id)
			</small>
		</h3>
	</div>
	@if(Model.Documentation != null) {
		@Html.DisplayFor(x => Model.Documentation)
	}
	<div class="mhl">
		@foreach(var m in Model.Properties) {
			if(!m.Ignore) {
				@Html.DisplayFor(x => m)
			}
		}
		@foreach(var m in Model.Methods) {
			if(!m.Ignore) {
				@Html.DisplayFor(x => m)
			}
		}
	</div>
</div>

<|start_filename|>Managed.AndroidDebugBridge/Receivers/MultilineReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public abstract class MultiLineReceiver : IShellOutputReceiver {

		/// <summary>
		/// 
		/// </summary>
		protected const String NEWLINE = "\r\n";
		/// <summary>
		/// 
		/// </summary>
		protected const String ENCODING = "ISO-8859-1";

		/// <summary>
		/// Gets or sets a value indicating whether [trim lines].
		/// </summary>
		/// <value><c>true</c> if [trim lines]; otherwise, <c>false</c>.</value>
		public bool TrimLines { get; set; }
		/// <summary>
		/// Gets or sets the unfinished line.
		/// </summary>
		/// <value>The unfinished line.</value>
		protected String UnfinishedLine { get; set; }
		/// <summary>
		/// Gets or sets the lines.
		/// </summary>
		/// <value>The lines.</value>
		protected ICollection<String> Lines { get; set; }

		/// <summary>
		/// Initializes a new instance of the <see cref="MultiLineReceiver"/> class.
		/// </summary>
		public MultiLineReceiver( ) {
			Lines = new List<String> ( );
		}

		/// <summary>
		/// Adds the output.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		public void AddOutput( byte[] data, int offset, int length ) {
			if ( !IsCancelled ) {
				String s = null;
				try {
					s = Encoding.GetEncoding ( ENCODING ).GetString ( data, offset, length ); //$NON-NLS-1$
				} catch ( DecoderFallbackException ) {
					// normal encoding didn't work, try the default one
					s = Encoding.Default.GetString ( data, offset, length );
				}

				// ok we've got a string
				if ( !String.IsNullOrEmpty ( s ) ) {
					// if we had an unfinished line we add it.
					if ( !String.IsNullOrEmpty ( UnfinishedLine ) ) {
						s = UnfinishedLine + s;
						UnfinishedLine = null;
					}

					// now we split the lines
					//Lines.Clear ( );
					int start = 0;
					do {
						int index = s.IndexOf ( NEWLINE, start ); //$NON-NLS-1$

						// if \r\n was not found, this is an unfinished line
						// and we store it to be processed for the next packet
						if ( index == -1 ) {
							UnfinishedLine = s.Substring ( start );
							break;
						}

						// so we found a \r\n;
						// extract the line
						String line = s.Substring ( start, index - start );
						if ( TrimLines ) {
							line = line.Trim ( );
						}
						Lines.Add ( line );

						// move start to after the \r\n we found
						start = index + 2;
					} while ( true );
				}
			}
		}

		/// <summary>
		/// Flushes the output.
		/// </summary>
		public void Flush( ) {
			if (!IsCancelled && Lines.Count > 0 ) {
				// at this point we've split all the lines.
				// make the array
				String[] lines = Lines.ToArray ( );

				// send it for final processing
				ProcessNewLines ( lines );
				Lines.Clear ( );
			}

			if ( !IsCancelled && !String.IsNullOrEmpty ( UnfinishedLine ) ) {
				ProcessNewLines ( new String[] { UnfinishedLine } );
			}

			Done ( );
		}

		/// <summary>
		/// Finishes the receiver
		/// </summary>
		protected virtual void Done( ) {
			// Do nothing
		}

		/// <summary>
		/// Gets a value indicating whether this instance is canceled.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is canceled; otherwise, <c>false</c>.
		/// </value>
		public virtual bool IsCancelled { get; protected set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected abstract void ProcessNewLines( String[] lines );
	}

}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetInvalidPathChars.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Managed.Adb.IO;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetInvalidPathChars {
		[Fact]
		public void WhenGetttingInvalidPathChars_ShouldEqualExpected ( ) {
			var result = LinuxPath.GetInvalidPathChars ( );
			Assert.Equal ( LinuxPathConsts.InvalidPathChars, result );
		}



	}
}


<|start_filename|>Madb.Site/assets/styles/documentation.css<|end_filename|>
﻿.method {
  font-family: Consolas, Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
  white-space: normal;
  word-spacing: normal;
}
.method a {
  text-decoration: underline;
  -moz-text-decoration-line: underline;
  text-decoration-line: underline;
  -moz-text-decoration-color: #333333;
  text-decoration-color: #333333;
  color: inherit;
}
.method .method-arguments:before {
  content: "(";
  margin-right: 5px;
}
.method .method-arguments:after {
  content: ")";
  margin-left: 5px;
}
.method .method-arguments .method-param-separator:after {
  content: ",";
  margin-right: 5px;
}
.method .parameter.parameter-optional:before {
  content: "[";
}
.method .parameter.parameter-optional:after {
  content: "]";
}
/*# sourceMappingURL=documentation.css.map */

<|start_filename|>Managed.AndroidDebugBridge/Receivers/NullOutputReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class NullOutputReceiver : IShellOutputReceiver {

		/// <summary>
		/// Prevents a default instance of the <see cref="NullOutputReceiver" /> class from being created.
		/// </summary>
		private NullOutputReceiver ( ) {
			IsCancelled = false;
		}

		private static NullOutputReceiver _instance = null;

		/// <summary>
		/// Gets the instance.
		/// </summary>
		/// <value>
		/// The instance.
		/// </value>
		public static IShellOutputReceiver Instance {
			get {
				if ( _instance == null ) {
					_instance = new NullOutputReceiver ( );
				}
				return _instance;
			}
		}

		/// <summary>
		/// Adds the output.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		public void AddOutput ( byte[] data, int offset, int length ) {
			// do nothing
		}

		/// <summary>
		/// Flushes the output.
		/// </summary>
		/// <remarks>
		/// This should always be called at the end of the "process" in order to indicate that the data is ready to be processed further if needed.
		/// </remarks>
		public void Flush ( ) {
			// do nothing
		}

		/// <summary>
		/// Gets a value indicating whether this instance is cancelled.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is cancelled; otherwise, <c>false</c>.
		/// </value>
		public bool IsCancelled { get; private set; }
	}

}


<|start_filename|>Madb.Site/Views/Shared/_IconPartial.cshtml<|end_filename|>
﻿@model Madb.Site.Models.IconHelperModel
@if(Model.Show) { <i class="fa @(Model.Icon) mrm" title="@(Model.Title)"></i> }

<|start_filename|>Madb.Site/Models/Documentation/Xml/Reference.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	public class Reference {
		[XmlAttribute("cref")]
		public string Link { get; set; }
		[XmlText]
		public string Description { get; set; }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/LinkResoverReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Camalot.Common.Extensions;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="Managed.Adb.MultiLineReceiver" />
	internal sealed class LinkResoverReceiver : MultiLineReceiver {
		/// <summary>
		/// Initializes a new instance of the <see cref="LinkResoverReceiver"/> class.
		/// </summary>
		public LinkResoverReceiver ( ) {

		}

		/// <summary>
		/// Gets or sets the resolved path.
		/// </summary>
		/// <value>
		/// The resolved path.
		/// </value>
		public string ResolvedPath { get; set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			// all we care about is a line with '->'
			var regex = @"->\s+([^$]+)";
			foreach ( var line in lines.Where ( l => l.IsMatch(regex) ) ) {
				ResolvedPath = line.Match ( regex ).Groups[1].Value;
			}

		}
	}
}


<|start_filename|>Madb.Site/Controllers/AssetsController.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Madb.Site.Controllers {
	public class AssetsController : Controller {
		// GET: Assets
		public PartialViewResult Gist(string id) {
			return PartialView(model: id);
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/DebugPortManager.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// Centralized point to provide a IDebugPortProvider to ddmlib.
	/// </summary>
	public class DebugPortManager {
		/// <summary>
		/// no static port
		/// </summary>
		public const int NO_STATIC_PORT = -1;

		/// <summary>
		/// Initializes a new instance of the <see cref="DebugPortManager"/> class.
		/// </summary>
		public DebugPortManager ( ) {

		}

		/// <summary>
		/// Gets or sets the IDebugPortProvider that will be used when a new Client requests
		/// </summary>
		public IDebugPortProvider Provider { get; set; }

		/// <summary>
		/// The _instance
		/// </summary>
		private static DebugPortManager _instance;
		/// <summary>
		/// Returns an instance of the debug port manager
		/// </summary>
		public DebugPortManager Instance {
			get {
				if ( _instance == null ) {
					_instance = new DebugPortManager ( );
				}
				return _instance;
			}
		}
	}
}


<|start_filename|>Madb.Site/Models/NavigationPositions.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Madb.Site.Models {
	public enum NavigationPositions {
		Left,
		Right
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Receivers/MountPointReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// A dynamic mount point receiver.
	/// </summary>
	/// <remarks>Works on busybox and non-busybox devices</remarks>
	public class MountPointReceiver : MultiLineReceiver {
		/// <summary>
		/// The mount parsing pattern.
		/// </summary>
		private const String RE_MOUNTPOINT_PATTERN = @"^([\S]+)\s+([\S]+)\s+([\S]+)\s+(r[wo]).*$";
		/// <summary>
		/// The mount command
		/// </summary>
		public const String MOUNT_COMMAND = "cat /proc/mounts";

		/// <summary>
		/// Initializes a new instance of the <see cref="MountPointReceiver"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public MountPointReceiver ( Device device ) {
			Device = device;
		}

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		/// <workitem id="16001">Bug w/ MountPointReceiver.cs/ProcessNewLines()</workitem>
		protected override void ProcessNewLines ( string[] lines ) {
			Device.MountPoints.Clear ( );

			lines.ForEach ( line => {
				var m = line.Match ( RE_MOUNTPOINT_PATTERN, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace );
				if ( m.Success ) {
					String block = m.Groups[1].Value.Trim ( ).Replace ( "//", "/" );
					String name = m.Groups[2].Value.Trim ( );
					String fs = m.Groups[3].Value.Trim ( );
					bool ro = String.Compare ( "ro", m.Groups[4].Value.Trim ( ), false ) == 0;
					MountPoint mnt = new MountPoint ( block, name, fs, ro );
					String key = name.Substring ( 1 );
					// currently does not support multiple mounts to the same location...
					if ( !Device.MountPoints.ContainsKey ( name ) ) {
						Device.MountPoints.Add ( name, mnt );
					}
				}
			} );
		}

		/// <summary>
		/// Finishes the receiver
		/// </summary>
		protected override void Done ( ) {
			this.Device.OnBuildInfoChanged ( EventArgs.Empty );
			base.Done ( );
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		public Device Device { get; set; }
	}
}


<|start_filename|>.build/keyimport.bat<|end_filename|>
 sn -i ..\shared\madb.pfx VS_KEY_B66E4F208CF07E41

<|start_filename|>Managed.AndroidDebugBridge/AdbResponse.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// An Adb Communication Response
	/// </summary>
	public class AdbResponse {

		/// <summary>
		/// Initializes a new instance of the <see cref="AdbResponse"/> class.
		/// </summary>
		public AdbResponse ( ) {
			Message = string.Empty;
		}

		/// <summary>
		/// Gets or sets a value indicating whether the IO communication was a success.
		/// </summary>
		/// <value>
		///   <c>true</c> if successful; otherwise, <c>false</c>.
		/// </value>
		public bool IOSuccess { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether this <see cref="AdbResponse"/> is okay.
		/// </summary>
		/// <value>
		///   <c>true</c> if okay; otherwise, <c>false</c>.
		/// </value>
		public bool Okay { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether this <see cref="AdbResponse"/> is timeout.
		/// </summary>
		/// <value>
		///   <c>true</c> if timeout; otherwise, <c>false</c>.
		/// </value>
		public bool Timeout { get; set; }
		/// <summary>
		/// Gets or sets the message.
		/// </summary>
		/// <value>
		/// The message.
		/// </value>
		public String Message { get; set; }
	}

}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetPathRoot.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetPathRoot {
		[Fact]
		public void WhenPathIsNull_ShouldReturnNull () {
			var result = LinuxPath.GetPathRoot ( null );
			Assert.Null ( result );
		}

		[Fact]
		public void WhenPathEmpty_ShouldReturnRelativeCurrentPath ( ) {
			var result = LinuxPath.GetPathRoot ( string.Empty );
			Assert.Equal ( "./", result );
		}

		[Fact]
		public void WhenPathIsRooted_ShouldReturnRootPath () {
			var fixture = new Fixture ( );
			var path = fixture.Create ( "/path-" );
			var result = LinuxPath.GetPathRoot ( path );
			Assert.Equal ( "/", result );
		}

		[Fact]
		public void WhenPathIsRelative_ShouldReturnRelativeCurrentPath ( ) {
			var fixture = new Fixture ( );
			var path = fixture.Create ( "path-" );
			var result = LinuxPath.GetPathRoot ( path );
			Assert.Equal ( "./", result );
		}

	}


}


<|start_filename|>Managed.AndroidDebugBridge/Debugger.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="Managed.Adb.IPacketConsumer" />
	public class Debugger : IPacketConsumer {
		/// <summary>
		/// 
		/// </summary>
		public enum ConnectionStates {
			/// <summary>
			/// not connected
			/// </summary>
			NotConnected = 1,
			/// <summary>
			/// await shake
			/// </summary>
			AwaitShake = 2,
			/// <summary>
			/// ready
			/// </summary>
			Ready = 3
		}
		private const int INITIAL_BUF_SIZE = 1 * 1024;
		private const int MAX_BUF_SIZE = 32 * 1024;

		private const int PRE_DATA_BUF_SIZE = 256;

		/// <summary>
		/// Initializes a new instance of the <see cref="Debugger"/> class.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="listenPort">The listen port.</param>
		public Debugger ( IClient client, int listenPort ) {
			this.Client = client;
			this.ListenPort = listenPort;

			IPEndPoint endPoint = new IPEndPoint ( IPAddress.Loopback, listenPort );
			ListenChannel = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			ListenChannel.Blocking = false;
			ListenChannel.ExclusiveAddressUse = false;
			ListenChannel.Bind ( endPoint );

			ConnectionState = ConnectionStates.NotConnected;
			Log.d ( "ddms", this.ToString ( ) );
		}


		/// <summary>
		/// Gets or sets the read buffer.
		/// </summary>
		/// <value>
		/// The read buffer.
		/// </value>
		public BinaryReader ReadBuffer { get; set; }
		/// <summary>
		/// Gets or sets the pre data buffer.
		/// </summary>
		/// <value>
		/// The pre data buffer.
		/// </value>
		public BinaryWriter PreDataBuffer { get; set; }
		/// <summary>
		/// Gets or sets the listen channel.
		/// </summary>
		/// <value>
		/// The listen channel.
		/// </value>
		public Socket ListenChannel { get; set; }
		/// <summary>
		/// Gets or sets the channel.
		/// </summary>
		/// <value>
		/// The channel.
		/// </value>
		public Socket Channel { get; set; }
		/// <summary>
		/// Gets or sets the client.
		/// </summary>
		/// <value>
		/// The client.
		/// </value>
		public IClient Client { get; set; }
		/// <summary>
		/// Gets or sets the listen port.
		/// </summary>
		/// <value>
		/// The listen port.
		/// </value>
		public int ListenPort { get; set; }
		/// <summary>
		/// Gets or sets the state of the connection.
		/// </summary>
		/// <value>
		/// The state of the connection.
		/// </value>
		public ConnectionStates ConnectionState { get; set; }

		/// <summary>
		/// Gets a value indicating whether this instance is debugger attached.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is debugger attached; otherwise, <c>false</c>.
		/// </value>
		public bool IsDebuggerAttached { get; private set; }


		/// <summary>
		/// Reads this instance.
		/// </summary>
		/// <exception cref="System.NotImplementedException"></exception>
		public void Read ( ) {
			throw new NotImplementedException ( );
			//int count;

			/*if ( mReadBuffer.position ( ) == mReadBuffer.capacity ( ) ) {
				if ( mReadBuffer.capacity ( ) * 2 > MAX_BUF_SIZE ) {
					throw new BufferOverflowException ( );
				}
				Log.d ( "ddms", "Expanding read buffer to "
						+ mReadBuffer.capacity ( ) * 2 );

				ByteBuffer newBuffer =
								ByteBuffer.allocate ( mReadBuffer.capacity ( ) * 2 );
				mReadBuffer.position ( 0 );
				newBuffer.put ( mReadBuffer );     // leaves "position" at end

				mReadBuffer = newBuffer;
			}

			count = mChannel.read ( mReadBuffer );
			Log.v ( "ddms", "Read " + count + " bytes from " + this );
			if ( count < 0 ) throw new IOException ( "read failed" );*/
		}

		/// <summary>
		/// Gets the JDWP packet.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="System.NotImplementedException"></exception>
		public /*JdwpPacket*/ Object GetJdwpPacket ( ) {
			throw new NotImplementedException ( );

			/*if (mConnState == ST_AWAIT_SHAKE) {
            int result;

            result = JdwpPacket.findHandshake(mReadBuffer);
            //Log.v("ddms", "findHand: " + result);
            switch (result) {
                case JdwpPacket.HANDSHAKE_GOOD:
                    Log.d("ddms", "Good handshake from debugger");
                    JdwpPacket.consumeHandshake(mReadBuffer);
                    sendHandshake();
                    mConnState = ST_READY;

                    ClientData cd = mClient.getClientData();
                    cd.setDebuggerConnectionStatus(DebuggerStatus.ATTACHED);
                    mClient.update(Client.CHANGE_DEBUGGER_STATUS);

                    // see if we have another packet in the buffer
                    return getJdwpPacket();
                case JdwpPacket.HANDSHAKE_BAD:
                    // not a debugger, throw an exception so we drop the line
                    Log.d("ddms", "Bad handshake from debugger");
                    throw new IOException("bad handshake");
                case JdwpPacket.HANDSHAKE_NOTYET:
                    break;
                default:
                    Log.e("ddms", "Unknown packet while waiting for client handshake");
            }
            return null;
        } else if (mConnState == ST_READY) {
            if (mReadBuffer.position() != 0) {
                Log.v("ddms", "Checking " + mReadBuffer.position() + " bytes");
            }
            return JdwpPacket.findPacket(mReadBuffer);
        } else {
            Log.e("ddms", "Receiving data in state = " + mConnState);
        }

        return null;*/
		}

		// TODO: JdwpPacket
		/// <summary>
		/// Forwards the packet to client.
		/// </summary>
		/// <param name="packet">The packet.</param>
		public void ForwardPacketToClient ( /*JdwpPacket*/ Object packet ) {
			Client.SendAndConsume ( packet );
		}

		/// <summary>
		/// Sends the handshake.
		/// </summary>
		/// <returns></returns>
		/// <exception cref="System.NotImplementedException"></exception>
		public bool SendHandshake ( ) {
			throw new NotImplementedException ( );
			/*ByteBuffer tempBuffer = ByteBuffer.allocate ( JdwpPacket.HANDSHAKE_LEN );
			JdwpPacket.PutHandshake ( tempBuffer );
			int expectedLength = tempBuffer.position ( );
			tempBuffer.flip ( );
			if ( Channel.Send ( tempBuffer ) != expectedLength ) {
				throw new IOException ( "partial handshake write" );
			}

			expectedLength = PreDataBuffer.BaseStream.Position;
			if ( expectedLength > 0 ) {
				Log.d ( "ddms", "Sending " + PreDataBuffer.BaseStream.Position
								+ " bytes of saved data" );
				//PreDataBuffer.flip ( );
				if ( Channel.Send ( PreDataBuffer ) != expectedLength ) {
					throw new IOException ( "partial pre-data write" );
				}
				PreDataBuffer.
			}*/
		}

		//TODO: JdwpPacket
		/// <summary>
		/// Sends the and consume.
		/// </summary>
		/// <param name="packet">The packet.</param>
		public void SendAndConsume ( /*JdwpPacket*/ Object packet ) {
			if ( Channel == null ) {
				/*
				 * Buffer this up so we can send it to the debugger when it
				 * finally does connect.  This is essential because the VM_START
				 * message might be telling the debugger that the VM is
				 * suspended.  The alternative approach would be for us to
				 * capture and interpret VM_START and send it later if we
				 * didn't choose to un-suspend the VM for our own purposes.
				 */
				//Log.d ( "ddms", "Saving packet 0x" + packet.ID.ToString ( "X" ) );
				//packet.MovePacket ( PreDataBuffer );
			} else {
				//packet.WriteAndConsume ( Channel );
			}
		}

		//		public voidr RegisterListener

		/// <summary>
		/// Accepts this instance.
		/// </summary>
		/// <returns></returns>
		public Socket Accept ( ) {
			return Accept ( ListenChannel );
		}

		/// <summary>
		/// Accepts the specified listen chan.
		/// </summary>
		/// <param name="listenChan">The listen chan.</param>
		/// <returns></returns>
		public Socket Accept ( Socket listenChan ) {
			lock ( listenChan ) {
				if ( listenChan != null ) {
					Socket newChan = listenChan.Accept ( );
					if ( Channel != null ) {
						Log.w ( "ddms", "debugger already talking to " + Client.ToString ( ) + " on " + ListenPort.ToString ( ) );
						newChan.Close ( );
						return null;
					}

					Channel = newChan;
					Channel.Blocking = false;
					ConnectionState = ConnectionStates.AwaitShake;
					return Channel;
				}

				return null;
			}
		}

		/// <summary>
		/// Closes the data.
		/// </summary>
		public void CloseData ( ) {
			try {
				if ( Channel != null ) {
					Channel.Close ( );
					Channel = null;
					ConnectionState = ConnectionStates.NotConnected;

					//TODO: ClientData
					/*ClientData cd = Client.ClientData;
					cd.DebuggerConnectionStatus = DebuggerStatus.Default;*/
					Client.Update ( ClientChangeMask.ChangeDebuggerStatus );

				}
			} catch ( IOException ioe ) {
				Log.w ( "ddms", ioe );
			}
		}

		/// <summary>
		/// Closes this instance.
		/// </summary>
		public void Close ( ) {
			try {
				if ( ListenChannel != null ) {
					ListenChannel.Close ( );
				}
				ListenChannel = null;
				CloseData ( );
			} catch ( IOException ioe ) {
				Log.w ( "ddms", ioe );
			}
		}

		/// <summary>
		/// Returns a <see cref="System.String" /> that represents this instance.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String" /> that represents this instance.
		/// </returns>
		public override string ToString ( ) {
			// mChannel != null means we have connection, ST_READY means it's going
			return "[Debugger " + ListenPort + "-->" + Client.ClientData/*.Pid*/
							+ ( ( ConnectionState != ConnectionStates.Ready ) ? " inactive]" : " active]" );
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/IDevice.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;

namespace Managed.Adb {

	/// <summary>
	/// 
	/// </summary>
	public interface IDevice {

		/// <summary>
		/// Occurs when device state changed.
		/// </summary>
		event EventHandler<EventArgs> StateChanged;
		/// <summary>
		/// Occurs when build info changed.
		/// </summary>
		event EventHandler<EventArgs> BuildInfoChanged;
		/// <summary>
		/// Occurs when client list changed.
		/// </summary>
		event EventHandler<EventArgs> ClientListChanged;

		/// <summary>
		/// Gets the file system.
		/// </summary>
		/// <value>
		/// The file system.
		/// </value>
		FileSystem FileSystem { get; }

		/// <summary>
		/// Gets the busy box.
		/// </summary>
		/// <value>
		/// The busy box.
		/// </value>
		BusyBox BusyBox { get; }

		/// <summary>
		/// Gets the serial number of the device.
		/// </summary>
		/// <value>The serial number.</value>
		string SerialNumber { get; }
		/// <summary>
		/// Gets the TCP endpoint defined when the transport is TCP.
		/// </summary>
		/// <value>
		/// The endpoint.
		/// </value>
		IPEndPoint Endpoint { get; }

		/// <summary>
		/// Gets the type of the transport used to connect to this device.
		/// </summary>
		/// <value>
		/// The type of the transport.
		/// </value>
		TransportType TransportType { get; }

		/// <summary>
		/// Returns the name of the AVD the emulator is running.
		/// <p/>
		/// This is only valid if {@link #isEmulator()} returns true.
		/// <p/>
		/// If the emulator is not running any AVD (for instance it's running from an Android source
		/// tree build), this method will return "<code>&lt;build&gt;</code>"
		/// @return the name of the AVD or  <code>null</code>
		///  if there isn't any.
		/// </summary>
		/// <value>The name of the avd.</value>
		string AvdName { get; set; }

		/// <summary>
		/// Gets the environment variables.
		/// </summary>
		/// <value>The environment variables.</value>
		Dictionary<string, string> EnvironmentVariables { get; }

		/// <summary>
		/// Gets the mount points.
		/// </summary>
		/// <value>The mount points.</value>
		Dictionary<string, MountPoint> MountPoints { get; }

		/// <summary>
		/// Gets the state.
		/// </summary>
		/// <value>The state.</value>
		/// Returns the state of the device.
		DeviceState State { get; }

		/// <summary>
		/// Returns the device properties. It contains the whole output of 'getprop'
		/// </summary>
		/// <value>The properties.</value>
		Dictionary<string, string> Properties { get; }

		/// <summary>
		/// Gets the property value.
		/// </summary>
		/// <param name="name">The name of the property.</param>
		/// <returns>
		/// the value or <code>null</code> if the property does not exist.
		/// </returns>
		string GetProperty ( string name );
		/// <summary>
		/// Gets the first property that exists in the array of property names.
		/// </summary>
		/// <param name="name">The array of property names.</param>
		/// <returns>
		/// the value or <code>null</code> if the property does not exist.
		/// </returns>
		string GetProperty ( params string[] name );

		/// <summary>
		/// Gets a value indicating whether the device is online.
		/// </summary>
		/// <value><c>true</c> if the device is online; otherwise, <c>false</c>.</value>
		bool IsOnline { get; }


		/// <summary>
		/// Gets a value indicating whether this device is emulator.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this device is emulator; otherwise, <c>false</c>.
		/// </value>
		bool IsEmulator { get; }

		/// <summary>
		/// Gets a value indicating whether this device is offline.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this device is offline; otherwise, <c>false</c>.
		/// </value>
		bool IsOffline { get; }


		/// <summary>
		/// Gets a value indicating whether this device is in boot loader mode.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this device is in boot loader mode; otherwise, <c>false</c>.
		/// </value>
		bool IsBootLoader { get; }

		/*
		 * Returns whether the {@link Device} has {@link Client}s.
		 */
		//bool HasClients { get; }

		/// <summary>
		/// Gets the list of clients
		/// </summary>
		List<IClient> Clients { get; }

		/*
		 * Returns a {@link Client} by its application name.
		 * @param applicationName the name of the application
		 * @return the <code>Client</code> object or <code>null</code> if no match was found.
		 */
		//Client GetClient(String applicationName);

		/// <summary>
		/// Returns a <see cref="SyncService" /> object to push / pull files to and from the device.
		/// </summary>
		/// <value>
		/// The synchronize service.
		/// </value>
		/// <exception cref="System.IO.IOException">Throws IOException if the connection with adb failed.</exception>
		/// <remarks>
		/// <code>null</code> if the SyncService couldn't be created. This can happen if adb
		/// refuse to open the connection because the {@link IDevice} is invalid (or got disconnected).
		/// </remarks>
		SyncService SyncService { get; }

		/// <summary>
		/// Returns a <see cref="FileListingService" /> for this device.
		/// </summary>
		/// <value>
		/// The file listing service.
		/// </value>
		FileListingService FileListingService { get; }


		/// <summary>
		/// Takes a screen shot of the device and returns it as a <see cref="RawImage"/>
		/// </summary>
		/// <value>The screenshot.</value>
		RawImage Screenshot { get; }

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		void ExecuteShellCommand ( string command, IShellOutputReceiver receiver );
		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		void ExecuteShellCommand ( string command, IShellOutputReceiver receiver, int maxTimeToOutputResponse );

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="commandArgs">The command args.</param>
		void ExecuteShellCommand ( string command, IShellOutputReceiver receiver, params object[] commandArgs );

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		/// <param name="commandArgs">The command args.</param>
		void ExecuteShellCommand ( string command, IShellOutputReceiver receiver, int maxTimeToOutputResponse, params object[] commandArgs );


		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="commandArgs">The command args.</param>
		void ExecuteRootShellCommand ( string command, IShellOutputReceiver receiver, params object[] commandArgs );

		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		/// <param name="commandArgs">The command args.</param>
		void ExecuteRootShellCommand ( string command, IShellOutputReceiver receiver, int maxTimeToOutputResponse, params object[] commandArgs );

		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		void ExecuteRootShellCommand ( string command, IShellOutputReceiver receiver );

		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		void ExecuteRootShellCommand ( string command, IShellOutputReceiver receiver, int maxTimeToOutputResponse );
		/*
		 * Runs the event log service and outputs the event log to the {@link LogReceiver}.
		 * @param receiver the receiver to receive the event log entries.
		 * @throws IOException
		 */
		//void RunEventLogService(LogReceiver receiver);

		/*
		 * Runs the log service for the given log and outputs the log to the {@link LogReceiver}.
		 * @param logname the logname of the log to read from.
		 * @param receiver the receiver to receive the event log entries.
		 * @throws IOException
		 */
		//void RunLogService(String logname, LogReceiver receiver);
		
		/// <summary>
		/// Creates a port forwarding between a local and a remote port.
		/// </summary>
		/// <param name="localPort">the local port to forward</param>
		/// <param name="remotePort">the remote port.</param>
		/// <returns><code>true</code> if success.</returns>
		bool CreateForward(int localPort, int remotePort);

		/// <summary>
		/// Creates a reverse port forwarding between a local and a remote port.
		/// </summary>
		/// <param name="remotePort">the remote port to forward</param>
		/// <param name="localPort">the local port.</param>
		/// <returns><code>true</code> if success.</returns>
		bool CreateReverseForward ( int remotePort, int localPort );

		/// <summary>
		/// Removes a port forwarding between a local and a remote port.
		/// </summary>
		/// <param name="localPort"> the local port to forward</param>
		/// <returns><code>true</code> if success.</returns>
		bool RemoveForward ( int localPort );

		/*
		 * Returns the name of the client by pid or <code>null</code> if pid is unknown
		 * @param pid the pid of the client.
		 */
		//String GetClientName(int pid);

		/// <summary>
		/// Installs an Android application on device.
		/// This is a helper method that combines the syncPackageToDevice, installRemotePackage,
		/// and removePackage steps
		/// </summary>
		/// <param name="packageFilePath">the absolute file system path to file on local host to install</param>
		/// <param name="reinstall">set to <code>true</code>if re-install of app should be performed</param>
		void InstallPackage ( string packageFilePath, bool reinstall );

		/// <summary>
		/// Pushes a file to device
		/// </summary>
		/// <param name="localFilePath">the absolute path to file on local host</param>
		/// <returns>
		/// destination path on device for file
		/// </returns>
		/// <exception cref="System.IO.IOException">if fatal error occurred when pushing file</exception>
		string SyncPackageToDevice ( string localFilePath );
 
		/// <summary>
		/// Installs the application package that was pushed to a temporary location on the device.
		/// </summary>
		/// <param name="remoteFilePath">absolute file path to package file on device</param>
		/// <param name="reinstall">set to <code>true</code> if re-install of app should be performed</param>
		void InstallRemotePackage( string remoteFilePath, bool reinstall);


		/// <summary>
		/// Remove a file from device
		/// </summary>
		/// <param name="remoteFilePath">path on device of file to remove</param>
		/// <exception cref="System.IO.IOException">if file removal failed</exception>
		void RemoveRemotePackage(string remoteFilePath);

		/// <summary>
		/// Uninstall an package from the device.
		/// </summary>
		/// <param name="packageName">Name of the package.</param>
		/// <exception cref="System.IO.IOException"></exception>
		/// <exception cref="Exceptions.PackageInstallationException"></exception>
		void UninstallPackage (string packageName) ;

		/// <summary>
		/// Refreshes the environment variables.
		/// </summary>
		void RefreshEnvironmentVariables ( );

		/// <summary>
		/// Refreshes the mount points.
		/// </summary>
		void RefreshMountPoints ( );

		/// <summary>
		/// Refreshes the properties.
		/// </summary>
		void RefreshProperties ( );
	}
}


<|start_filename|>Madb.Site/Extensions/XmlDocumentationReader.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using Camalot.Common.Extensions;

namespace Madb.Site.Extensions {
	public static partial class MadbSiteExtensions {

		public static string GetXmlDocumentationName(this MethodInfo mi) {
			var mparams = mi.GetParameters();
			var gcount = mi.GetGenericArguments().Count();
			var generics = mi.GetGenericArguments().Select((generic, index) => new { generic, index });
			var paramItems = mparams.Select((p, index) => new {
				p,
				index = generics.Where(x => x.generic == p.ParameterType).Count() > 0 ? generics.Where(x => x.generic == p.ParameterType).First().index : index
			}).Select(x => x.p.ParameterType.XmlDocumentParameterSafeName(x.index));

			return "M:{0}.{1}{2}{4}{3}{5}".With(

				mi.ReflectedType.XmlDocumentTypeSafeName(),
				mi.Name,
				gcount > 0 ? "``{0}".With(gcount) : "",
				string.Join(",", paramItems),
				mparams.Count() > 0 ? "(" : "",
				mparams.Count() > 0 ? ")" : ""
				);
		}

		public static string GetXmlDocumentationName(this PropertyInfo propertyInfo) {
			return "P:{0}.{1}".With(propertyInfo.ReflectedType.XmlDocumentTypeSafeName(), propertyInfo.Name);
		}

		public static string GetXmlDocumentationName(this Type type) {
			return "T:{0}.{1}".With(type.Namespace,type.Name);
		}

		private static string XmlDocumentTypeSafeName(this Type type) {
			return "{1}.{0}".With(type.Name.Replace("`", "``"), type.Namespace);
		}

		private static string XmlDocumentParameterSafeName(this Type type, int index) {
			var gparams = type.GetGenericArguments();
			var s = new StringBuilder();
			s.Append("{");
			for(var i = 0; i < gparams.Length; ++i) {
				if(gparams.Length > 1) {
					s.Append("``{0},".With(i));
				} else {
					s.Append(gparams[i].GetXmlParameterTypeSaveName(i));
				}
			}
			if(s.Length > 1 && s[s.Length - 1] == ',') {
				s.Remove(s.Length - 1, 1);
			}
			s.Append("}");
			if(type.IsGenericType) {
				return "{1}.{0}{2}".With(type.Name.Substring(0, type.Name.LastIndexOf("`")), type.Namespace, s);
			} else if(type.IsGenericParameter) {
				return "``{0}".With(index);
			} else if(type.IsGenericTypeDefinition) {
				return "GTD";
			} else {
				return "{1}.{0}".With(type.Name, type.Namespace);
			}
		}

		private static string GetXmlParameterTypeSaveName(this Type type, int index) {
			if(type.IsGenericParameter) {
				return "``{0}".With(index);
			} else {
				return "{1}.{0}".With(type.Name, type.Namespace);
			}
		}

		public static Models.Documentation.Xml.Member GetDocumenation(this XmlDocument doc, MethodInfo mi) {
			var itemName = mi.GetXmlDocumentationName();
			var tdoc = new XmlDocument();

			var node = doc.SelectSingleNode("//member[@name=\"{0}\"]".With(itemName));
			if(node == null) {
				return null;
			}
			var nnode = tdoc.ImportNode(node, true);
			tdoc.AppendChild(nnode);
			var serializer = new XmlSerializer(typeof(Models.Documentation.Xml.Member));
			using(var reader = new StringReader(tdoc.OuterXml)) {
				using(var xreader = XmlReader.Create(reader)) {
					var member = serializer.Deserialize(xreader) as Models.Documentation.Xml.Member;
					if(mi.IsExtension()) {
						if(member.Params.Count > 0) {
							member.Params.RemoveAt(0);
						}
					}
					return member;
				}
			}
		}

		public static Models.Documentation.Xml.Member GetDocumenation(this XmlDocument doc, PropertyInfo pi) {
			var itemName = pi.GetXmlDocumentationName();
			var tdoc = new XmlDocument();

			var node = doc.SelectSingleNode("//member[@name=\"{0}\"]".With(itemName));
			if(node == null) {
				return null;
			}
			var nnode = tdoc.ImportNode(node, true);
			tdoc.AppendChild(nnode);
			var serializer = new XmlSerializer(typeof(Models.Documentation.Xml.Member));
			using(var reader = new StringReader(tdoc.OuterXml)) {
				using(var xreader = XmlReader.Create(reader)) {
					var member = serializer.Deserialize(xreader) as Models.Documentation.Xml.Member;
					return member;
				}
			}
		}

		public static Models.Documentation.Xml.Member GetDocumenation(this XmlDocument doc, Type type) {
			var itemName = type.GetXmlDocumentationName();
			var tdoc = new XmlDocument();

			var node = doc.SelectSingleNode("//member[@name=\"{0}\"]".With(itemName));
			if(node == null) {
				return null;
			}
			var nnode = tdoc.ImportNode(node, true);
			tdoc.AppendChild(nnode);
			var serializer = new XmlSerializer(typeof(Models.Documentation.Xml.Member));
			using(var reader = new StringReader(tdoc.OuterXml)) {
				using(var xreader = XmlReader.Create(reader)) {
					var member = serializer.Deserialize(xreader) as Models.Documentation.Xml.Member;
					return member;
				}
			}
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Logs/LogReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Logs {
	/// <summary>
	/// 
	/// </summary>
	public class LogReceiver {
		/// <summary>
		/// The entr y_ heade r_ size
		/// </summary>
		private const int ENTRY_HEADER_SIZE = 20; // 2*2 + 4*4; see LogEntry.
		/// <summary>
		/// Initializes a new instance of the <see cref="LogReceiver"/> class.
		/// </summary>
		/// <param name="listener">The listener.</param>
		public LogReceiver ( ILogListener listener ) {
			EntryDataOffset = 0;
			EntryHeaderBuffer = new byte[ENTRY_HEADER_SIZE];
			EntryHeaderOffset = 0;
			Listener = listener;
		}

		/// <summary>
		/// Gets or sets the entry data offset.
		/// </summary>
		/// <value>
		/// The entry data offset.
		/// </value>
		private int EntryDataOffset { get; set; }
		/// <summary>
		/// Gets or sets the entry header offset.
		/// </summary>
		/// <value>
		/// The entry header offset.
		/// </value>
		private int EntryHeaderOffset { get; set; }
		/// <summary>
		/// Gets or sets the entry header buffer.
		/// </summary>
		/// <value>
		/// The entry header buffer.
		/// </value>
		private byte[] EntryHeaderBuffer { get; set; }

		/// <summary>
		/// Gets or sets the current entry.
		/// </summary>
		/// <value>
		/// The current entry.
		/// </value>
		private LogEntry CurrentEntry { get; set; }
		/// <summary>
		/// Gets or sets the listener.
		/// </summary>
		/// <value>
		/// The listener.
		/// </value>
		private ILogListener Listener { get; set; }
		/// <summary>
		/// Gets a value indicating whether this instance is cancelled.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is cancelled; otherwise, <c>false</c>.
		/// </value>
		public bool IsCancelled { get; private set; }

		/// <summary>
		/// Cancels this instance.
		/// </summary>
		public void Cancel ( ) {
			this.IsCancelled = true;
		}

		/// <summary>
		/// Parses the new data.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		public void ParseNewData ( byte[] data, int offset, int length ) {
			// notify the listener of new raw data
			if ( Listener != null ) {
				Listener.NewData ( data, offset, length );
			}

			// loop while there is still data to be read and the receiver has not be cancelled.
			while ( length > 0 && !IsCancelled ) {
				// first check if we have no current entry.
				if ( CurrentEntry == null ) {
					if ( EntryHeaderOffset + length < ENTRY_HEADER_SIZE ) {
						// if we don't have enough data to finish the header, save
						// the data we have and return
						Array.Copy ( data, offset, EntryHeaderBuffer, EntryHeaderOffset, length );
						EntryHeaderOffset += length;
						return;
					} else {
						// we have enough to fill the header, let's do it.
						// did we store some part at the beginning of the header?
						if ( EntryHeaderOffset != 0 ) {
							// copy the rest of the entry header into the header buffer
							int size = ENTRY_HEADER_SIZE - EntryHeaderOffset;
							Array.Copy ( data, offset, EntryHeaderBuffer, EntryHeaderOffset, size );

							// create the entry from the header buffer
							CurrentEntry = CreateEntry ( EntryHeaderBuffer, 0 );

							// since we used the whole entry header buffer, we reset  the offset
							EntryHeaderOffset = 0;

							// adjust current offset and remaining length to the beginning
							// of the entry data
							offset += size;
							length -= size;
						} else {
							// create the entry directly from the data array
							CurrentEntry = CreateEntry ( data, offset );
							// adjust current offset and remaining length to the beginning
							// of the entry data
							offset += ENTRY_HEADER_SIZE;
							length -= ENTRY_HEADER_SIZE;
						}
					}
				}


				// at this point, we have an entry, and offset/length have been updated to skip
				// the entry header.
				if ( length >= CurrentEntry.Length - EntryDataOffset ) {
					// compute and save the size of the data that we have to read for this entry,
					// based on how much we may already have read.
					int dataSize = CurrentEntry.Length - EntryDataOffset;

					// we only read what we need, and put it in the entry buffer.
					Array.Copy ( data, offset, CurrentEntry.Data, EntryDataOffset, dataSize );

					// notify the listener of a new entry
					if ( Listener != null ) {
						Listener.NewEntry ( CurrentEntry );
					}

					// reset some flags: we have read 0 data of the current entry.
					// and we have no current entry being read.
					EntryDataOffset = 0;
					CurrentEntry = null;

					// and update the data buffer info to the end of the current entry / start
					// of the next one.
					offset += dataSize;
					length -= dataSize;
				} else {
					// we don't have enough data to fill this entry, so we store what we have
					// in the entry itself.
					Array.Copy ( data, offset, CurrentEntry.Data, EntryDataOffset, length );

					// save the amount read for the data.
					EntryDataOffset += length;
					return;
				}
			}
		}


		/// <summary>
		/// Creates the entry.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="offset">The offset.</param>
		/// <returns></returns>
		/// <exception cref="System.ArgumentException">Buffer not big enough to hold full LoggerEntry header</exception>
		private LogEntry CreateEntry ( byte[] data, int offset ) {
			if ( data.Length < offset + ENTRY_HEADER_SIZE ) {
				throw new ArgumentException ( "Buffer not big enough to hold full LoggerEntry header" );
			}

			// create the new entry and fill it.
			LogEntry entry = new LogEntry ( );
			entry.Length = data.SwapU16bitFromArray ( offset );

			// we've read only 16 bits, but since there's also a 16 bit padding,
			// we can skip right over both.
			offset += 4;

			entry.ProcessId = data.Swap32bitFromArray ( offset );
			offset += 4;
			entry.ThreadId = data.Swap32bitFromArray ( offset );
			offset += 4;
			var sec = data.Swap32bitFromArray ( offset );
			
			offset += 4;
			entry.NanoSeconds = data.Swap32bitFromArray ( offset );
			offset += 4;

			// allocate the data
			entry.Data = new byte[entry.Length];

			return entry;
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/ChunkHandler.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public abstract class ChunkHandler {
		/// <summary>
		/// 
		/// </summary>
		public enum ByteOrder {
			/// <summary>
			/// 
			/// </summary>
			LittleEndian,
			/// <summary>
			/// 
			/// </summary>
			BigEndian
		}

		/// <summary>
		/// 
		/// </summary>
		public const int CHUNK_HEADER_LEN = 8;   // 4-byte type, 4-byte len
		/// <summary>
		/// 
		/// </summary>
		public const ByteOrder CHUNK_ORDER = ByteOrder.BigEndian;

		/// <summary>
		/// 
		/// </summary>
		public const int CHUNK_FAIL = -1;

		/// <summary>
		/// Prevents a default instance of the <see cref="ChunkHandler"/> class from being created.
		/// </summary>
		ChunkHandler ( ) { }

		/**
		 * Client is ready.  The monitor thread calls this method on all
		 * handlers when the client is determined to be DDM-aware (usually
		 * after receiving a HELO response.)
		 *
		 * The handler can use this opportunity to initialize client-side
		 * activity.  Because there's a fair chance we'll want to send a
		 * message to the client, this method can throw an IOException.
		 */
		public abstract void ClientReady ( IClient client );

		/**
		 * Client has gone away.  Can be used to clean up any resources
		 * associated with this client connection.
		 */
		public abstract void ClientDisconnected ( IClient client );

		/**
		 * Handle an incoming chunk.  The data, of chunk type "type", begins
		 * at the start of "data" and continues to data.limit().
		 *
		 * If "isReply" is set, then "msgId" will be the ID of the request
		 * we sent to the client.  Otherwise, it's the ID generated by the
		 * client for this event.  Note that it's possible to receive chunks
		 * in reply packets for which we are not registered.
		 *
		 * The handler may not modify the contents of "data".
		 */
		public abstract void HandleChunk ( IClient client, int type,
				byte[] data, bool isReply, int msgId );

		/**
		 * Handle chunks not recognized by handlers.  The handleChunk() method
		 * in sub-classes should call this if the chunk type isn't recognized.
		 */
		protected void handleUnknownChunk ( IClient client, int type,
				MemoryStream data, bool isReply, int msgId ) {
			if ( type == CHUNK_FAIL ) {
				int errorCode, msgLen;
				String msg;

				errorCode = data.ReadByte ( );
				msgLen = data.ReadByte ( );

				msg = GetString ( data, msgLen );
				Log.w ( "ddms", "WARNING: failure code=" + errorCode + " msg=" + msg );
			} else {
				Log.w ( "ddms", "WARNING: received unknown chunk " + name ( type )
						+ ": len=" + data.Length + ", reply=" + isReply
						+ ", msgId=0x" + msgId.ToString ( "X8" ) );
			}
			Log.w ( "ddms", "         client " + client + ", handler " + this );
		}


		/**
		 * Utility function to copy a String out of a ByteBuffer.
		 *
		 * This is here because multiple chunk handlers can make use of it,
		 * and there's nowhere better to put it.
		 */
		static String GetString ( MemoryStream buf, int len ) {
			char[] data = new char[len];
			for ( int i = 0; i < len; i++ )
				data[i] = (char)buf.ReadByte ( );
			return new String ( data );
		}

		/**
		 * Utility function to copy a String into a ByteBuffer.
		 */
		static void PutString ( MemoryStream buf, String str ) {
			byte[] data = Encoding.Default.GetBytes ( str );
			buf.Write ( data, 0, data.Length );
		}

		/**
		 * Convert a 4-character string to a 32-bit type.
		 */
		static int type ( String typeName ) {
			int val = 0;

			if ( typeName.Length != 4 ) {
				Log.e ( "ddms", "Type name must be 4 letter long" );
				throw new ArgumentException ( "Type name must be 4 letter long" );
			}

			for ( int i = 0; i < 4; i++ ) {
				val <<= 8;
				val |= (byte)typeName[i];
			}

			return val;
		}

		/**
		 * Convert an integer type to a 4-character string.
		 */
		static String name ( int type ) {
			char[] ascii = new char[4];

			ascii[0] = (char)( ( type >> 24 ) & 0xff );
			ascii[1] = (char)( ( type >> 16 ) & 0xff );
			ascii[2] = (char)( ( type >> 8 ) & 0xff );
			ascii[3] = (char)( type & 0xff );

			return new String ( ascii );
		}

		/**
		 * Allocate a ByteBuffer with enough space to hold the JDWP packet
		 * header and one chunk header in addition to the demands of the
		 * chunk being created.
		 *
		 * "maxChunkLen" indicates the size of the chunk contents only.
		 */
		static BinaryReader allocBuffer ( int maxChunkLen ) {
			/*
			using ( MemoryStream ms = new MemoryStream(JdwpPacket.JDWP_HEADER_LEN + 8 +maxChunkLen) ) {
				using ( EndianBinaryReader ebr = new EndianBinaryReader(CHUNK_ORDER == ByteOrder.LittleEndian ? EndianBitConverter.Little : EndianBitConverter.Big, ms ) ) {
					return ebr;
				}
			}
			 */
			return null;
		}

		/**
		 * Return the slice of the JDWP packet buffer that holds just the
		 * chunk data.
		 */
		static BinaryReader GetChunkDataBuf ( MemoryStream jdwpBuf ) {
			/* EndianBinaryReader ebr = null;

			 System.Diagnostics.Debug.Assert ( jdwpBuf.Position == 0 );

			 jdwpBuf.Position = JdwpPacket.JDWP_HEADER_LEN + CHUNK_HEADER_LEN;
		 EndianBitConverter ebc = null;
		 if ( CHUNK_ORDER == ByteOrder.LittleEndian ) {
			 ebc = EndianBitConverter.Little;
		 } else {
			 ebc =	EndianBitConverter.Big;
		 }
			 ebr = new EndianBinaryReader(ebc,new MemoryStream(jdwpBuf.ToArray()) );
			 jdwpBuf.Position = 0;
			 return ebr;*/

			return null;
		}

		/**
		 * Write the chunk header at the start of the chunk.
		 *
		 * Pass in the byte buffer returned by JdwpPacket.getPayload().
		 */
		// TODO: JdwpPacket
		static void finishChunkPacket (/*JdwpPacket*/ Object packet, int type, int chunkLen ) {
			/*ByteBuffer buf = packet.getPayload();

			buf.putInt(0x00, type);
			buf.putInt(0x04, chunkLen);

			packet.finishPacket(CHUNK_HEADER_LEN + chunkLen);*/
		}

		/**
		 * Check that the client is opened with the proper debugger port for the
		 * specified application name, and if not, reopen it.
		 * @param client
		 * @param uiThread
		 * @param appName
		 * @return
		 */
		protected static IClient checkDebuggerPortForAppName ( IClient client, String appName ) {
			/*IDebugPortProvider provider = DebugPortManager.getProvider ( );
			if ( provider != null ) {
				Device device = client.GetDeviceImpl ( );
				int newPort = provider.GetPort ( device, appName );

				if ( newPort != IDebugPortProvider.NO_STATIC_PORT &&
								newPort != client.getDebuggerListenPort ( ) ) {

					AndroidDebugBridge bridge = AndroidDebugBridge.Bridge;
					if ( bridge != null ) {
						DeviceMonitor deviceMonitor = bridge.DeviceMonitor;
						if ( deviceMonitor != null ) {
							deviceMonitor.addClientToDropAndReopen ( client, newPort );
							client = null;
						}
					}
				}
			}*/

			return client;
		}
	}
}


<|start_filename|>Madb.Site/assets/styles/endpointmvc.css<|end_filename|>
﻿.epm-content {
  background-color: #fff;
}
.epm-nav-host {
  position: fixed;
  top: 49px;
  width: 50px;
  z-index: 1036;
}
.epm-nav-host.expanded.left {
  left: 299px;
}
.epm-nav-host.expanded.right {
  right: 299px;
}
.epm-nav-host.left {
  left: 0;
  -moz-transition: left linear 300ms;
  -o-transition: left linear 300ms;
  -webkit-transition: left linear 300ms;
  transition: left linear 300ms;
}
.epm-nav-host.left .epm-nav-toggle {
  border-right: solid 1px #2371f2;
  margin-right: 5px;
}
.epm-nav-host.right {
  right: 0;
  -moz-transition: right linear 300ms;
  -o-transition: right linear 300ms;
  -webkit-transition: right linear 300ms;
  transition: right linear 300ms;
}
.epm-nav-host.right .epm-nav-toggle {
  border-left: solid 1px #2371f2;
  margin-left: 5px;
}
.epm-nav-host .epm-nav-toggle {
  box-shadow: 0 0.5em 1em -3px rgba(0, 0, 0, 0.258824);
  display: block;
  border: none;
  background-color: #4285f4;
  border-bottom: solid 1px #2371f2;
  border-radius: 0;
  cursor: pointer;
  padding: 10px;
  z-index: 1030;
}
.epm-nav-host .epm-nav-toggle > .icon-bar {
  background-color: #dddddd;
  display: block;
  width: 22px;
  height: 3px;
}
.epm-nav-host .epm-nav-toggle > .icon-bar + .icon-bar {
  margin-top: 4px;
}
.epm-nav-host .epm-nav-toggle > .icon-bar:hover > .icon-bar {
  background-color: #e5e5e5;
}
.epm-nav {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  z-index: 1035;
  border: none;
  background-color: #4285f4;
  width: 300px;
  max-width: 300px;
  position: fixed;
  top: 49px;
  bottom: 0;
  overflow-y: auto;
  overflow-x: auto;
  white-space: nowrap;
}
.epm-nav::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.epm-nav::-webkit-scrollbar-track {
  background-color: transparent;
  -webkit-border-radius: 5px;
}
.epm-nav::-webkit-scrollbar-thumb:vertical {
  background-color: #2371f2;
  -webkit-border-radius: 6px;
}
.epm-nav::-webkit-scrollbar-thumb:vertical:hover,
.epm-nav::-webkit-scrollbar-thumb:horizontal:hover {
  background-color: #669cf6;
}
.epm-nav::-webkit-scrollbar-thumb:horizontal {
  background-color: #2371f2;
  -webkit-border-radius: 6px;
}
.epm-nav .nav.nested {
  height: 0;
  overflow: hidden;
}
.epm-nav .nav.nested.nav-always-expanded,
.epm-nav .nav.nested.nav-expanded {
  height: auto;
}
.epm-nav.left {
  left: -305px;
  border-right: solid 1px #2371f2;
  -moz-transition: left linear 300ms;
  -o-transition: left linear 300ms;
  -webkit-transition: left linear 300ms;
  transition: left linear 300ms;
}
.epm-nav.left li > a {
  border-right: 2px solid #4285f4;
}
.epm-nav.left li.active > a {
  border-right-color: #ffffff;
}
.epm-nav.left.epm-nav-primary li.active > a {
  border-right-color: #9c27b0;
}
.epm-nav.left.epm-nav-success li.active > a {
  border-right-color: #259b24;
}
.epm-nav.left.epm-nav-danger li.active > a {
  border-right-color: #e51c23;
}
.epm-nav.left.epm-nav-warning li.active > a {
  border-right-color: #ff5722;
}
.epm-nav.left.epm-nav-info li.active > a {
  border-right-color: #00bcd4;
}
.epm-nav.right {
  right: -305px;
  border-left: solid 1px #2371f2;
  -moz-transition: right linear 300ms;
  -o-transition: right linear 300ms;
  -webkit-transition: right linear 300ms;
  transition: right linear 300ms;
}
.epm-nav.right li > a {
  border-left: 2px solid #4285f4;
}
.epm-nav.right li.active > a {
  border-left-color: #ffffff;
}
.epm-nav.right.epm-nav-primary li.active > a {
  border-left-color: #9c27b0;
}
.epm-nav.right.epm-nav-success li.active > a {
  border-left-color: #259b24;
}
.epm-nav.right.epm-nav-danger li.active > a {
  border-left-color: #e51c23;
}
.epm-nav.right.epm-nav-warning li.active > a {
  border-left-color: #ff5722;
}
.epm-nav.right.epm-nav-info li.active > a {
  border-left-color: #00bcd4;
}
.epm-nav.expanded.left {
  left: 0;
}
.epm-nav.expanded.left > .epm-nav-host {
  left: 257px;
}
.epm-nav.expanded.right {
  right: 0;
}
.epm-nav.expanded.right > .epm-nav-host {
  right: 234px;
}
.epm-nav .nav-search {
  margin: 0 2px 0 0;
}
.epm-nav .nav-search button.clear {
  border: none;
  background-color: transparent;
  margin: 0 0 0 -25px;
  padding: 0;
  color: #ddd;
}
.epm-nav .nav-search input[type="search"] {
  border: solid 1px #2371f2;
  background-color: #4285f4;
  width: 100%;
  color: #ffffff;
  padding: 2px 15px 2px 4px;
  -moz-transition: none linear 300ms;
  -o-transition: none linear 300ms;
  -webkit-transition: none linear 300ms;
  transition: none linear 300ms;
  margin: 0;
}
.epm-nav .nav-search input[type="search"]::-moz-placeholder {
  color: #dddddd;
}
.epm-nav .nav-search input[type="search"]:-ms-input-placeholder {
  color: #dddddd;
}
.epm-nav .nav-search input[type="search"]::-webkit-input-placeholder {
  color: #dddddd;
}
.epm-nav .nav-search input[type="search"]:hover,
.epm-nav .nav-search input[type="search"]:focus,
.epm-nav .nav-search input[type="search"]:focus:valid,
.epm-nav .nav-search input[type="search"]:focus:invalid {
  border-color: #669cf6;
  -webkit-box-shadow: none 0 1px #000000;
  -moz-box-shadow: none 0 1px #000000;
  box-shadow: none 0 1px #000000;
}
.epm-nav li {
  -moz-transition: height linear 300ms;
  -o-transition: height linear 300ms;
  -webkit-transition: height linear 300ms;
  transition: height linear 300ms;
}
.epm-nav li > a {
  padding: 5px;
  white-space: nowrap;
  color: #ddd;
}
.epm-nav li > a:focus,
.epm-nav li > a:hover,
.epm-nav li > a:active {
  background-color: #669cf6;
  border-left-color: #669cf6;
  border-right-color: #669cf6;
  color: #fff;
}
.epm-nav li.divider {
  height: 1px;
  line-height: 1px;
  font-size: 0;
  border-top: solid 1px #2371f2;
  margin: 2px 0 2px 0;
}
/*# sourceMappingURL=endpointmvc.css.map */

<|start_filename|>Managed.AndroidDebugBridge/PackageManager.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class PackageManager {
		private const String PM_LIST_FULL = "pm list packages -f";
		/// <summary>
		/// Initializes a new instance of the <see cref="PackageManager"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public PackageManager ( Device device ) {
			Device = device;
			Packages = new Dictionary<string, FileEntry> ( );
		}

		/// <summary>
		/// Gets or sets the packages.
		/// </summary>
		/// <value>
		/// The packages.
		/// </value>
		public Dictionary<String,FileEntry> Packages { get; set; }

		/// <summary>
		/// Refreshes the packages.
		/// </summary>
		public void RefreshPackages ( ) {
			if ( this.Device.IsOffline ) {
				throw new IOException ( "Device is offline" );
			}

			PackageManagerReceiver pmr = new PackageManagerReceiver ( this.Device, this );
			this.Device.ExecuteShellCommand ( PM_LIST_FULL, pmr );

		}

		/// <summary>
		/// Existses the specified package.
		/// </summary>
		/// <param name="package">The package.</param>
		/// <returns></returns>
		public bool Exists ( String package ) {
			try {
				return GetApkFileEntry ( package ) != null;
			} catch ( FileNotFoundException) {
				return false;
			}
		}

		/// <summary>
		/// Gets the apk file entry.
		/// </summary>
		/// <param name="package">The package.</param>
		/// <returns></returns>
		public FileEntry GetApkFileEntry ( String package ) {
			return FileEntry.Find ( this.Device, GetApkPath ( package ) );
		}

		/// <summary>
		/// Gets the apk path.
		/// </summary>
		/// <param name="package">The package.</param>
		/// <returns></returns>
		public String GetApkPath ( String package ) {

			if ( this.Device.IsOffline ) {
				throw new IOException ( "Device is offline" );
			}

			PackageManagerPathReceiver receiver = new PackageManagerPathReceiver();
			this.Device.ExecuteShellCommand ( "pm path {0}", receiver, package );
			if ( !String.IsNullOrEmpty ( receiver.Path ) ) {
				return receiver.Path;
			} else {
				throw new FileNotFoundException ( String.Format ( "The package '{0}' is not installed on the device: {1}", package, Device.SerialNumber ) );
			}

		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		private Device Device { get; set; }

		/// <summary>
		/// 
		/// </summary>
		private class PackageManagerPathReceiver : MultiLineReceiver {
			/// <summary>
			/// Pattern to parse the output of the 'pm path &lt;package&gt;' command.
			/// The output format looks like:
			/// /data/app/myapp.apk=com.mypackage.myapp
			/// </summary>
			public const String PM_PATH_PATTERN = "^package:(.+?)$";

			/// <summary>
			/// Initializes a new instance of the <see cref="PackageManagerPathReceiver"/> class.
			/// </summary>
			public PackageManagerPathReceiver ( ) {
				Path = null;
			}

			/// <summary>
			/// Gets or sets the path.
			/// </summary>
			/// <value>
			/// The path.
			/// </value>
			public String Path { get; private set; }

			/// <summary>
			/// Processes the new lines.
			/// </summary>
			/// <param name="lines">The lines.</param>
			protected override void ProcessNewLines ( string[] lines ) {
				foreach ( String line in lines ) {
					if ( !String.IsNullOrEmpty ( line ) && !line.StartsWith ( "#" ) ) {
						// get the filepath and package from the line
						Match m = Regex.Match ( line, PM_PATH_PATTERN, RegexOptions.Compiled );
						if ( m.Success ) {
							Path = m.Groups[1].Value;
						}
					}
				}
			}
		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForManagedAdbExtenstions/Swap32bitsToArray.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForManagedAdbExtenstions {
	public class Swap32bitsToArray {
		[Fact]
		public void WhenValueIsPositive_ShouldReturnSwapped() {
			var fixture = new Fixture ( );
			var value = fixture.Create<int> ( );
			var offset = fixture.Create<int> ( );
			var dest = new byte[offset + 4];
			Assert.True ( offset >= 0 );

			ManagedAdbExtenstions.Swap32bitsToArray ( value, dest, offset );
			Assert.True ( dest.Length == offset + 4 );
			Assert.True ( dest[offset] == (byte)( value & 0x000000FF ) );
			Assert.True ( dest[offset + 1] == (byte)( value & 0x0000FF00 ) >> 8 );
			Assert.True ( dest[offset + 2] == (byte)( value & 0x00FF0000 ) >> 16 );
			Assert.True ( dest[offset + 3] == (byte)( value & 0xFF000000 ) >> 24 );
		}

		[Fact]
		public void WhenValueIsZero_ShouldReturnSwapped ( ) {
			var fixture = new Fixture ( );
			var value = 0;
			var offset = fixture.Create<int> ( );
			var dest = new byte[offset + 4];
			Assert.True ( offset >= 0 );

			ManagedAdbExtenstions.Swap32bitsToArray ( value, dest, offset );
			Assert.True ( dest.Length == offset + 4 );
			Assert.True ( dest[offset] == (byte)( value & 0x000000FF ) );
			Assert.True ( dest[offset + 1] == (byte)( value & 0x0000FF00 ) >> 8 );
			Assert.True ( dest[offset + 2] == (byte)( value & 0x00FF0000 ) >> 16 );
			Assert.True ( dest[offset + 3] == (byte)( value & 0xFF000000 ) >> 24 );
		}
		
	}
}


<|start_filename|>Madb.Site/Models/Documentation/Xml/Gist.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	public class Gist {
		[XmlAttribute("id")]
		public string Id { get; set; }
		[XmlText]
		public string Description { get; set; }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/FilePermission.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class FilePermissions {

		/// <summary>
		/// Initializes a new instance of the <see cref="FilePermissions"/> class.
		/// </summary>
		public FilePermissions ( ) : this("---------") {
			
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FilePermissions"/> class.
		/// </summary>
		/// <param name="permissions">The permissions.</param>
		/// <exception cref="System.ArgumentException"></exception>
		public FilePermissions ( String permissions ) {
			if ( permissions.Length > 9 ) {
				permissions = permissions.Substring ( 1,9 );
			}

			if ( permissions.Length < 9 ) {
				throw new ArgumentException ( String.Format("Invalid permissions string: {0}",permissions) );
			}

			User = new FilePermission ( permissions.Substring ( 0, 3 ) );
			Group = new FilePermission ( permissions.Substring ( 3, 3 ) );
			Other = new FilePermission ( permissions.Substring ( 6, 3 ) );
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FilePermissions"/> class.
		/// </summary>
		/// <param name="user">The user.</param>
		/// <param name="group">The group.</param>
		/// <param name="other">The other.</param>
		public FilePermissions ( FilePermission user, FilePermission group, FilePermission other ) {
			User = user;
			Group = group;
			Other = other;
		}

		/// <summary>
		/// Gets or sets the user permission.
		/// </summary>
		/// <value>
		/// The user.
		/// </value>
		public FilePermission User { get; set; }
		/// <summary>
		/// Gets or sets the group permission.
		/// </summary>
		/// <value>
		/// The group.
		/// </value>
		public FilePermission Group { get; set; }
		/// <summary>
		/// Gets or sets the other permission.
		/// </summary>
		/// <value>
		/// The other.
		/// </value>
		public FilePermission Other { get; set; }


		/// <summary>
		/// Returns a <see cref="System.String" /> that represents this instance.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String" /> that represents this instance.
		/// </returns>
		public override string ToString ( ) {
			return String.Format ( "{0}{1}{2}", User.ToString ( ), Group.ToString ( ), Other.ToString ( ) );
		}

		/// <summary>
		/// Converts to string that can be used in a chmod command.
		/// </summary>
		/// <returns></returns>
		public String ToChmod ( ) {
			return String.Format ( "{0}{1}{2}", (int)User.ToChmod ( ), (int)Group.ToChmod ( ), (int)Other.ToChmod ( ) );
		}
	}

	/// <summary>
	/// 
	/// </summary>
	public class FilePermission {

		/// <summary>
		/// 
		/// </summary>
		[Flags]
		public enum Modes {
			/// <summary>
			/// 
			/// </summary>
			NoAccess = 0,
			/// <summary>
			/// 
			/// </summary>
			Execute = 1,
			/// <summary>
			/// 
			/// </summary>
			Write = 2,
			/// <summary>
			/// 
			/// </summary>
			Read = 4
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FilePermission"/> class.
		/// </summary>
		public FilePermission ( )
			: this ( "---" ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="FilePermission"/> class.
		/// </summary>
		/// <param name="linuxPermissions">The linux permissions.</param>
		public FilePermission ( string linuxPermissions ) {
			this.CanRead = string.Compare ( linuxPermissions.Substring ( 0, 1 ), "r", false ) == 0;
			this.CanWrite = string.Compare ( linuxPermissions.Substring ( 1, 1 ), "w", false ) == 0;
			this.CanExecute = string.Compare ( linuxPermissions.Substring ( 2, 1 ), "x", false ) == 0 || string.Compare ( linuxPermissions.Substring ( 2, 1 ), "t", false ) == 0;
			this.CanDelete = this.CanWrite && string.Compare ( linuxPermissions.Substring ( 2, 1 ), "t", false ) != 0;
		}

		/// <summary>
		/// Gets or sets a value indicating whether this instance can execute.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance can execute; otherwise, <c>false</c>.
		/// </value>
		public bool CanExecute { get; private set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance can write.
		/// </summary>
		/// <value><c>true</c> if this instance can write; otherwise, <c>false</c>.</value>
		public bool CanWrite { get; private set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance can read.
		/// </summary>
		/// <value><c>true</c> if this instance can read; otherwise, <c>false</c>.</value>
		public bool CanRead { get; private set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance can delete.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance can delete; otherwise, <c>false</c>.
		/// </value>
		public bool CanDelete { get; private set; }

		/// <summary>
		/// Returns a string that represents the current object.
		/// </summary>
		/// <returns>
		/// A string that represents the current object.
		/// </returns>
		public override string ToString ( ) {
			StringBuilder perm = new StringBuilder ( );
			return perm.AppendFormat ( "{0}", CanRead ? "r" : "-" ).AppendFormat ( "{0}", CanWrite ? "w" : "-" ).AppendFormat ( "{0}", CanExecute ? CanDelete ? "x" : "t" : "-" ).ToString ( );
		}

		/// <summary>
		/// Converts the permissions to bit value that can be casted to an integer and used for calling chmod
		/// </summary>
		/// <returns></returns>
		public Modes ToChmod ( ) {
			Modes val = Modes.NoAccess;
			if ( CanRead ) {
				val |= Modes.Read;
			}

			if ( CanWrite ) {
				val |= Modes.Write;
			}

			if ( CanExecute ) {
				val |= Modes.Execute;
			}
			int ival = (int)val;
			return val;
		}

	}
}


<|start_filename|>Managed.AndroidDebugBridge/FileSystem.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Managed.Adb.IO;
using MoreLinq;
using System.Text.RegularExpressions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class FileSystem {

		/// <summary>
		/// Initializes a new instance of the <see cref="FileSystem"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public FileSystem ( Device device ) {
			Device = device;
		}

		/// <summary>
		/// Creates the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public FileEntry Create ( String path ) {
			Device.ThrowIfNull ( "Device" );

			path.ThrowIfNullOrWhiteSpace ( "path" );

			if ( !Device.IsOffline ) {
				if ( Exists ( path ) ) {
					throw new ArgumentException ( "The specified path already exists." );
				} else {
					var cer = new CommandErrorReceiver ( );
					var escaped = LinuxPath.Escape ( path );
					// use native touch command if its available.
					var cmd = Device.BusyBox.Available ? "touch" : ">";
					var command = String.Format ( "{0} {1}", cmd, escaped );
					if ( Device.CanSU ( ) ) {
						Device.ExecuteRootShellCommand ( command, cer );
					} else {
						Device.ExecuteShellCommand ( command, cer );
					}
					if ( !String.IsNullOrEmpty ( cer.ErrorMessage ) ) {
						throw new IOException ( String.Format ( "Error creating file: {0}", cer.ErrorMessage ) );
					} else {
						// at this point, the newly created file should exist.
						return Device.FileListingService.FindFileEntry ( path );
					}
				}
			} else {
				throw new IOException ( "Device is not online" );
			}
		}

		/// <summary>
		/// Creates the specified file entry.
		/// </summary>
		/// <param name="fileEntry">The file entry.</param>
		/// <returns></returns>
		public FileEntry Create ( FileEntry fileEntry ) {
			if ( fileEntry.IsDirectory ) {
				MakeDirectory ( fileEntry.FullPath );
				return Device.FileListingService.FindFileEntry ( fileEntry.FullPath );
			} else {
				return Create ( fileEntry.FullPath );
			}
		}

		/// <summary>
		/// Gets if the specified path exists on the device.
		/// </summary>
		/// <param name="path">the path to check</param>
		/// <returns><c>true</c>, if the path exists; otherwise, <c>false</c></returns>
		/// <exception cref="IOException">If the device is not connected.</exception>
		/// <exception cref="ArgumentNullException">If the device or path is null.</exception>
		public bool Exists ( String path ) {
			Device.ThrowIfNull ( "Device" );
			path.ThrowIfNullOrWhiteSpace ( "path" );

			if ( !Device.IsOffline ) {
				try {
					FileEntry fe = Device.FileListingService.FindFileEntry ( path );
					return fe != null;
				} catch ( FileNotFoundException ) {
					return false;
				}
			} else {
				throw new IOException ( "Device is not online" );
			}
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		private Device Device { get; set; }

		/// <summary>
		/// Makes the directory from the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		public void MakeDirectory ( String path ) {
			MakeDirectory ( path, false );
		}

		/// <summary>
		/// Makes the directory.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="forceDeviceMethod">if set to <c>true</c> forces the use of the "non-busybox" method.</param>
		public void MakeDirectory ( String path, bool forceDeviceMethod ) {
			Device.ThrowIfNull ( "Device" );
			path.ThrowIfNullOrWhiteSpace ( "path" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			try {
				//var fileEntry = FileEntry.FindOrCreate ( Device, path );
				// if we have busybox we can use the mkdir in there as it supports --parents
				if ( Device.BusyBox.Available && !forceDeviceMethod ) {
					try {
						Device.BusyBox.ExecuteShellCommand ( "mkdir -p {0}", cer, path );
					} catch {
						try {
							// if there was an error, then fallback too.
							MakeDirectoryFallbackInternal ( path, cer );
						} catch { }
					}
				} else {
					// if busybox is not available then we have to fallback
					MakeDirectoryFallbackInternal ( path, cer );
				}
			} catch {

			}
			if ( !String.IsNullOrEmpty ( cer.ErrorMessage ) ) {
				throw new IOException ( cer.ErrorMessage );
			}
		}

		/// <summary>
		/// this is a fallback if the mkdir -p fails for somereason
		/// </summary>
		/// <param name="path"></param>
		/// <param name="cer"></param>
		internal void MakeDirectoryFallbackInternal ( String path, CommandErrorReceiver cer ) {
			Device.ExecuteShellCommand ( "mkdir {0}", cer, path );
		}

		/// <summary>
		/// Copies the specified source to the specified destination.
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="destination">The destination.</param>
		public void Copy ( String source, String destination ) {
			Device.ThrowIfNull ( "Device" );
			source.ThrowIfNullOrWhiteSpace ( "source" );
			destination.ThrowIfNullOrWhiteSpace ( "destination" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			FileEntry sfe = Device.FileListingService.FindFileEntry ( source );

			Device.ExecuteShellCommand ( "cat {0} > {1}", cer, sfe.FullEscapedPath, destination );
			if ( !String.IsNullOrEmpty ( cer.ErrorMessage ) ) {
				throw new IOException ( cer.ErrorMessage );
			}
		}

		/// <summary>
		/// Moves the specified source to the specified destination.
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="destination">The destination.</param>
		public void Move ( String source, String destination ) {
			Device.ThrowIfNull ( "Device" );
			source.ThrowIfNullOrWhiteSpace ( "source" );
			destination.ThrowIfNullOrWhiteSpace ( "destination" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			FileEntry sfe = Device.FileListingService.FindFileEntry ( source );

			Device.ExecuteShellCommand ( "mv {0} {1}", cer, sfe.FullEscapedPath, destination );
			if ( !String.IsNullOrEmpty ( cer.ErrorMessage ) ) {
				throw new IOException ( cer.ErrorMessage );
			}
		}

		/// <summary>
		/// Chmods the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="permissions">The permissions.</param>
		public void Chmod ( String path, String permissions ) {
			Device.ThrowIfNull ( "Device" );
			path.ThrowIfNullOrWhiteSpace ( "path" );
			permissions.ThrowIfNullOrWhiteSpace ( "permissions" );

			FileEntry entry = Device.FileListingService.FindFileEntry ( path );
			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			Device.ExecuteShellCommand ( "chmod {0} {1}", cer, permissions, entry.FullEscapedPath );
		}

		/// <summary>
		/// Chmods the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="permissions">The permissions.</param>
		public void Chmod ( String path, FilePermissions permissions ) {
			Device.ThrowIfNull ( "Device" );
			path.ThrowIfNullOrWhiteSpace ( "path" );
			permissions.ThrowIfNull ( "permissions" );

			FileEntry entry = Device.FileListingService.FindFileEntry ( path );
			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			Device.ExecuteShellCommand ( "chmod {0} {1}", cer, permissions.ToChmod ( ), entry.FullEscapedPath );
		}

		/// <summary>
		/// Gets if the specified mount point is read-only
		/// </summary>
		/// <param name="mount"></param>
		/// <returns><code>true</code>, if read-only; otherwise, <code>false</code></returns>
		/// <exception cref="IOException">If mount point doesnt exist</exception>
		public bool IsMountPointReadOnly ( String mount ) {
			Device.ThrowIfNull ( "Device" );
			mount.ThrowIfNullOrWhiteSpace ( mount );

			if ( !Device.MountPoints.ContainsKey ( mount ) ) {
				throw new IOException ( "Invalid mount point" );
			}

			return Device.MountPoints[mount].IsReadOnly;
		}

		/// <summary>
		/// Deletes the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <exception cref="System.ArgumentNullException">
		/// If device is null
		/// or
		/// If path is null or empty.
		/// </exception>
		/// <gist id="adee6a11c5441da61af8" />
		/// <exception cref="System.IO.IOException">If the command fails.</exception>
		public void Delete(String path) {
			Device.ThrowIfNull ( "Device" );
			path.ThrowIfNullOrWhiteSpace ( "path" );
			FileEntry entry = Device.FileListingService.FindFileEntry ( path );

			Delete ( entry );
		}

		/// <summary>
		/// Deletes the specified path.
		/// </summary>
		/// <param name="fileEntry">The file entry.</param>
		/// <exception cref="System.IO.IOException">If the command fails.</exception>
		/// <exception cref="System.ArgumentNullException">If device is null or if path is null or empty.</exception>

		public void Delete ( FileEntry fileEntry ) {
			Device.ThrowIfNull("Device");
			fileEntry.ThrowIfNull ( "fileEntry" );
			if ( fileEntry.Exists ) {
				CommandErrorReceiver cer = new CommandErrorReceiver ( );
				Device.ExecuteShellCommand ( "rm -f {0} {1}", cer, fileEntry.IsDirectory ? "-r" : String.Empty, fileEntry.FullResolvedPath );

				if ( !String.IsNullOrEmpty ( cer.ErrorMessage ) ) {
					throw new IOException ( cer.ErrorMessage );
				}
			}
		}

		/// <summary>
		/// Gets the dev blocks for the device.
		/// </summary>
		/// <exception cref="System.IO.FileNotFoundException">Throws if unable to locate /dev/block </exception>
		public IEnumerable<FileEntry> DeviceBlocks {
			get {
				Device.ThrowIfNull ( "Device" );

				var blocks = FileEntry.Find ( Device, "/dev/block/" );
				blocks.Children = Device.FileListingService.GetChildren ( blocks, true, null ).ToList ( );
				return blocks.Children.Where ( b => b.Type == FileListingService.FileTypes.Block );
			}
		}

		/// <summary>
		/// Mounts the specified device.
		/// </summary>
		/// <param name="mountPoint">The mp.</param>
		/// <param name="options">The options.</param>
		public void Mount ( MountPoint mountPoint, String options ) {
			mountPoint.ThrowIfNull ( "mountPoint" );
			Device.ThrowIfNull ( "Device" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			if ( Device.BusyBox.Available ) {
				Device.ExecuteShellCommand ( "busybox mount {0} {4} -t {1} {2} {3}", cer, mountPoint.IsReadOnly ? "-r" : "-w",
					mountPoint.FileSystem, mountPoint.Block, mountPoint.Name,
					!String.IsNullOrEmpty ( options ) ? String.Format ( "-o {0}", options ) : String.Empty );
			} else {
				Device.ExecuteShellCommand ( "mount {0} {4} -t {1} {2} {3}", cer, mountPoint.IsReadOnly ? "-r" : "-w",
					mountPoint.FileSystem, mountPoint.Block, mountPoint.Name,
					!String.IsNullOrEmpty ( options ) ? String.Format ( "-o {0}", options ) : String.Empty );
			}
		}

		/// <summary>
		/// Attempts to mount the mount point to the associated device without knowing the device or the type.
		/// Some devices may not support this method.
		/// </summary>
		/// <param name="mountPoint"></param>
		public void Mount ( String mountPoint ) {
			mountPoint.ThrowIfNull ( "mountPoint" );
			Device.ThrowIfNull ( "Device" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			if ( Device.BusyBox.Available ) {
				Device.ExecuteShellCommand ( "busybox mount {0}", cer, mountPoint );
			} else {
				Device.ExecuteShellCommand ( "mount {0}", cer, mountPoint );
			}
		}

		/// <summary>
		/// Mounts the specified mount point.
		/// </summary>
		/// <param name="mountPoint">The mountPoint.</param>
		public void Mount ( MountPoint mountPoint ) {
			Mount ( mountPoint, String.Empty );
		}

		/// <summary>
		/// Mounts the specified devices to the specified directory.
		/// </summary>
		/// <param name="directory">The directory.</param>
		/// <param name="device">The device.</param>
		/// <param name="fileSytemType">Type of the file sytem.</param>
		/// <param name="isReadOnly">if set to <c>true</c> is read only.</param>
		/// <param name="options">The options.</param>
		public void Mount ( String directory, String device, String fileSytemType, bool isReadOnly, String options ) {
			Mount ( new MountPoint ( device, directory, fileSytemType, isReadOnly ), options );
		}

		/// <summary>
		/// Mounts the specified devices to the specified directory.
		/// </summary>
		/// <param name="directory">The directory.</param>
		/// <param name="device">The device.</param>
		/// <param name="fileSytemType">Type of the file sytem.</param>
		/// <param name="isReadOnly">if set to <c>true</c> is read only.</param>
		public void Mount ( String directory, String device, String fileSytemType, bool isReadOnly ) {
			Mount ( new MountPoint ( device, directory, fileSytemType, isReadOnly ), String.Empty );
		}

		/// <summary>
		/// Unmounts the specified mount point.
		/// </summary>
		/// <param name="mountPoint">The mountPoint.</param>
		public void Unmount ( MountPoint mountPoint ) {
			Unmount ( mountPoint, String.Empty );
		}


		/// <summary>
		/// Unmounts the specified mount point.
		/// </summary>
		/// <param name="mountPoint">The mountPoint.</param>
		/// <param name="options">The options.</param>
		public void Unmount ( MountPoint mountPoint, String options ) {
			mountPoint.ThrowIfNull ( "mountPoint" );

			Unmount ( mountPoint.Name, options );
		}

		/// <summary>
		/// Unmounts the specified mount point.
		/// </summary>
		/// <param name="mountPoint">The mount point.</param>
		public void Unmount ( String mountPoint ) {
			Unmount ( mountPoint, String.Empty );
		}

		/// <summary>
		/// Unmounts the specified mount point.
		/// </summary>
		/// <param name="mountPoint">The mount point.</param>
		/// <param name="options">The options.</param>
		public void Unmount ( String mountPoint, String options ) {
			mountPoint.ThrowIfNull ( "mountPoint" );
			Device.ThrowIfNull ( "Device" );

			CommandErrorReceiver cer = new CommandErrorReceiver ( );
			if ( Device.BusyBox.Available ) {
				Device.ExecuteShellCommand ( "busybox umount {1} {0}", cer, !String.IsNullOrEmpty ( options ) ? String.Format ( "-o {0}", options ) : String.Empty, mountPoint );
			} else {
				Device.ExecuteShellCommand ( "umount {1} {0}", cer, !String.IsNullOrEmpty ( options ) ? String.Format ( "-o {0}", options ) : String.Empty, mountPoint );
			}
		}

		/// <summary>
		/// Resolves the link to the true path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		/// <workitem id="19712">Uses "ls -l" to resolve links</workitem>
		public String ResolveLink ( String path ) {
			if ( this.Device.BusyBox.Available ) {
				var cresult = new CommandResultReceiver ( );
				this.Device.BusyBox.ExecuteShellCommand ( "readlink -f {0}", cresult, path );
				// if cresult is empty, return the path
				return ( cresult == null || String.IsNullOrEmpty ( cresult.Result ) ) ? path : cresult.Result;
			} else {
				try {
					// have to try 2 ways because why the hell would it just work...
					var cresult = new CommandResultReceiver ( );
					this.Device.ExecuteShellCommand ( "readlink -f {0}", cresult, path );
					if(string.IsNullOrWhiteSpace(cresult.Result)) {
						cresult = new CommandResultReceiver ( );
						this.Device.ExecuteShellCommand ( "readlink {0}", cresult, path );
						return ( string.IsNullOrWhiteSpace ( cresult.Result ) ) ? path : cresult.Result;
					}
					return cresult.Result;
				} catch ( Exception ) {
					// if the command doesn't exist then we just return the path.
				}
				return path;
			}
		}

	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/AdbCommandRejectedException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Exceptions {

	/// <summary>
	/// Exception thrown when adb refuses a command.
	/// </summary>
	public class AdbCommandRejectedException : AdbException {
		/// <summary>
		/// Initializes a new instance of the <see cref="AdbCommandRejectedException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		public AdbCommandRejectedException ( String message )
			: base ( message ) {
			IsDeviceOffline = message.Equals ( "device offline" );
			WasErrorDuringDeviceSelection = false;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="AdbCommandRejectedException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="errorDuringDeviceSelection">if set to <c>true</c> [error during device selection].</param>
		public AdbCommandRejectedException ( String message, bool errorDuringDeviceSelection )
			: base ( message ) {
			WasErrorDuringDeviceSelection = errorDuringDeviceSelection;
			IsDeviceOffline = message.Equals ( "device offline" );
		}
		/// <summary>
		/// Gets a value indicating whether this instance is device offline.
		/// </summary>
		/// <value>
		/// <c>true</c> if this instance is device offline; otherwise, <c>false</c>.
		/// </value>
		public bool IsDeviceOffline { get; private set; }
		/// <summary>
		/// Gets a value indicating whether [was error during device selection].
		/// </summary>
		/// <value>
		/// <c>true</c> if [was error during device selection]; otherwise, <c>false</c>.
		/// </value>
		public bool WasErrorDuringDeviceSelection { get; private set; }
	}
}


<|start_filename|>Madb.Site/assets/Scripts/endpointmvc.js<|end_filename|>
﻿(function ($, mouseTrap) {
	"use strict";
	$(function () {

		$(".root.container").each(function (idx, item) {
			var self = $(item);
			var nav = $(".epm-nav");			
			if (!nav.hasClass("left") && !nav.hasClass("right")) {
				throw new Error("Navigation is not setup correctly. Missing direction");
			}
			var isLeft = nav.hasClass("left");

			// init the root container
			self.addClass(isLeft ? "left" : "right");
		});

		// wire up the popovers
		$("[data-toggle='popover']").each(function () {
			var self = $(this);
			if (self.data("popover-setup")) {
				return;
			}
			self.data("popover-setup", true);
			self.popover();
		});

		// toggle the open/close
		$(".epm-nav-toggle").on("click", function () {
			var self = $(this);
			var target = $(self.data("epm-target"));
			var toggle = self.data("epm-toggle");
			var collapsed = "collapsed";
			if (target.hasClass(toggle)) {
				target.removeClass(toggle).addClass(collapsed);
				self.parent().removeClass(toggle).addClass(collapsed);
				self.attr("title", "Open");

				// find root container
				$(".root.container").removeClass("epm-nav-expanded");
			} else {
				target.removeClass(collapsed).addClass(toggle);
				self.parent().removeClass(collapsed).addClass(toggle);
				// find root container
				$(".root.container").addClass("epm-nav-expanded");
				self.attr("title", "Close");
			}
			self.trigger("click.epm-mousetrap");
		});

		// filter the navigation with what is typed in the search field
		$(".epm-nav .nav-search input.search-field").on("keyup reset.epm-search", function (event) {
			var self = $(this);
			var $list = $(self).closest("ul.nav");
			var items = $("li", $list).not(".no-filter");
			var value = $(this).val();
			var $clear = $(".epm-nav .nav-search button.clear");
			$clear.trigger(value && value.length > 0 ? "show-clear.epm-search" : "hide-clear.epm-search");
			items.each(function () {
				var s = $(this);
				if (s.text().toLowerCase().search(value.toLowerCase()) > -1 || (!value || value.length == 0)) {
					s.removeClass("hidden");
				} else {
					s.addClass("hidden");
				}
			});
		});

		// this clears the search box and resets the navigation
		$(".epm-nav .nav-search button.clear").on("click", function (event) {
			$(".epm-nav .nav-search input.search-field").val("").trigger("reset.epm-search");
		}).on("show-clear.epm-search", function (event) {
			var $t = $(this);
			var clearTitle = $t.data("clear-title") || "Clear";
			var clearIcon = $t.data("clear-icon") || "fa-close";
			var searchIcon = $t.data("search-icon") || "fa-search";
			$t.removeClass(searchIcon).addClass(clearIcon).attr("title",clearTitle);
		}).on("hide-clear.epm-search", function (event) {
			var $t = $(this);
			var searchTitle = $t.data("search-title") || "Search";
			var clearIcon = $t.data("clear-icon") || "fa-close";
			var searchIcon = $t.data("search-icon") || "fa-search";
			$t.removeClass(clearIcon).addClass(searchIcon).attr("title", searchTitle);
		});

		// set up scrollspy on the body
		$("body").scrollspy({ target: ".epm-nav .nav", offset: 100 });

		// smooth scrolling if the jquery scrollTo plugin exists.
		$(".epm-nav .nav li a[data-scroll]").each(function () {
			var self = $(this);
			if (self.data("scroll-setup")) { return; }
			self.data("scroll-setup", true);
			var trigger = self.data("scroll") || "click";
			self.on(trigger, function (event) {
				if ($.scrollTo) {
					var $s = $(this);
					var topOffset = parseInt($s.data("scroll-offset"), 0);
					var target = $(this.hash);
					$.scrollTo(target, { duration: 1000, offset: topOffset });
					event.preventDefault();
				}
			});
		});



		// if you have mousetrap (http://craig.is/killing/mice) loaded, endpointMVC will bind some events
		if (mouseTrap) {
			// change the input to have the mouse bindings:
			var field = $(".epm-nav.expanded .nav-search input.search-field");
			var currentPH = field.attr("placeholder");
			field.attr("placeholder", currentPH + " (Ctrl+Q)");

			// change the title of open/close with ctrl+left/ctrl+right on the click trigger
			$(".epm-nav-toggle").on("click.epm-mousetrap", function () {
				$(".expanded.left .epm-nav-toggle").attr("title", "Close (Ctrl+Left)");
				$(".collapsed.right .epm-nav-toggle").attr("title", "Open (Ctrl+Left)");
				$(".collapsed.left .epm-nav-toggle").attr("title", "Open (Ctrl+Right)");
				$(".expanded.right .epm-nav-toggle").attr("title", "Close (Ctrl+Right)");
			}).trigger("click.epm-mousetrap");

			mouseTrap.bind("ctrl+q", function (e) {
				// bind ctrl+q to focus the search box
				$(".epm-nav.expanded .nav-search input.search-field").focus();
			}).bind("ctrl+left",function(e) {
				// bind ctrl+left and either open or close the navigation (depending on the location)
				$(".expanded.left .epm-nav-toggle").trigger("click").attr("title", "Open (Ctrl+Right)");
				$(".collapsed.right .epm-nav-toggle").trigger("click").attr("title", "Close (Ctrl+Right)");
			}).bind("ctrl+right", function (e) {
				// bind ctrl+right and either open or close the navigation (depending on the location)
				$(".expanded.right .epm-nav-toggle").trigger("click").attr("title", "Open (Ctrl+Left)");
				$(".collapsed.left .epm-nav-toggle").trigger("click").attr("title", "Close (Ctrl+Left)");
			});
		}
	});
})(window.jQuery, window.Mousetrap);

<|start_filename|>Madb.Site/App_Start/BundleConfig.cs<|end_filename|>
﻿using System.Web;
using System.Web.Optimization;
using Camalot.Common.Extensions;
using Camalot.Common.Mvc.Extensions;

namespace Madb.Site {
	public class BundleConfig {
		// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
		public static void RegisterBundles(BundleCollection bundles) {
			bundles.LoadFromWebConfiguration();
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Extensions/FileInfoHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {

		/// <summary>
		/// Determines whether the specified path is directory.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns>
		///   <c>true</c> if the specified path is directory; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsDirectory ( String path ) {
			return File.Exists ( path ) && ( File.GetAttributes ( path ) & FileAttributes.Directory ) == FileAttributes.Directory;
		}

		/// <summary>
		/// Determines whether the specified fsi is directory.
		/// </summary>
		/// <param name="fsi">The fsi.</param>
		/// <returns>
		///   <c>true</c> if the specified fsi is directory; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsDirectory ( this FileSystemInfo fsi ) {
			return (fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
		}

		/// <summary>
		/// Determines whether the specified path is file.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns>
		///   <c>true</c> if the specified path is file; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsFile ( String path ) {
			return File.Exists ( path ) && !IsDirectory ( path );
		}

		/// <summary>
		/// Determines whether the specified fsi is file.
		/// </summary>
		/// <param name="fsi">The fsi.</param>
		/// <returns>
		///   <c>true</c> if the specified fsi is file; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsFile ( this FileSystemInfo fsi ) {
			return fsi is FileInfo && !IsDirectory ( fsi.FullName );
		}

		/// <summary>
		/// Gets the file system info.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public static FileSystemInfo GetFileSystemInfo ( this String path ) {
			if ( IsDirectory ( path ) ) {
				return new DirectoryInfo ( path );
			} else {
				return new FileInfo ( path );
			}
		}

	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetFileName.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetFileName {

		[Fact]
		public void WhenPathContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.GetFileName ( "/some/path/{0}-{1}.ext".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "file-" ) ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );
		}

		[Fact]
		public void WhenPathIsNull_ShouldReturnNull ( ) {
			var fixture = new Fixture ( );
			var result = LinuxPath.GetFileName ( null );
			Assert.Null ( result );
		}

		[Fact]
		public void WhenPathIsDirectory_ShouldReturnEmpty ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1-" );
			var p2 = "{0}/".With ( fixture.Create ( "path2-" ) );
			var p = LinuxPath.Combine ( p1, p2 );
			var result = LinuxPath.GetFileName ( p );
			Assert.Equal ( string.Empty, result );
		}

		[Fact]
		public void WhenPathIsFileWithExtension_ShouldReturnFileWithExtension ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1-" );
			var p2 = "{0}/".With ( fixture.Create ( "path2-" ) );
			var f = "{0}{1}".With ( fixture.Create ( "file-" ), ".ext1" );
			var p = LinuxPath.Combine ( p1, p2, f );
			var result = LinuxPath.GetFileName ( p );
			Assert.Equal ( f, result );
		}

		[Fact]
		public void WhenPathIsFileWithoutExtension_ShouldReturnFileWithoutExtension ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1-" );
			var p2 = "{0}/".With ( fixture.Create ( "path2-" ) );
			var f = "{0}".With ( fixture.Create ( "file-" ) );
			var p = LinuxPath.Combine ( p1, p2, f );
			var result = LinuxPath.GetFileName ( p );
			Assert.Equal ( f, result );
		}
	}
}



<|start_filename|>Managed.AndroidDebugBridge/SyncService.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
using Managed.Adb.IO;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="System.IDisposable" />
	public class SyncService : IDisposable {
		private const String OKAY = "OKAY";
		private const String FAIL = "FAIL";
		private const String STAT = "STAT";
		private const String RECV = "RECV";
		private const String DATA = "DATA";
		private const String DONE = "DONE";
		private const String SEND = "SEND";
		private const String LIST = "LIST";
		private const String DENT = "DENT";
		private const string TAG = "sync";
		/// <summary>
		/// 
		/// </summary>
		[Flags]
		public enum FileMode {
			/// <summary>
			/// The unknown
			/// </summary>
			UNKNOWN = 0x0000, // unknown
			/// <summary>
			/// The socket
			/// </summary>
			Socket = 0xc000, // type: socket
			/// <summary>
			/// The symbolic link
			/// </summary>
			SymbolicLink = 0xa000, // type: symbolic link
			/// <summary>
			/// The regular
			/// </summary>
			Regular = 0x8000, // type: regular file
			/// <summary>
			/// The block
			/// </summary>
			Block = 0x6000, // type: block device
			/// <summary>
			/// The directory
			/// </summary>
			Directory = 0x4000, // type: directory
			/// <summary>
			/// The character
			/// </summary>
			Character = 0x2000, // type: character device
			/// <summary>
			/// The fifo
			/// </summary>
			FIFO = 0x1000  // type: fifo
		}

		/*private const int S_ISOCK = 0xc000; // type: symbolic link
		private const int S_IFLNK = 0xa000; // type: symbolic link
		private const int S_IFREG = 0x8000; // type: regular file
		private const int S_IFBLK = 0x6000; // type: block device
		private const int S_IFDIR = 0x4000; // type: directory
		private const int S_IFCHR = 0x2000; // type: character device
		private const int S_IFIFO = 0x1000; // type: fifo

		private const int S_ISUID = 0x0800; // set-uid bit
		private const int S_ISGID = 0x0400; // set-gid bit
		private const int S_ISVTX = 0x0200; // sticky bit
		private const int S_IRWXU = 0x01C0; // user permissions
		private const int S_IRUSR = 0x0100; // user: read;
		private const int S_IWUSR = 0x0080; // user: write;
		private const int S_IXUSR = 0x0040; // user: execute;
		private const int S_IRWXG = 0x0038; // group permissions
		private const int S_IRGRP = 0x0020; // group: read;
		private const int S_IWGRP = 0x0010; // group: write;
		private const int S_IXGRP = 0x0008; // group: execute;
		private const int S_IRWXO = 0x0007; // other permissions
		private const int S_IROTH = 0x0004; // other: read;
		private const int S_IWOTH = 0x0002; // other: write;
		private const int S_IXOTH = 0x0001; // other: execute;*/

		private const int SYNC_DATA_MAX = 64 * 1024;
		private const int REMOTE_PATH_MAX_LENGTH = 1024;

		/// <summary>
		/// Initializes the <see cref="SyncService"/> class.
		/// </summary>
		static SyncService ( ) {
			NullProgressMonitor = new NullSyncProgressMonitor ( );
		}

		/// <summary>
		/// Gets the null progress monitor.
		/// </summary>
		/// <value>
		/// The null progress monitor.
		/// </value>
		public static NullSyncProgressMonitor NullProgressMonitor { get; private set; }
		/// <summary>
		/// Gets or sets the data buffer.
		/// </summary>
		/// <value>
		/// The data buffer.
		/// </value>
		private static byte[] DataBuffer { get; set; }

		/// <summary>
		/// Checks the result array starts with the provided code
		/// </summary>
		/// <param name="result">The result array to check</param>
		/// <param name="code">The 4 byte code.</param>
		/// <returns>true if the code matches.</returns>
		private static bool CheckResult ( byte[] result, byte[] code ) {

			if ( result.Length >= code.Length ) {
				for ( int i = 0; i < code.Length; i++ ) {
					if ( result[i] != code[i] ) {
						return false;
					}
				}
				return true;
			}
			return false;
		}

		/// <summary>
		/// Gets the file type from the mode
		/// </summary>
		/// <param name="mode">the file mode flags</param>
		/// <returns></returns>
		private static FileListingService.FileTypes GetFileType ( FileMode mode ) {
			if ( ( mode & FileMode.Socket ) == FileMode.Socket ) {
				return FileListingService.FileTypes.Socket;
			}

			if ( ( mode & FileMode.SymbolicLink ) == FileMode.SymbolicLink ) {
				return FileListingService.FileTypes.Link;
			}

			if ( ( mode & FileMode.Regular ) == FileMode.Regular ) {
				return FileListingService.FileTypes.File;
			}

			if ( ( mode & FileMode.Block ) == FileMode.Block ) {
				return FileListingService.FileTypes.Block;
			}

			if ( ( mode & FileMode.Directory ) == FileMode.Directory ) {
				return FileListingService.FileTypes.Directory;
			}

			if ( ( mode & FileMode.Character ) == FileMode.Character ) {
				return FileListingService.FileTypes.Character;
			}

			if ( ( mode & FileMode.FIFO ) == FileMode.FIFO ) {
				return FileListingService.FileTypes.FIFO;
			}

			return FileListingService.FileTypes.Other;
		}



		/// <summary>
		/// Create a command with a code and an int values
		/// </summary>
		/// <param name="command">the 4 byte command (STAT, RECV, ...).</param>
		/// <param name="value"></param>
		/// <returns>the byte[] to send to the device through adb</returns>
		private static byte[] CreateRequest ( String command, int value ) {
			return CreateRequest ( Encoding.Default.GetBytes ( command ), value );
		}

		/// <summary>
		/// Create a command with a code and an int values
		/// </summary>
		/// <param name="command">the 4 byte command (STAT, RECV, ...).</param>
		/// <param name="value"></param>
		/// <returns>the byte[] to send to the device through adb</returns>
		private static byte[] CreateRequest ( byte[] command, int value ) {
			byte[] array = new byte[8];

			Array.Copy ( command, 0, array, 0, 4 );
			value.Swap32bitsToArray ( array, 4 );

			return array;
		}

		/// <summary>
		/// Creates the data array for a file request. This creates an array with a 4 byte command + the remote file name.
		/// </summary>
		/// <param name="command">the 4 byte command (STAT, RECV, ...).</param>
		/// <param name="path">The path, as a byte array, of the remote file on which to execute the command</param>
		/// <returns>the byte[] to send to the device through adb</returns>
		private static byte[] CreateFileRequest ( String command, String path ) {
			return CreateFileRequest ( Encoding.Default.GetBytes ( command ), Encoding.Default.GetBytes ( path ) );
		}

		/// <summary>
		/// Creates the data array for a file request. This creates an array with a 4 byte command + the remote file name.
		/// </summary>
		/// <param name="command">the 4 byte command (STAT, RECV, ...).</param>
		/// <param name="path">he path, as a byte array, of the remote file on which to execute the command</param>
		/// <returns>the byte[] to send to the device through adb</returns>
		private static byte[] CreateFileRequest ( byte[] command, byte[] path ) {
			byte[] array = new byte[8 + path.Length];

			Array.Copy ( command, 0, array, 0, 4 );
			path.Length.Swap32bitsToArray ( array, 4 );
			Array.Copy ( path, 0, array, 8, path.Length );

			return array;
		}

		/// <summary>
		/// Creates the send file request.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="path">The path.</param>
		/// <param name="mode">The mode.</param>
		/// <returns></returns>
		private static byte[] CreateSendFileRequest ( String command, String path, FileMode mode ) {
			return CreateSendFileRequest ( Encoding.Default.GetBytes ( command ), Encoding.Default.GetBytes ( path ), mode );
		}

		/// <summary>
		/// Creates the send file request.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="path">The path.</param>
		/// <param name="mode">The mode.</param>
		/// <returns></returns>
		private static byte[] CreateSendFileRequest ( byte[] command, byte[] path, FileMode mode ) {
			String modeString = String.Format ( ",{0}", ( (int)mode & 0777 ) );
			byte[] modeContent = null;
			try {
				modeContent = Encoding.Default.GetBytes ( modeString );
			} catch ( EncoderFallbackException ) {
				return null;
			}

			byte[] array = new byte[8 + path.Length + modeContent.Length];
			Array.Copy ( command, 0, array, 0, 4 );
			( path.Length + modeContent.Length ).Swap32bitsToArray ( array, 4 );
			Array.Copy ( path, 0, array, 8, path.Length );
			Array.Copy ( modeContent, 0, array, 8 + path.Length, modeContent.Length );

			return array;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="SyncService"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public SyncService ( Device device )
			: this ( AndroidDebugBridge.SocketAddress, device ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="SyncService"/> class.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		public SyncService ( IPEndPoint address, Device device ) {
			Address = address;
			Device = device;
			Open ( );
		}

		/// <summary>
		/// Gets the address.
		/// </summary>
		/// <value>
		/// The address.
		/// </value>
		public IPEndPoint Address { get; private set; }
		/// <summary>
		/// Gets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		public Device Device { get; private set; }
		/// <summary>
		/// Gets or sets the channel.
		/// </summary>
		/// <value>
		/// The channel.
		/// </value>
		private Socket Channel { get; set; }
		/// <summary>
		/// Gets a value indicating whether this instance is open.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance is open; otherwise, <c>false</c>.
		/// </value>
		public bool IsOpen {
			get {
				return Channel != null && Channel.Connected;
			}
		}

		/// <summary>
		/// Opens this connection.
		/// </summary>
		/// <returns></returns>
		public bool Open ( ) {
			if ( IsOpen ) {
				return true;
			}

			try {
				Channel = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
				Channel.Connect ( this.Address );
				Channel.Blocking = true;

				// target a specific device
				AdbHelper.Instance.SetDevice ( Channel, Device );

				byte[] request = AdbHelper.Instance.FormAdbRequest ( "sync:" );
				AdbHelper.Instance.Write ( Channel, request, -1, DdmPreferences.Timeout );

				AdbResponse resp = AdbHelper.Instance.ReadAdbResponse ( Channel, false /* readDiagString */);

				if ( !resp.IOSuccess || !resp.Okay ) {
					Log.w ( "ddms:syncservice", "Got timeout or unhappy response from ADB sync req: {0}", resp.Message );
					Channel.Close ( );
					Channel = null;
					return false;
				}
			} catch ( IOException ) {
				Close ( );
				throw;
			}

			return true;
		}

		/**
		 * Closes the connection.
		 */
		/// <summary>
		/// Closes this connection.
		/// </summary>
		public void Close ( ) {
			if ( Channel != null ) {
				try {
					Channel.Close ( );
				} catch ( IOException ) {
					
				}
				Channel = null;
			}
		}

		/// <summary>
		/// Pulls file(s) or folder(s).
		/// </summary>
		/// <param name="entries">the remote item(s) to pull</param>
		/// <param name="localPath">The local destination. If the entries count is &gt; 1 or if the unique entry is a
		/// folder, this should be a folder.</param>
		/// <param name="monitor">The progress monitor. Cannot be null.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		/// <gist id="c9ca09c0c0779d0a5fb8" />
		public SyncResult Pull ( IEnumerable<FileEntry> entries, String localPath, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}
			
			// first we check the destination is a directory and exists
			DirectoryInfo d = new DirectoryInfo ( localPath );
			if ( !d.Exists ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_NO_DIR_TARGET );
			}

			if ( !d.IsDirectory() ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_TARGET_IS_FILE );
			}

			// get a FileListingService object
			FileListingService fls = new FileListingService ( Device );

			// compute the number of file to move
			long total = GetTotalRemoteFileSize ( entries, fls );
			Log.d (TAG, "total transfer: {0}", total );

			// start the monitor
			monitor.Start ( total );

			SyncResult result = DoPull ( entries, localPath, fls, monitor );

			monitor.Stop ( );

			return result;
		}

		/// <summary>
		/// Pulls a single file.
		/// </summary>
		/// <param name="remote">remote the remote file</param>
		/// <param name="localFilename">The local destination.</param>
		/// <param name="monitor">The progress monitor. Cannot be null.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		/// <exception cref="ArgumentNullException">Throws if monitor is null</exception>
		/// <gist id="39fdc76b6f394b9bdf88" />
		public SyncResult PullFile ( FileEntry remote, String localFilename, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			long total = remote.Size;
			monitor.Start ( total );

			SyncResult result = DoPullFile ( remote.FullPath, localFilename, monitor );

			monitor.Stop ( );
			return result;
		}

		/// <summary>
		/// Pulls a single file.
		/// <para>Because this method just deals with a String for the remote file instead of FileEntry,
		/// the size of the file being pulled is unknown and the ISyncProgressMonitor will not properly
		/// show the progress</para>
		/// </summary>
		/// <param name="remoteFilepath">the full path to the remote file</param>
		/// <param name="localFilename">The local destination.</param>
		/// <param name="monitor">The progress monitor. Cannot be null.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		/// <exception cref="ArgumentNullException">Throws if monitor is null</exception>
		/// <gist id="9021e6c39ee20a6e122b" />
		public SyncResult PullFile ( String remoteFilepath, String localFilename, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			long totalWork = 0;
			try {
				FileListingService fls = new FileListingService ( this.Device );
				FileEntry remoteFileEntry = fls.FindFileEntry ( remoteFilepath );
				totalWork = remoteFileEntry.Size;
			} catch ( FileNotFoundException ffe ) {
				Log.w ( "ddms", ffe );
			}
			monitor.Start ( totalWork );

			SyncResult result = DoPullFile ( remoteFilepath, localFilename, monitor );

			monitor.Stop ( );
			return result;
		}

		/// <summary>
		/// Push several files.
		/// </summary>
		/// <param name="local">An array of local files to push</param>
		/// <param name="remote">the remote FileEntry representing a directory.</param>
		/// <param name="monitor">The progress monitor. Cannot be null.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">Monitor cannot be null</exception>
		/// <gist id="380b3c149499bf31e49d" />
		public SyncResult Push ( IEnumerable<String> local, FileEntry remote, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			if ( !remote.IsDirectory ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_REMOTE_IS_FILE );
			}

			// make a list of File from the list of String
			List<FileSystemInfo> files = new List<FileSystemInfo> ( );
			foreach ( String path in local ) {
				files.Add ( path.GetFileSystemInfo ( ) );
			}

			// get the total count of the bytes to transfer
			long total = GetTotalLocalFileSize ( files );

			monitor.Start ( total );
			SyncResult result = DoPush ( files, remote.FullPath, monitor );
			monitor.Stop ( );

			return result;
		}

		/// <summary>
		/// Push a single file.
		/// </summary>
		/// <param name="local">the local filepath.</param>
		/// <param name="remote">The remote filepath.</param>
		/// <param name="monitor">The progress monitor. Cannot be null.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		/// <exception cref="ArgumentNullException">Throws if monitor is null</exception>
		public SyncResult PushFile ( String local, String remote, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			FileInfo f = new FileInfo ( local );
			if ( !f.Exists ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_NO_LOCAL_FILE );
			}

			if ( f.IsDirectory ( ) ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_LOCAL_IS_DIRECTORY );
			}

			monitor.Start ( f.Length );
			SyncResult result = DoPushFile ( local, remote, monitor );
			monitor.Stop ( );

			return result;
		}

		/// <summary>
		/// Push a single file
		/// </summary>
		/// <param name="local">the local file to push</param>
		/// <param name="remotePath">the remote file (length max is 1024)</param>
		/// <param name="monitor">the monitor. The monitor must be started already.</param>
		/// <returns>
		/// a SyncResult object with a code and an optional message.
		/// </returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		/// <exception cref="ArgumentNullException">Throws if monitor is null</exception>
		private SyncResult DoPushFile ( string local, string remotePath, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			FileStream fs = null;
			byte[] msg;

			int timeOut = DdmPreferences.Timeout;
			Log.d (TAG, "Remote File: {0}", remotePath );
			try {
				byte[] remotePathContent = remotePath.GetBytes ( AdbHelper.DEFAULT_ENCODING );

				if ( remotePathContent.Length > REMOTE_PATH_MAX_LENGTH ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_REMOTE_PATH_LENGTH );
				}

				// this shouldn't happen but still...
				if ( !File.Exists ( local ) ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_NO_LOCAL_FILE );
				}

				// create the stream to read the file
				fs = new FileStream ( local, System.IO.FileMode.Open, FileAccess.Read );

				// create the header for the action
				msg = CreateSendFileRequest ( SEND.GetBytes ( ), remotePathContent, (FileMode)0644 );
			} catch ( EncoderFallbackException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_REMOTE_PATH_ENCODING, e );
			} catch ( FileNotFoundException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_FILE_READ_ERROR, e );
			}

			// and send it. We use a custom try/catch block to make the difference between
			// file and network IO exceptions.
			try {
				AdbHelper.Instance.Write ( Channel, msg, -1, timeOut );
			} catch ( IOException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR, e );
			}

			// create the buffer used to read.
			// we read max SYNC_DATA_MAX, but we need 2 4 bytes at the beginning.
			if ( DataBuffer == null ) {
				DataBuffer = new byte[SYNC_DATA_MAX + 8];
			}
			byte[] bDATA = DATA.GetBytes ( );
			Array.Copy ( bDATA, 0, DataBuffer, 0, bDATA.Length );

			// look while there is something to read
			while ( true ) {
				// check if we're canceled
				if ( monitor.IsCanceled ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
				}

				// read up to SYNC_DATA_MAX
				int readCount = 0;
				try {
					readCount = fs.Read ( DataBuffer, 8, SYNC_DATA_MAX );
				} catch ( IOException e ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_FILE_READ_ERROR, e );
				}

				if ( readCount == 0 ) {
					// we reached the end of the file
					break;
				}

				// now send the data to the device
				// first write the amount read
				readCount.Swap32bitsToArray(DataBuffer, 4);

				// now write it
				try {
					AdbHelper.Instance.Write ( Channel, DataBuffer, readCount + 8, timeOut );
				} catch ( IOException e ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR, e );
				}

				// and advance the monitor
				monitor.Advance ( readCount );
			}
			// close the local file
			try {
				fs.Close ( );
			} catch ( IOException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_FILE_READ_ERROR, e );
			}

			try {
				// create the DONE message
				long time = DateTime.Now.CurrentTimeMillis ( ) / 1000;
				msg = CreateRequest ( DONE, (int)time );

				// and send it.
				AdbHelper.Instance.Write ( Channel, msg, -1, timeOut );

				// read the result, in a byte array containing 2 ints
				// (id, size)
				byte[] result = new byte[8];
				AdbHelper.Instance.Read ( Channel, result, -1 /* full length */, timeOut );

				if ( !CheckResult ( result, OKAY.GetBytes ( ) ) ) {
					if ( CheckResult ( result, FAIL.GetBytes ( ) ) ) {
						// read some error message...
						int len = result.Swap32bitFromArray ( 4 );

						AdbHelper.Instance.Read ( Channel, DataBuffer, len, timeOut );

						// output the result?
						String message = DataBuffer.GetString ( 0, len );
						Log.e ( "ddms", "transfer error: " + message );
						return new SyncResult ( ErrorCodeHelper.RESULT_UNKNOWN_ERROR, message );
					}

					return new SyncResult ( ErrorCodeHelper.RESULT_UNKNOWN_ERROR );
				}
			} catch ( IOException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR, e );
			}

			// files pushed have no permissions...
			// lets check if we can get to the file...
			if(this.Device.FileSystem.Exists(remotePath)) {
				this.Device.FileSystem.Chmod(remotePath, "0666");
			}
			return new SyncResult ( ErrorCodeHelper.RESULT_OK );
		}

		/// <summary>
		/// Does the push.
		/// </summary>
		/// <param name="files">The files.</param>
		/// <param name="remotePath">The remote path.</param>
		/// <param name="monitor">The monitor.</param>
		/// <returns></returns>
		/// <exception cref="System.ArgumentNullException">monitor;Monitor cannot be null</exception>
		private SyncResult DoPush ( IEnumerable<FileSystemInfo> files, string remotePath, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			// check if we're canceled
			if ( monitor.IsCanceled ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
			}

			foreach ( FileSystemInfo f in files ) {
				// check if we're canceled
				if ( monitor.IsCanceled ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
				}
				// append the name of the directory/file to the remote path
				String dest = LinuxPath.Combine ( remotePath, f.Name );
				if ( f.Exists ) {
					if ( f.IsDirectory ( ) ) {
						DirectoryInfo fsiDir = f as DirectoryInfo;
						monitor.StartSubTask ( f.FullName, dest );
						SyncResult result = DoPush ( fsiDir.GetFileSystemInfos ( ), dest, monitor );

						if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
							return result;
						}

						monitor.Advance ( 1 );
					} else if ( f.IsFile ( ) ) {
						monitor.StartSubTask ( f.FullName, dest );
						SyncResult result = DoPushFile ( f.FullName, dest, monitor );
						if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
							return result;
						}
					}
				}
			}

			return new SyncResult ( ErrorCodeHelper.RESULT_OK );
		}

		/// <summary>
		/// Pulls a remote file
		/// </summary>
		/// <param name="remotePath">the remote file (length max is 1024)</param>
		/// <param name="localPath">the local destination</param>
		/// <param name="monitor">the monitor. The monitor must be started already.</param>
		/// <returns>a SyncResult object with a code and an optional message.</returns>
		/// <exception cref="ArgumentNullException">Throws if monitor is null</exception>
		private SyncResult DoPullFile ( string remotePath, string localPath, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}


			byte[] msg = null;
			byte[] pullResult = new byte[8];

			int timeOut = DdmPreferences.Timeout;

			try {
				byte[] remotePathContent = remotePath.GetBytes ( AdbHelper.DEFAULT_ENCODING );

				if ( remotePathContent.Length > REMOTE_PATH_MAX_LENGTH ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_REMOTE_PATH_LENGTH );
				}

				// create the full request message
				msg = CreateFileRequest ( RECV.GetBytes ( ), remotePathContent );

				// and send it.
				AdbHelper.Instance.Write ( Channel, msg, -1, timeOut );

				// read the result, in a byte array containing 2 ints
				// (id, size)
				AdbHelper.Instance.Read ( Channel, pullResult, -1, timeOut );

				// check we have the proper data back
				if ( CheckResult ( pullResult, DATA.GetBytes ( ) ) == false &&
								CheckResult ( pullResult, DONE.GetBytes ( ) ) == false ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR );
				}
			} catch ( EncoderFallbackException e ) {
				Log.e ( TAG, e );
				return new SyncResult ( ErrorCodeHelper.RESULT_REMOTE_PATH_ENCODING, e );
			} catch ( IOException e ) {
				Log.e ( TAG, e );
				return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR, e );
			}

			// access the destination file
			FileInfo f = new FileInfo ( localPath );

			// create the stream to write in the file. We use a new try/catch block to differentiate
			// between file and network io exceptions.
			FileStream fos = null;
			try {
				fos = new FileStream ( f.FullName,System.IO.FileMode.Create,FileAccess.Write );
			} catch ( FileNotFoundException e ) {
				return new SyncResult ( ErrorCodeHelper.RESULT_FILE_WRITE_ERROR, e );
			}

			// the buffer to read the data
			byte[] data = new byte[SYNC_DATA_MAX];
			using ( fos ) {
				// loop to get data until we're done.
				while ( true ) {
					// check if we're canceled
					if ( monitor.IsCanceled ) {
						return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
					}

					// if we're done, we stop the loop
					if ( CheckResult ( pullResult, DONE.GetBytes ( ) ) ) {
						break;
					}
					if ( CheckResult ( pullResult, DATA.GetBytes ( ) ) == false ) {
						// hmm there's an error
						return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR );
					}
					int length = pullResult.Swap32bitFromArray ( 4 );
					if ( length > SYNC_DATA_MAX ) {
						// buffer overrun!
						// error and exit
						return new SyncResult ( ErrorCodeHelper.RESULT_BUFFER_OVERRUN );
					}

					try {
						// now read the length we received
						AdbHelper.Instance.Read ( Channel, data, length, timeOut );

						// get the header for the next packet.
						AdbHelper.Instance.Read ( Channel, pullResult, -1, timeOut );
					} catch ( IOException e ) {
						Log.e ( TAG, e );
						return new SyncResult ( ErrorCodeHelper.RESULT_CONNECTION_ERROR, e );
					}
					// write the content in the file
					try {
						fos.Write ( data, 0, length );
					} catch ( IOException e ) {
						return new SyncResult ( ErrorCodeHelper.RESULT_FILE_WRITE_ERROR, e );
					}

					monitor.Advance ( length );
				}

				try {
					fos.Flush ( );
				} catch ( IOException e ) {
					Log.e (TAG, e );
					return new SyncResult ( ErrorCodeHelper.RESULT_FILE_WRITE_ERROR, e );
				}
			}
			return new SyncResult ( ErrorCodeHelper.RESULT_OK );
		}

		/// <summary>
		/// Does the pull.
		/// </summary>
		/// <param name="entries">The entries.</param>
		/// <param name="localPath">The local path.</param>
		/// <param name="fileListingService">The file listing service.</param>
		/// <param name="monitor">The monitor.</param>
		/// <returns></returns>
		/// <exception cref="System.ArgumentNullException">Throws if the ISyncProgressMonitor is null</exception>
		/// <exception cref="System.IO.IOException">Throws if unable to create a file or folder</exception>
		private SyncResult DoPull ( IEnumerable<FileEntry> entries, string localPath, FileListingService fileListingService, ISyncProgressMonitor monitor ) {
			if ( monitor == null ) {
				throw new ArgumentNullException ( "monitor", "Monitor cannot be null" );
			}

			// check if we're cancelled
			if ( monitor.IsCanceled ) {

				return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
			}

			// check if we need to create the local directory
			DirectoryInfo localDir = new DirectoryInfo ( localPath );
			if ( !localDir.Exists ) {
				localDir.Create ( );
			}

			foreach ( FileEntry e in entries ) {
				// check if we're canceled
				if ( monitor.IsCanceled ) {
					return new SyncResult ( ErrorCodeHelper.RESULT_CANCELED );
				}

				// the destination item (folder or file)


				String dest = Path.Combine ( localPath, e.Name );

				// get type (we only pull directory and files for now)
				FileListingService.FileTypes type = e.Type;
				if ( type == FileListingService.FileTypes.Directory ) {
					monitor.StartSubTask ( e.FullPath, dest );
					// then recursively call the content. Since we did a ls command
					// to get the number of files, we can use the cache
					FileEntry[] children = fileListingService.GetChildren ( e, true, null );
					SyncResult result = DoPull ( children, dest, fileListingService, monitor );
					if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
						return result;
					}
					monitor.Advance ( 1 );
				} else if ( type == FileListingService.FileTypes.File ) {
					monitor.StartSubTask ( e.FullPath, dest );
					SyncResult result = DoPullFile ( e.FullPath, dest, monitor );
					if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
						return result;
					}
				} else if ( type == FileListingService.FileTypes.Link ) {
					monitor.StartSubTask ( e.FullPath, dest );
					SyncResult result = DoPullFile ( e.FullResolvedPath, dest, monitor );
					if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
						return result;
					}
				} else {
					Log.d ( "ddms-sync", String.Format ( "unknown type to transfer: {0}", type ) );
				}
			}

			return new SyncResult ( ErrorCodeHelper.RESULT_OK );
		}

		/// <summary>
		/// compute the recursive file size of all the files in the list. Folder have a weight of 1.
		/// </summary>
		/// <param name="entries">The remote files</param>
		/// <param name="fls">The FileListingService</param>
		/// <returns>The total number of bytes of the specified remote files</returns>
		private long GetTotalRemoteFileSize ( IEnumerable<FileEntry> entries, FileListingService fls ) {
			long count = 0;
			foreach ( FileEntry e in entries ) {
				FileListingService.FileTypes type = e.Type;
				if ( type == FileListingService.FileTypes.Directory ) {
					// get the children
					IEnumerable<FileEntry> children = fls.GetChildren ( e, false, null );
					count += GetTotalRemoteFileSize ( children, fls ) + 1;
				} else if ( type == FileListingService.FileTypes.File ) {
					count += e.Size;
				}
			}

			return count;
		}

		/// <summary>
		/// compute the recursive file size of all the files in the list. Folders have a weight of 1.
		/// </summary>
		/// <param name="fsis">The fsis.</param>
		/// <returns>
		/// The total number of bytes
		/// </returns>
		/// <remarks>
		/// This does not check for circular links.
		/// </remarks>
		private long GetTotalLocalFileSize ( IEnumerable<FileSystemInfo> fsis ) {
			long count = 0;

			foreach ( FileSystemInfo fsi in fsis ) {
				if ( fsi.Exists ) {
					if ( fsi is DirectoryInfo ) {
						return GetTotalLocalFileSize ( ( fsi as DirectoryInfo ).GetFileSystemInfos ( ) ) + 1;
					} else if ( fsi is FileInfo ) {
						count += ( fsi as FileInfo ).Length;
					}
				}
			}

			return count;
		}

		/// <summary>
		/// Returns the mode of the remote file.
		/// </summary>
		/// <param name="path">the remote file</param>
		/// <returns>the mode if all went well; otherwise, FileMode.UNKNOWN</returns>
		private FileMode ReadMode ( String path ) {
			try {
				// create the stat request message.
				byte[] msg = CreateFileRequest ( STAT, path );

				AdbHelper.Instance.Write ( Channel, msg, -1 /* full length */, DdmPreferences.Timeout );

				// read the result, in a byte array containing 4 ints
				// (id, mode, size, time)
				byte[] statResult = new byte[16];
				AdbHelper.Instance.Read ( Channel, statResult, -1 /* full length */, DdmPreferences.Timeout );

				// check we have the proper data back
				if ( CheckResult ( statResult, Encoding.Default.GetBytes ( STAT ) ) == false ) {
					return FileMode.UNKNOWN;
				}

				// we return the mode (2nd int in the array)
				return (FileMode)statResult.Swap32bitFromArray ( 4 );
			} catch ( IOException e ) {
				Log.w ( "SyncService", e );
				return FileMode.UNKNOWN;
			}
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose ( ) {
			this.Close ( );
		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/CombineTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class CombineTests {
		[Fact]
		public void When2ArgsAndPath1IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( null, fixture.Create ( "path2" ) );
			} );
		}
		[Fact]
		public void When2ArgsAndPath2IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), null );
			} );
		}

		[Fact]
		public void When2ArgsAndPath1IsEmpty_ShouldReturnRelativePath2 ( ) {
			var fixture = new Fixture ( );
			var p2 = fixture.Create ( "path2-" );
			var result = LinuxPath.Combine ( string.Empty, p2 );
			Assert.Equal ( "./{0}/".With ( p2 ), result );
		}

		[Fact]
		public void When2ArgsAndPath1IsEmptyAndPath2IsRooted_ShouldReturnRootedPath2 ( ) {
			var fixture = new Fixture ( );
			var p2 = fixture.Create ( "/path2-" );
			var result = LinuxPath.Combine ( string.Empty, p2 );
			Assert.Equal ( "/{0}/".With ( p2 ).REReplace ( "//", "/" ), result );
		}

		[Fact]
		public void When2ArgsAndPath2IsEmpty_ShouldReturnRelativePath1 ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "path1-" );
			var p2 = string.Empty;
			var result = LinuxPath.Combine ( p1, p2 );
			Assert.Equal ( "./{0}/".With ( p1 ), result );
		}

		[Fact]
		public void When2ArgsAndPath2IsEmptyAndPath2IsRooted_ShouldReturnRootedPath1 ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1-" );
			var p2 = string.Empty;
			var result = LinuxPath.Combine ( p1, p2 );
			Assert.Equal ( "/{0}/".With ( p1 ).REReplace ( "//", "/" ), result );
		}

		[Fact]
		public void When2ArgsAndPath1ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}-{1}".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "path1" ) ), fixture.Create ( "path2" ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When2ArgsAndPath2ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), "{0}-{1}".With ( fixture.Create ( "path2" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When2Args_ShouldReturnCombined ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1" );
			var p2 = fixture.Create ( "path2" );
			var result = LinuxPath.Combine ( p1, p2 );
			Assert.Equal ( "{0}/{1}".With ( p1, p2 ), result );
		}

		[Fact]
		public void When2ArgsAndPathsHaveSeparators_ShouldReturnCombined ( ) {
			var fixture = new Fixture ( );
			var p1 = "{0}/".With ( fixture.Create ( "/path1" ) );
			var p2 = fixture.Create ( "path2" );
			var result = LinuxPath.Combine ( p1, p2 );
			Assert.Equal ( "{0}/{1}".With ( p1, p2 ).REReplace ( "//", "/" ), result );
		}

		[Fact]
		public void When2ArgsAndPath2IsRooted_ShouldReturnPath2 ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1-" );
			var p2 = fixture.Create ( "/path2-" );
			var result = LinuxPath.Combine ( p1, p2 );
			Assert.Equal ( "{0}/".With ( p2 ), result );
		}

		[Fact]
		public void When3ArgsAndPath1IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( null, fixture.Create ( "path2" ), fixture.Create ( "path3" ) );
			} );
		}

		[Fact]
		public void When3ArgsAndPath2IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), null, fixture.Create ( "path3" ) );
			} );
		}

		[Fact]
		public void When3ArgsAndPath3IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), fixture.Create ( "path2" ), null );
			} );
		}

		[Fact]
		public void When3ArgsAndPath1ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}-{1}".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "path1" ) ), fixture.Create ( "path2" ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When3ArgsAndPath2ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), "{0}-{1}".With ( fixture.Create ( "path2" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When3ArgsAndPath3ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), fixture.Create ( "path2" ), "{0}-{1}".With ( fixture.Create ( "path3" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When3Args_ShouldReturnCombined ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1" );
			var p2 = fixture.Create ( "path2" );
			var p3 = fixture.Create ( "path3" );
			var result = LinuxPath.Combine ( p1, p2, p3 );
			Assert.Equal ( "{0}/{1}/{2}".With ( p1, p2, p3 ), result );
		}

		[Fact]
		public void When4ArgsAndPath1IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( null, fixture.Create ( "path2" ), fixture.Create ( "path3" ), fixture.Create ( "path4" ) );
			} );
		}

		[Fact]
		public void When4ArgsAndPath2IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), null, fixture.Create ( "path3" ), fixture.Create ( "path4" ) );
			} );
		}

		[Fact]
		public void When4ArgsAndPath3IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), fixture.Create ( "path2" ), null, fixture.Create ( "path4" ) );
			} );
		}
		[Fact]
		public void When4ArgsAndPath4IsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				var result = LinuxPath.Combine ( fixture.Create ( "path1" ), fixture.Create ( "path2" ), fixture.Create ( "path3" ), null );
			} );
		}

		[Fact]
		public void When4ArgsAndPath1ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}-{1}".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "path1" ) ), fixture.Create ( "path2" ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When4ArgsAndPath2ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), "{0}-{1}".With ( fixture.Create ( "path2" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When4ArgsAndPath3ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), fixture.Create ( "path2" ), "{0}-{1}".With ( fixture.Create ( "path3" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When4ArgsAndPath4ContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.Combine ( "/{0}".With ( fixture.Create ( "path1" ) ), fixture.Create ( "path2" ), fixture.Create ( "path3" ), "{0}-{1}".With ( fixture.Create ( "path4" ), LinuxPathConsts.InvalidPathChars[x] ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );

		}

		[Fact]
		public void When4Args_ShouldReturnCombined ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1" );
			var p2 = fixture.Create ( "path2/" );
			var p3 = fixture.Create ( "./path3" );
			var p4 = fixture.Create ( "path4/" );
			var result = LinuxPath.Combine ( p1, p2, p3, p4 );
			Assert.Equal ( "{0}/{1}/{2}/{3}".With ( p1, p2, p3, p4 ), result );
		}

		[Fact]
		public void WhenArgsArray_ShouldReturnCombined ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1" );
			var p2 = fixture.Create ( "path2" );
			var p3 = fixture.Create ( "path3" );
			var p4 = fixture.Create ( "path4" );
			var p5 = fixture.Create ( "path5" );
			var result = LinuxPath.Combine ( p1, p2, p3, p4, p5 );
			var expected = "{0}/{1}/{2}/{3}/{4}".With ( p1, p2, p3, p4, p5 );
			Assert.Equal ( expected, result );
		}

		[Fact]
		public void WhenArgsArrayIsNull_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			string[] args = null;
			Assert.Throws<ArgumentNullException> ( ( ) => {
				LinuxPath.Combine ( args );
			} );
		}

		[Fact]
		public void WhenArgsArrayContainsNullItem_ShouldThrowArgumentNullException ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "/path1" );
			string p2 = null;
			var p3 = fixture.Create ( "path3" );
			var p4 = fixture.Create ( "path4" );
			var p5 = fixture.Create ( "path5" );
			Assert.Throws<ArgumentNullException> ( ( ) => {
				LinuxPath.Combine ( p1, p2, p3, p4, p5 );
			} );
			
		}


	}
}


<|start_filename|>Managed.AndroidDebugBridge/IPacketConsumer.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public interface IPacketConsumer {
		/// <summary>
		/// Reads this instance.
		/// </summary>
		void Read ( );
		// TODO: JdwpPacket
		/// <summary>
		/// Gets the JDWP packet.
		/// </summary>
		/// <returns></returns>
		/*JdwpPacket*/
		object GetJdwpPacket ( );
		/// <summary>
		/// Forwards the packet to client.
		/// </summary>
		/// <param name="packet">The packet.</param>
		void ForwardPacketToClient ( /*JdwpPacket*/ object packet );
		/// <summary>
		/// Sends the handshake.
		/// </summary>
		bool SendHandshake ( );
		/// <summary>
		/// Sends the and consume.
		/// </summary>
		/// <param name="packet">The packet.</param>
		void SendAndConsume ( /*JdwpPacket*/ object packet );
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/Quote.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class Quote {
		[Fact]
		public void WhenValueIsNull_ShouldReturnNull ( ) {
			var result = LinuxPath.Quote ( null );
			Assert.Null ( result );
		}

		[Fact] 
		public void WhenValueIsEmpty_ShouldReturnEmpty () {
			var result = LinuxPath.Quote ( string.Empty );
			Assert.Equal ( string.Empty, result );
		}
		[Fact] 
		public void WhenValueHasSpace_ShouldReturnQuotedValue() {
			var fixture = new Fixture ( );

			var val = fixture.Create ( "value " );
			var result = LinuxPath.Quote ( val );
			Assert.Equal ( "\"{0}\"".With ( val ), result );
		}

		[Fact]
		public void WhenValueDoesNotHaveSpace_ShouldReturnValue ( ) {
			var fixture = new Fixture ( );

			var val = fixture.Create ( "value-" );
			var result = LinuxPath.Quote ( val );
			Assert.Equal ( val , result );
		}
	}
}


<|start_filename|>Madb.Site/assets/Scripts/system.copy.js<|end_filename|>
﻿(function ($, document, window) {
	"use strict";
	$(function () {
		$("a[data-copy]").each(function () {
			var self = $(this);
			if (self.data("copy-setup")) { return; }
			self.data("copy-setup", true);
			var on = self.data("copy") || "click";
			self.on(on, function (event) {
				var $t = $(this);
				var target = $($t.data("copy-target"));
				__copy(target);
				event.preventDefault();
			});

		});

		var __copy = function (target) {
			var textarea = $("<textarea />").text(target.text()).css("display", "none");
			var texteareaElement = textarea.get(0);
			var t1 = "Text successfully copied to your clipboard";
			var t2 = "Press CTRL+C (CMD+C on Mac) to copy the text to your clipboard";
			var toastText = t2;
			// for IE
			if (texteareaElement.createTextRange) {
				var copied = texteareaElement.createTextRange();
				copied.executeCommand("Copy");
				toastText = t1;
			} else if (window.copy) {
				window.copy(textarea.text());
				toastText = t1;
			} 

			var range = document.createRange();
			range.selectNodeContents(target.get(0));
			var sel = window.getSelection();
			sel.removeAllRanges();
			sel.addRange(range);
			toastr.clear();
			toastr.options = {
				"closeButton": false,
				"debug": false,
				"positionClass": "toast-top-full-width",
				"onclick": null,
				"showDuration": 300,
				"hideDuration": 500,
				"timeOut": 5000,
				"extendedTimeOut": 2000,
				"showEasing": "linear",
				"hideEasing": "linear",
				"showMethod": "fadeIn",
				"hideMethod": "fadeOut"
			};

			toastr["info"](toastText);
		}
	})
})(window.jQuery, window.document, window);

<|start_filename|>Managed.AndroidDebugBridge/ClientEventArgs.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public enum ClientChangeMask {
		/// <summary>
		/// 
		/// </summary>
		ChangeInfo,
		/// <summary>
		/// 
		/// </summary>
		ChangeDebuggerStatus,
		/// <summary>
		/// 
		/// </summary>
		ChangeThreadMode,
		/// <summary>
		/// 
		/// </summary>
		ChangeThreadData,
		/// <summary>
		/// 
		/// </summary>
		ChangeHeapMode,
		/// <summary>
		/// 
		/// </summary>
		ChangeHeapData,
		/// <summary>
		/// 
		/// </summary>
		ChangeNatvieHeapData
	}

	/// <summary>
	/// 
	/// </summary>
	public class ClientEventArgs : EventArgs {

		/// <summary>
		/// Initializes a new instance of the <see cref="ClientEventArgs"/> class.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="changeMask">The change mask.</param>
		public ClientEventArgs ( IClient client, ClientChangeMask changeMask ) {
			this.Client = client;
			this.ChangeMask = changeMask;
		}

		/// <summary>
		/// Gets the change mask.
		/// </summary>
		/// <value>The change mask.</value>
		public ClientChangeMask ChangeMask { get; private set; }
		/// <summary>
		/// Gets the client.
		/// </summary>
		/// <value>The client.</value>
		public IClient Client { get; private set; }

	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/IShellOutputReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public interface IShellOutputReceiver {
		/// <summary>
		/// Adds the output.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="length">The length.</param>
		void AddOutput ( byte[] data, int offset, int length );
		/// <summary>
		/// Flushes the output. 
		/// </summary>
		/// <remarks>This should always be called at the end of the "process" in order to indicate that the data is ready to be processed further if needed.</remarks>
		void Flush ( );
		/// <summary>
		/// Gets a value indicating whether this instance is cancelled.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is cancelled; otherwise, <c>false</c>.
		/// </value>
		bool IsCancelled { get; }
	}

}


<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/Type.cshtml<|end_filename|>
﻿@model Type
@{
	var typeUrl = Url.UrlForType(Model);
	var isExternal = !typeUrl.StartsWith("#");
	var scrollOffset = -70;
}
<!--
-->@if(isExternal) {<!--
	--><a href="@typeUrl" target="_blank" title="@(Model.ToSafeFullName())">@Model.ToSafeName()</a><!--
-->} else {<!--
	--><a href="@typeUrl" data-scroll="click" data-scroll-offset="@(scrollOffset)" title="@(Model.ToSafeFullName())">@Model.ToSafeName()</a><!--
-->}


<|start_filename|>Madb.Site/Controllers/DocumentationController.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Madb.Site.Services;

namespace Madb.Site.Controllers {
	public class DocumentationController : Controller {
		// GET: Documentation
		public ActionResult Index(String id) {
			var builder = new DocumentationService();
			var model = builder.Build(id);
			return View(model);
		}

		public PartialViewResult Navigation(string id) {
			var builder = new DocumentationService();
			var model = builder.Build(id);
			return this.PartialView(model);
		}
	}
}

<|start_filename|>Madb.Site/Views/Documentation/Index.cshtml<|end_filename|>
﻿@model Madb.Site.Models.Documentation.NamespaceModel

@{
	ViewBag.Title = Model.Name;
}

@section featured {
	<div id="home"></div>
	<section class="featured jumbotron jumbotron-warning mbl">
		<div class="container">
			<div class="title">
				<i class="logo pull-left"></i>
				<h1>@(Html.SiteName()).</h1>
				<h2 class="muted">A managed port of the Android Debug Bridge.</h2>
				<hr />
				<p class="text-center">
					<a href="https://madb.codeplex.com/" target="_blank" class="btn btn-lg"><i class="fa fa-external-link-square mrs" title="Project"></i><span class="">Project</span></a>
					<a href="https://madb.codeplex.com/SourceControl/latest#trunk/Managed.AndroidDebugBridge/" target="_blank" class="btn btn- btn-lg"><i class="fa fa-code-fork mrs" title="Source"></i><span class="">Source</span></a>
					<a href="https://madb.codeplex.com/releases" target="_blank" class="btn btn-lg"><i class="fa fa-download mrs" title="Download"></i><span class="">Download</span></a>
					<a href="https://madb.codeplex.com/workitem/list/basic" target="_blank" class="btn btn-lg"><i class="fa fa-bug mrs" title="Issues"></i><span class="">Issues</span></a>
					<a href="https://madb.codeplex.com/discussions" target="_blank" class="btn btn-lg"><i class="fa fa-quote-left mrs" title="Discussions"></i><span class="">Discussions</span></a>
				</p>
			</div>
		</div>
	</section>
}

@(Html.Partial("_AboutPartial"))
@(Html.Partial("_NugetPartial"))
@(Html.Partial("_LicensePartial"))

<div id="documentation">
	@(Html.Partial("_AdPartial"))
	<div class="panel panel-success pan">
		<div class="panel-heading"><h1 class="zero lowercase"><i class="fa fa-book mrm"></i>Documentation</h1></div>
		<div class="panel-body">
			@foreach(var ns in Model.Namespaces) {
				if(!ns.Ignore) {
					@(Html.Partial("_AdPartial"))
					@Html.DisplayFor(d => ns)
				}
			}
		</div>
	</div>
</div>


<|start_filename|>Managed.AndroidDebugBridge/IO/ByteOrder.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.IO {
	/// <summary>
	/// 
	/// </summary>
	/// <ignore>true</ignore>
	public class ByteOrder {

		/// <summary>
		/// Initializes a new instance of the <see cref="ByteOrder"/> class.
		/// </summary>
		/// <param name="name">The name.</param>
		private ByteOrder ( string name ) {
			this.Name = name;
		}

		/// <summary>
		/// The big endian
		/// </summary>
		public readonly static ByteOrder BIG_ENDIAN = new ByteOrder ( "BIG_ENDIAN" );
		/// <summary>
		/// The little endian
		/// </summary>
		public readonly static ByteOrder LITTLE_ENDIAN = new ByteOrder ( "LITTLE_ENDIAN" );

		/// <summary>
		/// Gets the name.
		/// </summary>
		/// <value>
		/// The name.
		/// </value>
		public string Name { get; private set; }
		/// <summary>
		/// Returns a <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
		/// </returns>
		public override string ToString ( ) {
			return Name;
		}
	}

}


<|start_filename|>Managed.AndroidDebugBridge/Extensions/ThrowIf.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {
		internal static void ThrowIfNegative<T> ( this int argument, Expression<Func<T, string>> func ) {
			if ( argument < 0 ) {
				ThrowException ( s => new ArgumentOutOfRangeException ( s ), func );
			}
		}

		internal static void ThrowIfNonPositive<T> ( this int argument, Expression<Func<T, string>> func ) {
			if ( argument <= 0 ) {
				ThrowException ( s => new ArgumentOutOfRangeException ( s ), func );
			}
		}

		/// <summary>
		/// Throws if null.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="argument">The argument.</param>
		/// <param name="func">The function.</param>
		public static void ThrowIfNull<T> ( this T argument, Expression<Func<T, string>> func ) where T : class {
			if ( argument == null ) {
				ThrowException ( s => new ArgumentNullException ( s ), func );
			}
		}

		/// <summary>
		/// Throws if null or empty.
		/// </summary>
		/// <param name="argument">The argument.</param>
		/// <param name="func">The function.</param>
		public static void ThrowIfNullOrEmpty ( this String argument, Expression<Func<String, string>> func ) {
			if ( String.IsNullOrEmpty(argument) ) {
				ThrowException ( s => new ArgumentNullException ( s ), func );
			}
		}

		/// <summary>
		/// Throws if null or white space.
		/// </summary>
		/// <param name="argument">The argument.</param>
		/// <param name="func">The function.</param>
		public static void ThrowIfNullOrWhiteSpace ( this String argument, Expression<Func<String, string>> func ) {
			if ( String.IsNullOrEmpty ( argument ) || String.IsNullOrEmpty(argument.Trim()) ) {
				ThrowException ( s => new ArgumentNullException ( s ), func );
			}
		}

		private static void ThrowException<T, E> ( Func<string, E> e, Expression<Func<T, string>> func ) where E : Exception {
			string name = string.Empty;
			Expression body = func.Body;
			if ( body is MemberExpression )
				name = ( (MemberExpression)body ).Member.Name;
			throw e ( name );
		}

		internal static void ThrowIfNull<T> ( this T argument, string name ) where T : class {
			if ( argument == null ) {
				throw new ArgumentNullException ( name );
			}
		}

		internal static void ThrowIfNullOrEmpty ( this String argument, string name ) {
			if ( String.IsNullOrEmpty(argument) ) {
				throw new ArgumentNullException ( name );
			}
		}

		internal static void ThrowIfNullOrWhiteSpace ( this String argument, string name ) {
			if ( String.IsNullOrEmpty ( argument ) || String.IsNullOrEmpty ( argument.Trim ( ) ) ) {
				throw new ArgumentNullException ( name );
			}
		}

		internal static void ThrowIfNegative ( this int argument, string name ) {
			if ( argument < 0 ) {
				throw new ArgumentOutOfRangeException ( name );
			}
		}

		internal static void ThrowIfNonPositive ( this int argument, string name ) {
			if ( argument <= 0 ) {
				throw new ArgumentOutOfRangeException ( name );
			}
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/GetPropReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetPropReceiver : MultiLineReceiver {
		/// <summary>
		/// The getprop command
		/// </summary>
		public const String GETPROP_COMMAND = "getprop";
		private const String GETPROP_PATTERN = "^\\[([^]]+)\\]\\:\\s*\\[(.*)\\]$";

		/// <summary>
		/// Initializes a new instance of the <see cref="GetPropReceiver"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public GetPropReceiver ( Device device ) {
			this.Device = device;
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>The device.</value>
		public Device Device { get; set; }


		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			// We receive an array of lines. We're expecting
			// to have the build info in the first line, and the build
			// date in the 2nd line. There seems to be an empty line
			// after all that.

			foreach ( string line in lines ) {
				if ( string.IsNullOrEmpty ( line ) || line.StartsWith ( "#" ) || line.StartsWith("$") ) {
					continue;
				}
				var m = line.Match ( GETPROP_PATTERN, RegexOptions.Compiled );
				if ( m.Success ) {
					var label = m.Groups[1].Value.Trim ( );
					var value = m.Groups[2].Value.Trim ( );

					if ( label.Length > 0 ) {
						Device.Properties.Add ( label, value );
					}
				}
			}
		}

		/// <summary>
		/// Finishes the receiver
		/// </summary>
		protected override void Done ( ) {
			this.Device.OnBuildInfoChanged ( EventArgs.Empty );
			base.Done ( );
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/AllocationInfo.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Managed.Adb {

	/// <summary>
	///  Holds Allocation information.
	/// </summary>
	public class AllocationInfo : IComparable<AllocationInfo> {

		/// <summary>
		/// Initializes a new instance of the <see cref="AllocationInfo"/> class.
		/// </summary>
		/// <param name="allocatedClass">The allocated class.</param>
		/// <param name="allocationSize">Size of the allocation.</param>
		/// <param name="threadId">The thread id.</param>
		/// <param name="stackTrace">The stack trace.</param>
		public AllocationInfo ( String allocatedClass, int allocationSize, short threadId, StackTrace stackTrace ) {
			AllocatedClass = allocatedClass;
			AllocationSize = allocationSize;
			ThreadId = threadId;
			StackTrace = stackTrace;
		}

		/// <summary>
		/// Gets the allocated class.
		/// </summary>
		/// <value>The allocated class.</value>
		public String AllocatedClass { get; private set; }
		/// <summary>
		/// Gets the size of the allocation.
		/// </summary>
		/// <value>The size of the allocation.</value>
		public int AllocationSize { get; private set; }
		/// <summary>
		/// Gets the thread id.
		/// </summary>
		/// <value>The thread id.</value>
		public short ThreadId { get; private set; }
		/// <summary>
		/// Gets the stack trace.
		/// </summary>
		/// <value>The stack trace.</value>
		public StackTrace StackTrace { get; private set; }


		/// <summary>
		/// Compares the current object with another object of the same type.
		/// </summary>
		/// <param name="other">An object to compare with this object.</param>
		/// <returns>
		/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
		/// </returns>
		public int CompareTo ( AllocationInfo other ) {
			return other.AllocationSize - AllocationSize;
		}

	}
}


<|start_filename|>Managed.AndroidDebugBridge/AndroidDebugBridgeEventArgs.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <ignore>true</ignore>
	public class AndroidDebugBridgeEventArgs : EventArgs {

		/// <summary>
		/// Initializes a new instance of the <see cref="AndroidDebugBridgeEventArgs"/> class.
		/// </summary>
		/// <param name="bridge">The bridge.</param>
		public AndroidDebugBridgeEventArgs ( AndroidDebugBridge bridge ) {
			this.Bridge = bridge;
		}

		/// <summary>
		/// Gets the bridge.
		/// </summary>
		/// <value>The bridge.</value>
		public AndroidDebugBridge Bridge { get; private set; }

	}
}


<|start_filename|>Managed.AndroidDebugBridge/IO/Rgb565.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;

namespace Managed.Adb.IO {
	/// <summary>
	/// A class that represents Rgb565 Image information
	/// </summary>
	public static class Rgb565 {

		/// <summary>
		/// Reads the file and returns the RGB565 Image
		/// </summary>
		/// <param name="file">The file.</param>
		/// <returns></returns>
		public static Image ToImage ( string file ) {
			using ( FileStream fs = new FileStream ( file, FileMode.Open, FileAccess.Read ) ) {
				return ToImage ( fs );
			}
		}

		/// <summary>
		/// Reads the file and returns the RGB565 Image
		/// </summary>
		/// <param name="stream">The stream.</param>
		/// <returns></returns>
		public static Image ToImage ( Stream stream ) {
			byte[] buffer = new byte[32768];
			using ( MemoryStream ms = new MemoryStream ( ) ) {
				while ( true ) {
					int read = stream.Read ( buffer, 0, buffer.Length );
					if ( read <= 0 ) {
						return ToImage ( ms.ToArray ( ) );
					}
					ms.Write ( buffer, 0, read );
				}
			}

		}

		/// <summary>
		/// Reads the file and returns the RGB565 Image
		/// </summary>
		/// <param name="buffer">The buffer.</param>
		/// <returns></returns>
		public static Image ToImage ( byte[] buffer ) {
			return ToImage ( PixelFormat.Format16bppRgb565, buffer );
		}

		/// <summary>
		/// Reads the file and returns the RGB565 Image
		/// </summary>
		/// <param name="format">The format.</param>
		/// <param name="buffer">The buffer.</param>
		/// <returns></returns>
		public static Image ToImage ( PixelFormat format, byte[] buffer ) {
			int pixels = buffer.Length / 2;
			Size imageSize = ScreenResolution.Instance.CalculateSize ( pixels );
			return ToImage ( format, buffer, imageSize.Width, imageSize.Height );
		}


		/// <summary>
		/// Gets the Image from the raw image data
		/// </summary>
		/// <param name="format">The format.</param>
		/// <param name="data">The data.</param>
		/// <param name="width">The width.</param>
		/// <param name="height">The height.</param>
		/// <returns></returns>
		public static Image ToImage( PixelFormat format, byte[] data, int width, int height ) {
			int pixels = data.Length / 2;
			Bitmap bitmap = null;
			Bitmap image = null;
			BitmapData bitmapdata = null;
			pixels = ScreenResolution.Instance.PixelsFromSize ( new Size(width,height) );

			try {
				bitmap = new Bitmap ( width, height, format );
				bitmapdata = bitmap.LockBits ( new Rectangle ( 0, 0, width, height ), ImageLockMode.WriteOnly, format );
				image = new Bitmap ( width, height, format );

				for ( int i = 0; i < data.Length; i++ ) {
					Marshal.WriteByte ( bitmapdata.Scan0, i, data[i] );
				}
				bitmap.UnlockBits ( bitmapdata );
				using ( Graphics g = Graphics.FromImage ( image ) ) {
					g.DrawImage ( bitmap, new Point ( 0, 0 ) );
					return image;
				}

			} catch ( Exception ) {
				throw;
			}
		}

		/// <summary>
		/// Converts the data to an image
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="width">The width.</param>
		/// <param name="height">The height.</param>
		/// <returns></returns>
		public static Image ToImage( byte[] data, int width, int height ) {
			return ToImage ( PixelFormat.Format16bppRgb565, data, width, height );
		}

		/// <summary>
		/// Saves the image as an Rgb565 bitmap to disk
		/// </summary>
		/// <param name="image">The image.</param>
		/// <param name="file">The file.</param>
		/// <returns></returns>
		public static bool ToRgb565( this Image image, string file ) {
			try {
				Bitmap bmp = image as Bitmap;
				BitmapData bmpData = bmp.LockBits ( new Rectangle ( 0, 0, bmp.Width, bmp.Height ), ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb565 );
				using ( FileStream fs = new FileStream ( file, FileMode.Create, FileAccess.Write, FileShare.Read ) ) {
					byte[] buffer = new byte[307200];
					Marshal.Copy ( bmpData.Scan0, buffer, 0, buffer.Length );
					fs.Write ( buffer, 0, buffer.Length );
				}
				bmp.UnlockBits ( bmpData );
				return true;
			} catch {
				return false;
			}
		}

		/// <summary>
		/// Saves the image as an Rgb565 bitmap to the specified stream
		/// </summary>
		/// <param name="image">The image.</param>
		/// <param name="stream">The stream.</param>
		/// <returns></returns>
		public static bool ToRgb565( this Image image, Stream stream ) {
			try {
				Bitmap bmp = image as Bitmap;
				BitmapData bmpData = bmp.LockBits ( new Rectangle ( 0, 0, bmp.Width, bmp.Height ), ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb565 );
				using ( stream ) {
					byte[] buffer = new byte[307200];
					Marshal.Copy ( bmpData.Scan0, buffer, 0, buffer.Length );
					stream.Write ( buffer, 0, buffer.Length );
				}
				bmp.UnlockBits ( bmpData );
				return true;
			} catch {
				return false;
			}
		}
	}

}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetInvalidFileNameChars.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Managed.Adb.IO;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetInvalidFileNameChars {
		[Fact]
		public void WhenGetttingInvalidFileNameChars_ShouldEqualExpected () {
			var result = LinuxPath.GetInvalidFileNameChars ( );
			Assert.Equal ( LinuxPathConsts.InvalidFileNameChars, result );
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/ErrorCodeHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <ignore>true</ignore>
	public static class ErrorCodeHelper {
		/** Result code for transfer success. */
    public const int RESULT_OK = 0;
    /** Result code for canceled transfer */
    public const int RESULT_CANCELED = 1;
    /** Result code for unknown error */
    public const int RESULT_UNKNOWN_ERROR = 2;
    /** Result code for network connection error */
    public const int RESULT_CONNECTION_ERROR = 3;
    /** Result code for unknown remote object during a pull */
    public const int RESULT_NO_REMOTE_OBJECT = 4;
    /** Result code when attempting to pull multiple files into a file */
    public const int RESULT_TARGET_IS_FILE = 5;
    /** Result code when attempting to pull multiple into a directory that does not exist. */
    public const int RESULT_NO_DIR_TARGET = 6;
    /** Result code for wrong encoding on the remote path. */
    public const int RESULT_REMOTE_PATH_ENCODING = 7;
    /** Result code for remote path that is too long. */
    public const int RESULT_REMOTE_PATH_LENGTH = 8;
    /** Result code for error while writing local file. */
    public const int RESULT_FILE_WRITE_ERROR = 9;
    /** Result code for error while reading local file. */
    public const int RESULT_FILE_READ_ERROR = 10;
    /** Result code for attempting to push a file that does not exist. */
    public const int RESULT_NO_LOCAL_FILE = 11;
    /** Result code for attempting to push a directory. */
    public const int RESULT_LOCAL_IS_DIRECTORY = 12;
    /** Result code for when the target path of a multi file push is a file. */
    public const int RESULT_REMOTE_IS_FILE = 13;
    /** Result code for receiving too much data from the remove device at once */
    public const int RESULT_BUFFER_OVERRUN = 14;


		/// <summary>
		/// Errors the code to string.
		/// </summary>
		/// <param name="code">The code.</param>
		/// <returns></returns>
		public static String ErrorCodeToString ( int code ) {
			switch ( code ) {
				case RESULT_OK:
					return "Success.";
				case RESULT_CANCELED:
					return "Tranfert canceled by the user.";
				case RESULT_UNKNOWN_ERROR:
					return "Unknown Error.";
				case RESULT_CONNECTION_ERROR:
					return "Adb Connection Error.";
				case RESULT_NO_REMOTE_OBJECT:
					return "Remote object doesn't exist!";
				case RESULT_TARGET_IS_FILE:
					return "Target object is a file.";
				case RESULT_NO_DIR_TARGET:
					return "Target directory doesn't exist.";
				case RESULT_REMOTE_PATH_ENCODING:
					return "Remote Path encoding is not supported.";
				case RESULT_REMOTE_PATH_LENGTH:
					return "Remove path is too long.";
				case RESULT_FILE_WRITE_ERROR:
					return "Writing local file failed!";
				case RESULT_FILE_READ_ERROR:
					return "Reading local file failed!";
				case RESULT_NO_LOCAL_FILE:
					return "Local file doesn't exist.";
				case RESULT_LOCAL_IS_DIRECTORY:
					return "Local path is a directory.";
				case RESULT_REMOTE_IS_FILE:
					return "Remote path is a file.";
				case RESULT_BUFFER_OVERRUN:
					return "Receiving too much data.";
				default:
					return "Unknown error code.";
			}

		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/ListingServiceReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class ListingServiceReceiver : MultiLineReceiver {
		/// <summary>
		/// 
		/// </summary>
		private const String LINK_FORMAT = "-> {0}";
		/// <summary>
		/// Create an ls receiver/parser.
		/// </summary>
		/// <param name="parent">The list of current children. To prevent collapse during update, reusing the same 
		/// FileEntry objects for files that were already there is paramount.</param>
		/// <param name="entries">the list of new children to be filled by the receiver.</param>
		/// <param name="links">the list of link path to compute post ls, to figure out if the link 
		/// pointed to a file or to a directory.</param>
		public ListingServiceReceiver ( FileEntry parent, List<FileEntry> entries, List<String> links ) {
			Parent = parent;
			Entries = entries ?? new List<FileEntry>();
			Links = links ?? new List<String> ( );
			CurrentChildren = Parent.Children.ToArray ( );
		}

		/// <summary>
		/// Gets or sets the entries.
		/// </summary>
		/// <value>The entries.</value>
		public List<FileEntry> Entries { get; private set; }
		/// <summary>
		/// Gets or sets the links.
		/// </summary>
		/// <value>The links.</value>
		public List<String> Links { get; private set; }
		/// <summary>
		/// Gets or sets the current children.
		/// </summary>
		/// <value>The current children.</value>
		public FileEntry[] CurrentChildren { get; private set; }
		/// <summary>
		/// Gets or sets the parent.
		/// </summary>
		/// <value>The parent.</value>
		public FileEntry Parent { get; private set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			foreach ( string line in lines ) {
				// no need to handle empty lines.
				if ( line.Length == 0 ) {
					continue;
				}
				// maybe parse out the folder name and show it, but 'locked'?
				var deniedMatch = line.Match ( @"^l?stat\s'(.*?)'\failed:\spermission\sdenied" );
				if ( ( deniedMatch.Success ) ) {
					Console.Write ( $"Permission Denied: {deniedMatch.Groups[2].Value}" );
					continue;
				}

				// run the line through the regexp
				var m = line.Trim ( ).Match ( FileListingService.LS_PATTERN_EX, RegexOptions.Compiled );
				if ( !m.Success ) {
					Log.v ( "madb", "no match on file pattern: {0}", line );
					continue;
				}
				// get the name
				string name = m.Groups[9].Value;

				if ( string.Compare ( name, ".", true ) == 0 || string.Compare ( name, "..", true ) == 0 ) {
					// we don't care if the entry is a "." or ".."
					continue;
				}

				// get the rest of the groups
				string permissions = m.Groups[1].Value;
				string owner = m.Groups[2].Value;
				string group = m.Groups[3].Value;
				bool isExec = string.Compare ( m.Groups[10].Value, "*", true ) == 0;
				long size = 0;
				string sizeData = m.Groups[4].Value.Trim ( );
				long.TryParse ( string.IsNullOrWhiteSpace ( sizeData ) ? "-1" : sizeData, out size );
				string date1 = m.Groups[5].Value.Trim ( );
				string date2 = m.Groups[6].Value.Trim ( );
				string date3 = m.Groups[7].Value.Trim ( );

				DateTime date = DateTime.Now.GetEpoch ( );
				string time = m.Groups[8].Value.Trim();
				if ( string.IsNullOrWhiteSpace ( time ) ) {
					time = date.ToString ( "HH:mm" );
				}
				if ( date1.Length == 3 ) {
					// check if we don't have a year and use current if we don't
					string tyear = string.IsNullOrWhiteSpace ( date3 ) ? DateTime.Now.Year.ToString ( ) : date3;
					date = DateTime.ParseExact ( string.Format ( "{0}-{1}-{2} {3}", date1, date2.PadLeft(2,'0'), tyear, time ), "MMM-dd-yyyy HH:mm", CultureInfo.CreateSpecificCulture("en-US"));
				} else if ( date1.Length == 4 ) {
					date = DateTime.ParseExact( string.Format("{0}-{1}-{2} {3}", date1, date2.PadLeft(2, '0'), date3, time), "yyyy-MM-dd HH:mm", CultureInfo.CreateSpecificCulture("en-US"));
				}

				string info = null;
				string linkName = null;

				// and the type
				FileListingService.FileTypes objectType = FileListingService.FileTypes.Other;
				switch ( permissions[0] ) {
					case '-':
						objectType = FileListingService.FileTypes.File;
						break;
					case 'b':
						objectType = FileListingService.FileTypes.Block;
						break;
					case 'c':
						objectType = FileListingService.FileTypes.Character;
						break;
					case 'd':
						objectType = FileListingService.FileTypes.Directory;
						break;
					case 'l':
						objectType = FileListingService.FileTypes.Link;
						break;
					case 's':
						objectType = FileListingService.FileTypes.Socket;
						break;
					case 'p':
						objectType = FileListingService.FileTypes.FIFO;
						break;
				}


				// now check what we may be linking to
				if ( objectType == FileListingService.FileTypes.Link ) {
					string[] segments = name.Split ( new string[] { " -> " }, StringSplitOptions.RemoveEmptyEntries );
					// we should have 2 segments
					if ( segments.Length == 2 ) {
						// update the entry name to not contain the link
						name = segments[0];
						// and the link name
						info = segments[1];

						// now get the path to the link
						string[] pathSegments = info.Split ( new string[] { FileListingService.FILE_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries );
						if ( pathSegments.Length == 1 ) {
							// the link is to something in the same directory,
							// unless the link is ..
							if ( string.Compare ( "..", pathSegments[0], false ) == 0 ) {
								// set the type and we're done.
								objectType = FileListingService.FileTypes.DirectoryLink;
							} else {
								// either we found the object already
								// or we'll find it later.
							}
						}

						// if we set the size to -1, then its a directory link
						// this is a hack because Android M stock does not support -lFa the right way.
						if ( size == -1 ) {
							objectType = FileListingService.FileTypes.DirectoryLink;
							size = 0;
						}
					} else {
						
					}

					linkName = info;
					// add an arrow in front to specify it's a link.
					info = string.Format ( LINK_FORMAT, info );
				}

				// get the entry, either from an existing one, or a new one
				FileEntry entry = GetExistingEntry ( name );
				if ( entry == null ) {
					entry = new FileEntry ( Parent.Device, Parent, name, objectType, false /* isRoot */);
				}

				// add some misc info
				entry.Permissions = new FilePermissions ( permissions );
				entry.Size = size;
				entry.Date = date;
				entry.Owner = owner;
				entry.Group =  group;
				entry.IsExecutable = isExec;
				entry.LinkName = linkName;
				if ( objectType == FileListingService.FileTypes.Link || objectType == FileListingService.FileTypes.DirectoryLink ) {
					entry.Info = info;
				}

				Entries.Add ( entry );
			}
		}


		/// <summary>
		/// Gets a value indicating whether this instance is cancelled.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is cancelled; otherwise, <c>false</c>.
		/// </value>
		public override bool IsCancelled {
			get {
				return false;
			}
		}

		/// <summary>
		/// Queries for an already existing Entry per name
		/// </summary>
		/// <param name="name">the name of the entry</param>
		/// <returns>the existing FileEntry or null if no entry with a matching name exists.</returns>
		private FileEntry GetExistingEntry ( String name ) {
			for ( int i = 0; i < CurrentChildren.Length; i++ ) {
				FileEntry e = CurrentChildren[i];
				// since we're going to "erase" the one we use, we need to
				// check that the item is not null.
				if ( e != null ) {
					// compare per name, case-sensitive.
					if ( string.Compare ( name, e.Name, false ) == 0 ) {
						// erase from the list
						CurrentChildren[i] = null;
						// and return the object
						return e;
					}
				}
			}

			// couldn't find any matching object, return null
			return null;
		}


		/// <summary>
		/// Finishes the links.
		/// </summary>
		public void FinishLinks ( ) {
			// this isnt done in the DDMS lib either... 
			// TODO: Handle links in the listing service
		}
	}
}


<|start_filename|>Madb.Site/assets/styles/typography.css<|end_filename|>
﻿

.text-white {
	color: #fff !important;
}

.uppercase {
	text-transform: uppercase;
}

.lowercase {
	text-transform: lowercase;
}

.bold {
	font-weight: bold;
}

.center {
	text-align: center;
}

<|start_filename|>Managed.AndroidDebugBridge/Extensions/DateTimeHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {
		/// <summary>
		/// Gets EPOCH time
		/// </summary>
		public static readonly DateTime Epoch = new DateTime ( 1970, 1, 1 );

		/// <summary>
		/// Gets epoch time.
		/// </summary>
		/// <param name="dt">The dt.</param>
		/// <returns></returns>
		public static DateTime GetEpoch ( this DateTime dt ) {
			return Epoch;
		}

		/// <summary>
		/// Currents the time millis.
		/// </summary>
		/// <param name="dateTime">The date time.</param>
		/// <returns></returns>
		public static long CurrentTimeMillis ( this DateTime dateTime ) {
			return (long)( dateTime.ToUniversalTime() - Epoch ).TotalMilliseconds;
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/InstallReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class InstallReceiver : MultiLineReceiver {
		/// <summary>
		/// 
		/// </summary>
		private const string SUCCESS_OUTPUT = "Success";
		/// <summary>
		/// 
		/// </summary>
		private const string FAILURE_PATTERN = @"Failure(?:\s+\[(.*)\])?";


		private const string UNKNOWN_ERROR = "An unknown error occurred.";
		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			foreach ( string line in lines ) {
				if ( line.Length > 0 ) {
					if ( line.StartsWith ( SUCCESS_OUTPUT ) ) {
						ErrorMessage = null;
						Success = true;
					} else {
						var m = line.Match ( FAILURE_PATTERN, RegexOptions.Compiled | RegexOptions.IgnoreCase );
						ErrorMessage = UNKNOWN_ERROR;
						if ( m.Success ) {
							string msg = m.Groups[1].Value;
							ErrorMessage = string.IsNullOrWhiteSpace(msg) ? UNKNOWN_ERROR : msg;
						}
						Success = false;
					}
				}
			}
		}

		/// <summary>
		/// Gets the error message if the install was unsuccessful.
		/// </summary>
		/// <value>The error message.</value>
		public string ErrorMessage { get; private set; }

		/// <summary>
		/// Gets a value indicating whether the install was a success.
		/// </summary>
		/// <value>
		///   <c>true</c> if success; otherwise, <c>false</c>.
		/// </value>
		public bool Success { get; private set; }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Extensions/BytesHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {

		/// <summary>
		/// Reverses the bytes.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static UInt16 ReverseBytes ( this UInt16 value ) {
			return (UInt16)( ( value & 0xFFU ) << 8 | ( value & 0xFF00U ) >> 8 );
		}

		/// <summary>
		/// Reverses the bytes.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static UInt32 ReverseBytes ( this UInt32 value ) {
			return ( value & 0x000000FFU ) << 24 | ( value & 0x0000FF00U ) << 8 |
				 ( value & 0x00FF0000U ) >> 8 | ( value & 0xFF000000U ) >> 24;
		}

		/// <summary>
		/// Reverses the bytes.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static UInt64 ReverseBytes ( this UInt64 value ) {
			return ( value & 0x00000000000000FFUL ) << 56 | ( value & 0x000000000000FF00UL ) << 40 |
				 ( value & 0x0000000000FF0000UL ) << 24 | ( value & 0x00000000FF000000UL ) << 8 |
				 ( value & 0x000000FF00000000UL ) >> 8 | ( value & 0x0000FF0000000000UL ) >> 24 |
				 ( value & 0x00FF000000000000UL ) >> 40 | ( value & 0xFF00000000000000UL ) >> 56;
		}


		/// <summary>
		/// Ints the reverse for raw image.
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="action">The action.</param>
		public static void IntReverseForRawImage ( this byte[] source, Action<byte[]> action ) {
			var step = 4;
			for ( int i = 0; i < source.Count ( ); i += step ) {
				var b = new byte[step];
				for ( int x = b.Length - 1; x >= 0; --x ) {
					b[( step - 1 ) - x] = source[i + x];
				}

				b[2] = source[i + 0];
				b[1] = source[i + 1];
				b[0] = source[i + 2];
				b[3] = source[i + 3];

				action ( b );
			}
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/ParameterModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Camalot.Common.Extensions;

namespace Madb.Site.Models.Documentation {
	public class ParameterModel {
		public string Name { get; set; }
		public TypeModel Type { get; set; }
		public bool IsOut { get; set; }
		public bool IsIn { get; set; }
		public bool IsOptional { get; set; }

		public override string ToString() {
			return "{4}{2}{3}{0} {1}{5}".With(Type.ToString(), Name, IsOut ? "{out}" : "", IsIn ? "{in}" : "", IsOptional ? "[" : "", IsOptional ? "]" : "");
		}
	}
}

<|start_filename|>MadBee.Console/Arguments.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadBee.Console {
	public class Arguments : IEnumerable<String> {

		/// <summary>
		/// Initializes a new instance of the <see cref="Arguments"/> class.
		/// </summary>
		/// <param name="args">The args.</param>
		public Arguments( String[] args )
			: this ( ) {
			Parse ( args );
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Arguments"/> class.
		/// </summary>
		public Arguments( ) {
			Parameters = new Dictionary<String, String> ( );
		}

		private Dictionary<String, String> Parameters { get; set; }

		/// <summary>
		/// Parses the specified args.
		/// </summary>
		/// <param name="args">The args.</param>
		public void Parse( String[] args ) {
			Parameters.Clear ( );

			Regex spliter = new Regex ( @"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace );

			Regex remover = new Regex ( @"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace );

			string parameter = null;
			string[] parts;

			// Valid parameters forms:
			// {-,/,--}param{ ,=,:}((",')value(",'))
			// Examples: 
			// -param1 value1 --param2 /param3:"Test-:-work" 
			//   /param4=happy -param5 '--=nice=--'
			foreach ( string txt in args ) {

				// Look for new parameters (-,/ or --) and a
				// possible enclosed value (=,:)
				parts = spliter.Split ( txt, 3 );

				switch ( parts.Length ) {
					// Found a value (for the last parameter 
					// found (space separator))
					case 1:
						if ( parameter != null ) {
							if ( !Parameters.ContainsKey ( parameter ) ) {
								parts[0] = remover.Replace ( parts[0], "$1" );
								Parameters.Add ( parameter, parts[0] );
							}
							parameter = null;
						} else {
							parts[0] = remover.Replace ( parts[0], "$1" );
							if ( !Parameters.ContainsKey ( parts[0].ToLower ( ).Trim ( ) ) ) {
								Parameters.Add ( parts[0].ToLower ( ).Trim ( ), parts[0] );
							}
						}
						// else Error: no parameter waiting for a value (skipped)
						break;

					// Found just a parameter
					case 2:
						// The last parameter is still waiting. 
						// With no value, set it to true.
						if ( parameter != null ) {
							if ( !Parameters.ContainsKey ( parameter ) )
								Parameters.Add ( parameter, "true" );
						}
						parameter = parts[1];
						break;

					// Parameter with enclosed value
					case 3:
						// The last parameter is still waiting. 
						// With no value, set it to true.
						if ( parameter != null ) {
							if ( !Parameters.ContainsKey ( parameter ) )
								Parameters.Add ( parameter, "true" );
						}

						parameter = parts[1];

						// Remove possible enclosing characters (",')
						if ( !Parameters.ContainsKey ( parameter ) ) {
							parts[2] = remover.Replace ( parts[2], "$1" );
							Parameters.Add ( parameter, parts[2] );
						}

						parameter = null;
						break;
				}
			}
			// In case a parameter is still waiting
			if ( parameter != null ) {
				if ( !Parameters.ContainsKey ( parameter ) )
					Parameters.Add ( parameter, "true" );
			}
		}

		// Retrieve a parameter value if it exists 
		// (overriding C# indexer property)
		/// <summary>
		/// Gets the <see cref="System.String"/> with the specified param.
		/// </summary>
		/// <value></value>
		/// <exception cref="IndexOutOfRangeException">If it does not contain the specified param.</exception>
		public string this[String param] {
			get {
				return Get ( param );
			}
		}

		/// <summary>
		/// Gets the <see cref="System.String"/> with the specified paramlist.
		/// </summary>
		/// <value></value>
		/// <exception cref="IndexOutOfRangeException">If it does not contain the specified param.</exception>
		public string this[params String[] paramlist] {
			get {
				return Get ( paramlist );
			}
		}


		/// <summary>
		/// Gets the specified param value.
		/// </summary>
		/// <param name="param">The param.</param>
		/// <returns>The value of the param.</returns>
		/// <exception cref="IndexOutOfRangeException">If it does not contain the specified param.</exception>
		public String Get( String param ) {
			if ( ContainsKey ( param ) ) {
				return Parameters[param];
			}

			throw new IndexOutOfRangeException ( );
		}

		/// <summary>
		/// Gets the value of a param from the specified paramlist.
		/// </summary>
		/// <param name="paramlist">The paramlist.</param>
		/// <returns>The value of the param.</returns>
		/// <exception cref="IndexOutOfRangeException">If it does not contain the specified param.</exception>
		public String Get( params String[] paramlist ) {
			foreach ( var param in paramlist ) {
				if ( Parameters.ContainsKey ( param ) ) {
					return Parameters[param];
				}
			}

			throw new IndexOutOfRangeException ( );
		}

		/// <summary>
		/// Determines whether this instance contains the specified key.
		/// </summary>
		/// <param name="param">The param.</param>
		/// <returns>
		/// 	<c>true</c> if this instance contains the specified key; otherwise, <c>false</c>.
		/// </returns>
		public bool ContainsKey( String param ) {
			return Parameters.ContainsKey ( param );
		}

		/// <summary>
		/// Determines whether this instance contains any of the params in the specified param list.
		/// </summary>
		/// <param name="paramlist">The paramlist.</param>
		/// <returns>
		/// 	<c>true</c> if this instance contains any of the params in the specified param list; otherwise, <c>false</c>.
		/// </returns>
		public bool ContainsKey( params String[] paramlist ) {
			foreach ( var item in paramlist ) {
				if ( Parameters.ContainsKey ( item ) ) {
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Determines whether the specified value contains value.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns>
		/// 	<c>true</c> if the specified value contains value; otherwise, <c>false</c>.
		/// </returns>
		public bool ContainsValue( string value ) {
			return Parameters.ContainsValue ( value );
		}

		/// <summary>
		/// Gets the keys.
		/// </summary>
		/// <value>The keys.</value>
		public Dictionary<string, string>.KeyCollection Keys {
			get { return Parameters.Keys; }
		}

		/// <summary>
		/// Gets the values.
		/// </summary>
		/// <value>The values.</value>
		public Dictionary<String, String>.ValueCollection Values {
			get { return this.Parameters.Values; }
		}

		/// <summary>
		/// Gets the count.
		/// </summary>
		/// <value>The count.</value>
		public int Count { get { return this.Parameters.Count; } }



		/// <summary>
		/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
		/// </returns>
		public override string ToString( ) {
			StringBuilder sb = new StringBuilder ( );
			foreach ( string key in Parameters.Keys )
				sb.AppendFormat ( "/{0}={1} ", key, Parameters[key] );
			return sb.ToString ( ).Trim ( );
		}

		public IEnumerator<string> GetEnumerator( ) {
			return this.Keys.GetEnumerator ( );
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator( ) {
			return this.GetEnumerator ( );
		}
	}
}


<|start_filename|>Madb.Site/Views/Documentation/_LicensePartial.cshtml<|end_filename|>
﻿<div id="license">
	@(Html.Partial("_AdPartial"))
	<div class="panel panel-success pan">
		<div class="panel-heading"><h1 class="zero lowercase"><i class="fa fa-certificate mrm"></i>License</h1></div>
		<div class="panel-body">
			<div class="gist-container">
				@(Html.Action("Gist", new { controller = "assets", id = "3d408440566327fe5c62" }))
			</div>
		</div>
	</div>
</div>

<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/Member.cshtml<|end_filename|>
﻿@model Madb.Site.Models.Documentation.Xml.Member
@{
	const int scrollOffset = -70;
}
<div class="member">
	@if(Model.Summary.Where(m => !string.IsNullOrWhiteSpace(m.Value)).Any()) {
		<div class="alert alert-success">
			@foreach(var s in Model.Summary) {
				if(!string.IsNullOrWhiteSpace(s.Value)) {
					<p class="man mbs pan">@Html.Raw(s)</p>
				}
			}
		</div>
	}

	@if(Model.Remarks.Where(m => !string.IsNullOrWhiteSpace(m.Value)).Any()) {
		<div class="alert alert-primary">
			@foreach(var s in Model.Remarks) {
				if(!string.IsNullOrWhiteSpace(s.Value)) {
					<p class="man mbs pan">@Html.Raw(s)</p>
				}
			}
		</div>
	}

	@if(Model.Gists.Where(m => !string.IsNullOrWhiteSpace(m.Id)).Any()) {
		<div class="gist-host">
			@foreach(var s in Model.Gists) {
				if(!string.IsNullOrWhiteSpace(s.Description)) {
					<div class="alert alert-primary">@s.Description</div>
				}
				<text>@Html.Action("Gist", new { controller = "Assets", id = s.Id })</text>
			}
		</div>
	}

	@if(Model.Params.Where(m => !string.IsNullOrWhiteSpace(m.Value)).Any()) {
		<h4 class="zero">Parameters</h4>
		<div class="mts">
			<table class="table table-bordered table-condensed table-striped">
				<tr>
					<th>Name</th>
					<th>Description</th>
				</tr>
				@foreach(var s in Model.Params) {
					if(!string.IsNullOrWhiteSpace(s.Name)) {
						<tr>
							<td>@s.Name</td>
							<td>@s.Value</td>
						</tr>
					}
				}
			</table>
		</div>
	}

	@if(Model.Exceptions.Any()) {
		<h4 class="zero">Exceptions</h4>
		<div class="mts">
			<table class="table table-bordered table-condensed table-striped">
				<tr>
					<th>Type</th>
					<th>Description</th>
				</tr>
				@foreach(var s in Model.Exceptions) {
					var reference = s.Link.Substring(2);
					var link = Url.ParseReferenceUrl(s.Link);
					var text = Url.ParseReferenceAsText(string.IsNullOrWhiteSpace(s.Description) ? s.Link : "{0}".With(s.Description));
					var regex = new System.Text.RegularExpressions.Regex(@"\sor\s", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
					foreach(var item in regex.Split(text)) {
						<tr>
							<td>
								@if(link.StartsWith("#")) {
									<a href="@link" data-scroll="click" data-scroll-offset="@scrollOffset">@reference</a>
								} else {
									<a href="@link" target="_blank">@reference</a>
								}
							</td>
							<td>@item</td>
						</tr>
					}
				}
			</table>
		</div>
	}

	@if(Model.SeeAlsos.Any() || Model.Sees.Any()) {
		<h4 class="zero">References</h4>
		<div class="mts">
			<table class="table table-bordered table-condensed table-striped">
				@foreach(var s in Model.SeeAlsos.Concat(Model.Sees)) {
					if(!string.IsNullOrWhiteSpace(s.Link)) {
						var text = Url.ParseReferenceAsText(string.IsNullOrWhiteSpace(s.Description) ? s.Link : s.Description);
						// process the link to internals.
						var link = Url.ParseReferenceUrl(s.Link);
						<tr>
							<td>
								@if(link.StartsWith("#")) {
									<a href="@link" data-scroll="click" data-scroll-offset="@scrollOffset">@text</a>
								} else {
									<a href="@link" target="_blank">@text</a>
								}
							</td>
						</tr>
					}
				}
			</table>
		</div>
	}
</div>

<|start_filename|>Managed.AndroidDebugBridge/IO/ScreenResolution.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Managed.Adb.IO {
	internal class ScreenResolution {
		public const int QVGA = 320 * 240;
		public const int WQVGA = 320 * 480;
		public const int WQVGA2 = 400 * 240;
		public const int WQVGA3 = 432 * 240;
		public const int VGA = 640 * 480;
		public const int WGA = 800 * 480;
		public const int WVGA = 768 * 480;
		public const int WVGA2 = 854 * 480;
		public const int DVGA = 960 * 640;
		public const int PAL = 576 * 520;
		public const int NTSC = 486 * 440;
		public const int SVGA = 800 * 600;
		public const int WSVGA = 1024 * 576;
		public const int XGA = 1024 * 768;
		public const int XGAPLUS = 1152 * 864;
		public const int HD720 = 1280 * 720;
		public const int WXGA = 1280 * 768;
		public const int WXGA2 = 1280 * 800;
		public const int WXGA3 = 1280 * 854;
		public const int SXGA = 1280 * 1024;
		public const int WXGA4 = 1366 * 768;
		public const int SXGAMINUS = 1280 * 960;
		public const int SXGAPLUS = 1400 * 1050;
		public const int WXGAPLUS = 1440 * 900;
		public const int HD900 = 1600 * 900;
		public const int WSXGA = 1600 * 1024;
		public const int WSXGAPLUS = 1680 * 1050;
		public const int UXGA = 1600 * 1200;
		public const int HD1080 = 1920 * 1080;
		public const int QWXGA = 2048 * 1152;
		public const int WUXGA = 1920 * 1200;
		public const int TXGA = 1920 * 1400;
		public const int QXGA = 2048 * 1536;
		public const int WQHD = 2560 * 1440;
		public const int WQXGA = 2560 * 1600;
		public const int QSXGA = 2560 * 2048;
		public const int QSXGAPLUS = 2800 * 2100;
		public const int WQSXGA = 3200 * 2048;
		public const int QUXGA = 3200 * 2400;
		public const int QFHD = 3840 * 2160;
		public const int WQUXGA = 3840 * 2400;
		public const int HD4K = 4096 * 2304;
		public const int HXGA = 4096 * 3072;
		public const int WHXGA = 5120 * 3200;
		public const int HSXGA = 5120 * 4096;
		public const int WHSXGA = 6400 * 4096;
		public const int HUXGA = 6400 * 4800;
		public const int SHV = 7680 * 4320;
		public const int WHUXGA = 7680 * 4800;

		private ScreenResolution ( ) {
			Sizes = new Dictionary<int, Size> ( );
			Sizes.Add ( QVGA, new Size ( 320, 240 ) );
			Sizes.Add ( WQVGA, new Size ( 320, 480 ) );
			Sizes.Add ( WQVGA2, new Size ( 400, 240 ) );
			Sizes.Add ( WQVGA3, new Size ( 432, 240 ) );
			Sizes.Add ( NTSC, new Size ( 486, 440 ) );
			Sizes.Add ( VGA, new Size ( 640, 480 ) );
			Sizes.Add ( WGA, new Size ( 480, 800 ) );
			Sizes.Add ( WVGA2, new Size ( 480, 854 ) );
			Sizes.Add ( DVGA, new Size ( 960, 640 ) );
			Sizes.Add ( PAL, new Size ( 576, 520 ) );
			Sizes.Add ( SVGA, new Size ( 800, 600 ) );
			Sizes.Add ( WSVGA, new Size ( 1024, 576 ) );
			Sizes.Add ( XGA, new Size ( 1024, 768 ) );
			Sizes.Add ( XGAPLUS, new Size ( 1152, 864 ) );
			Sizes.Add ( HD720, new Size ( 1280, 720 ) );
			Sizes.Add ( WXGA, new Size ( 1280, 768 ) );
			Sizes.Add ( WXGA2, new Size ( 1280, 800 ) );
			Sizes.Add ( WXGA3, new Size ( 1280, 854 ) );
			Sizes.Add ( SXGA, new Size ( 1280, 1024 ) );
			Sizes.Add ( WXGA4, new Size ( 1366, 768 ) );
			Sizes.Add ( SXGAMINUS, new Size ( 1280, 960 ) );
			Sizes.Add ( SXGAPLUS, new Size ( 1400, 1050 ) );
			Sizes.Add ( WXGAPLUS, new Size ( 1440, 900 ) );
			Sizes.Add ( HD900, new Size ( 1600, 900 ) );
			Sizes.Add ( WSXGA, new Size ( 1600, 1024 ) );
			Sizes.Add ( WSXGAPLUS, new Size ( 1680, 1050 ) );
			Sizes.Add ( UXGA, new Size ( 1600, 1200 ) );
			Sizes.Add ( HD1080, new Size ( 1920, 1080 ) );
			Sizes.Add ( QWXGA, new Size ( 2048, 1152 ) );
			Sizes.Add ( WUXGA, new Size ( 1920, 1200 ) );
			Sizes.Add ( TXGA, new Size ( 1900, 1400 ) );
			Sizes.Add ( QXGA, new Size ( 2048, 1536 ) );
			Sizes.Add ( WQHD, new Size ( 2560, 1440 ) );
			Sizes.Add ( WQXGA, new Size ( 2560, 1600 ) );
			Sizes.Add ( QSXGA, new Size ( 2560, 2048 ) );
			Sizes.Add ( QSXGAPLUS, new Size ( 2800, 2100 ) );
			Sizes.Add ( WQSXGA, new Size ( 3200, 2048 ) );
			Sizes.Add ( QUXGA, new Size ( 3200, 2400 ) );
			Sizes.Add ( QFHD, new Size ( 3840, 2160 ) );
			Sizes.Add ( WQUXGA, new Size ( 3840, 2400 ) );
			Sizes.Add ( HD4K, new Size ( 4096, 2304 ) );
			Sizes.Add ( HXGA, new Size ( 4096, 3072 ) );
			Sizes.Add ( WHXGA, new Size ( 5120, 3200 ) );
			Sizes.Add ( HSXGA, new Size ( 5120, 4096 ) );
			Sizes.Add ( WHSXGA, new Size ( 6400, 4096 ) );
			Sizes.Add ( HUXGA, new Size ( 6400, 4800 ) );
			Sizes.Add ( SHV, new Size ( 7680, 4320 ) );
			Sizes.Add ( WHUXGA, new Size ( 7680, 4800 ) );

			// not a real resolution its here for comparison purposes only.
			Sizes.Add ( int.MaxValue / 2, new Size ( int.MaxValue, int.MaxValue ) );
		}

		private static ScreenResolution _instance = null;
		/// <summary>
		/// Gets the instance.
		/// </summary>
		/// <value>
		/// The instance.
		/// </value>
		public static ScreenResolution Instance {
			get {
				if ( _instance == null ) {
					_instance = new ScreenResolution ( );
				}
				return _instance;
			}
		}

		/// <summary>
		/// Gets the sizes.
		/// </summary>
		/// <value>
		/// The sizes.
		/// </value>
		public Dictionary<int, Size> Sizes { get; private set; }


		/// <summary>
		/// Calculates the size.
		/// </summary>
		/// <param name="pixels">The pixels.</param>
		/// <returns></returns>
		/// <exception cref="System.IndexOutOfRangeException"></exception>
		public Size CalculateSize ( long pixels ) {
			// this doesnt work very well, unless the number of pixels is exact!
			List<int> ordered = new List<int> ( Sizes.Keys );
			ordered.Sort ( );

			Console.WriteLine ( "total sizes: {0}", ordered.Count );
			for ( int i = 0; i < ordered.Count - 1; i++ ) {
				if ( pixels >= ordered[i] && pixels < ordered[i + 1] ) {
					Console.WriteLine ( "Resolution: {0}", ordered[i] );
					return Sizes[ordered[i]];
				}
			}

			// throw exception because we couldnt find it.
			throw new IndexOutOfRangeException ( );

		}

		/// <summary>
		/// Pixelses from size.
		/// </summary>
		/// <param name="size">The size.</param>
		/// <returns></returns>
		/// <exception cref="System.IndexOutOfRangeException"></exception>
		public int PixelsFromSize ( Size size ) {

			foreach ( var item in Sizes.Keys ) {
				var itemSize = Sizes[item];
				if ( size.Equals ( itemSize ) ) {
					Console.WriteLine ( "Size: {0}", itemSize.ToString ( ) );
					return item;
				}
			}

			throw new IndexOutOfRangeException ( );

		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/ClassModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Camalot.Common.Extensions;

namespace Madb.Site.Models.Documentation {
	public class ClassModel {
		public ClassModel() {
			Methods = new List<MethodModel>();
			Properties = new List<PropertyModel>();
		}
		public string Name { get; set; }
		public string Description { get; set; }
		public string Namespace { get; set; }
		public string Assembly { get; set; }
		public Xml.Member Documentation { get; set; }
		public string XmlName { get; set; }
		public bool Ignore { get { return Documentation != null && Documentation.Ignore; } }
		public bool IsStatic { get; set; }

		public IList<MethodModel> Methods {get;set;}

		public IList<PropertyModel> Properties { get; set; }

		public string Id {
			get {
				return "{0}.{1}".With(Namespace, Name).Slug();
			}
		}

		public override string ToString() {
			return "{0}.{1}".With(Namespace, Name);
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Receivers/ConsoleOutputReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class ConsoleOutputReceiver : MultiLineReceiver {
		private static ConsoleOutputReceiver _instance = null;
		/// <summary>
		/// Gets the instance.
		/// </summary>
		/// <value>
		/// The instance.
		/// </value>
		public static ConsoleOutputReceiver Instance {
			get {
				if ( _instance == null ) {
					_instance = new ConsoleOutputReceiver ( );
				}
				return _instance;
			}
		}
		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
			protected override void ProcessNewLines ( string[] lines ) {
				foreach ( var line in lines ) {
					if (string.IsNullOrWhiteSpace ( line ) || line.StartsWith ( "#" ) || line.StartsWith("$") ) {
						continue;
					}
					Console.WriteLine ( line );
        }
			}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/UnknownOptionException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// Thrown when a command has an unknown option passed
	/// </summary>
	public class UnknownOptionException : Exception {
		/// <summary>
		/// Initializes a new instance of the <see cref="UnknownOptionException"/> class.
		/// </summary>
		public UnknownOptionException ( )
			: base ( "Unknown option." ) {
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="UnknownOptionException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		public UnknownOptionException ( String message )
			: base ( message ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="UnknownOptionException"/> class.
		/// </summary>
		/// <param name="serializationInfo">The serialization info.</param>
		/// <param name="context">The context.</param>
		public UnknownOptionException ( SerializationInfo serializationInfo, StreamingContext context )
			: base ( serializationInfo, context ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="UnknownOptionException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="innerException">The inner exception.</param>
		public UnknownOptionException ( String message, Exception innerException )
			: base ( message, innerException ) {

		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/HasExtension.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class HasExtension {
		[Fact]
		public void WhenPathIsNull_ShouldReturnFalse () {
			var result = LinuxPath.HasExtension ( null );
			Assert.False ( result );
		}

		[Fact]
		public void WhenPathIsEmpty_ShouldReturnFalse ( ) {
			var result = LinuxPath.HasExtension ( string.Empty );
			Assert.False ( result );
		}

		[Fact]
		public void WhenPathDoesNotHaveFile_ShouldReturnFalse ( ) {
			var fixture = new Fixture ( );
			var path = "/path/to/file/";
			var result = LinuxPath.HasExtension ( path );
			Assert.False ( result );
		}

		[Fact]
		public void WhenPathHasExtension_ShouldReturnTrue ( ) {
			var fixture = new Fixture ( );
			var file = fixture.Create ( "file-" );
			var path = "/path/to/file/{0}.ext".With ( file );
			var result = LinuxPath.HasExtension ( path );
			Assert.True ( result );
		}

		[Fact]
		public void WhenPathDoesNotHaveExtension_ShouldReturnFalse ( ) {
			var fixture = new Fixture ( );
			var file = fixture.Create ( "file-" );
			var path = "/path/to/file/{0}".With ( file );
			var result = LinuxPath.HasExtension ( path );
			Assert.False ( result );
		}
	}
}


<|start_filename|>Madb.Site/Extensions/HtmlHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc.Html;
using System.Web.Mvc;
using Camalot.Common.Extensions;
using Madb.Site.Models;

namespace Madb.Site.Extensions {
	public static partial class MadbSiteExtensions {
		public static IHtmlString SiteName(this HtmlHelper helper) {
			var value = ConfigurationManager.AppSettings["site:Name"].Or("");
			return new MvcHtmlString(value);
		}

		public static IHtmlString DirectLink(this HtmlHelper helper, string id) {
			return helper.Partial("_DirectLink", id);
		}

		public static IHtmlString StaticIcon(this HtmlHelper helper, bool isStatic) {
			return helper.Icon("fa-flag", isStatic, "Static");
		}

		public static IHtmlString ReadonlyIcon(this HtmlHelper helper, bool isReadonly) {
			return helper.Icon("fa-lock", isReadonly, "Readonly");
		}

		public static IHtmlString ExtensionIcon(this HtmlHelper helper, bool isExtension) {
			return helper.Icon("fa-plug", isExtension, "Extension");
		}

		public static IHtmlString Icon(this HtmlHelper helper, string icon, bool show = true, string title = "") {
			return helper.Partial("_IconPartial", new IconHelperModel {
				Show = show,
				Title = title,
				Icon = icon
			});
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/NullSyncProgressMonitor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// A Sync progress monitor that does nothing
	/// </summary>
	public sealed class NullSyncProgressMonitor : ISyncProgressMonitor {

		/// <summary>
		/// Sent when the transfer starts
		/// </summary>
		/// <param name="totalWork">the total amount of work.</param>
		public void Start ( long totalWork ) {
		}

		/// <summary>
		/// Sent when the transfer is finished or interrupted.
		/// </summary>
		public void Stop ( ) {
		}

		/// <summary>
		/// Sent to query for possible cancellation.
		/// </summary>
		/// <returns><c>true</c> if the transfer should be stopped; otherwise, false</returns>
		public bool IsCanceled {
			get {
				return false;
			}
		}

		/// <summary>
		/// Sent when a sub task is started.
		/// </summary>
		/// <param name="source"></param>
		/// <param name="destination">the destination.</param>
		public void StartSubTask ( String source, String destination ) {
		}

		/// <summary>
		/// Sent when some progress have been made.
		/// </summary>
		/// <param name="work">the amount of work done.</param>
		public void Advance ( long work ) {
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Receivers/CommandResultReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class CommandResultReceiver : MultiLineReceiver{
		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			var result = new StringBuilder ( );
			foreach ( string line in lines ) {
				if ( string.IsNullOrWhiteSpace ( line ) || line.StartsWith ( "#" ) || line.StartsWith ( "$" ) ) {
					continue;
				}

				result.AppendLine ( line );
			}

			this.Result = result.ToString ( ).Trim ( );
		}

		/// <summary>
		/// Gets the result.
		/// </summary>
		/// <value>
		/// The result.
		/// </value>
		public string Result { get; private set; }
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Client.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace Managed.Adb {
	/// <summary>
	/// A debug client
	/// </summary>
	public class Client : IClient {


		/// <summary>
		/// 
		/// </summary>
		private const int SERVER_PROTOCOL_VERSION = 1;
		/// <summary>
		/// 
		/// </summary>
		private const int INITIAL_BUF_SIZE = 2 * 1024;
		/// <summary>
		/// 
		/// </summary>
		private const int MAX_BUF_SIZE = 200 * 1024 * 1024;
		/// <summary>
		/// 
		/// </summary>
		private const int WRITE_BUF_SIZE = 256;

		/// <summary>
		/// Initializes a new instance of the <see cref="Client"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="channel">The channel.</param>
		/// <param name="pid">The pid.</param>
		public Client ( Device device, Socket channel, int pid ) {
			this.Device = device;
			this.Channel = channel;
			this.ClientData = new ClientData ( pid );

			IsThreadUpdateEnabled = DdmPreferences.InitialThreadUpdate;
			IsHeapUpdateEnabled = DdmPreferences.InitialHeapUpdate;
			ConnectionState = ClientConnectionState.Init;
		}

		/// <summary>
		/// Gets the state of the change.
		/// </summary>
		/// <value>
		/// The state of the change.
		/// </value>
		public ClientChangeState ChangeState { get; private set; }

		/// <summary>
		/// Gets or sets the channel.
		/// </summary>
		/// <value>
		/// The channel.
		/// </value>
		public Socket Channel { get; set; }

		/// <summary>
		/// Gets the state of the connection.
		/// </summary>
		/// <value>
		/// The state of the connection.
		/// </value>
		public ClientConnectionState ConnectionState { get; private set; }

		/// <summary>
		/// Gets the device.
		/// </summary>
		public IDevice Device { get; private set; }

		/// <summary>
		/// Gets the device implementation.
		/// </summary>
		public Device DeviceImplementation { get; private set; }

		/// <summary>
		/// Gets the debugger listen port.
		/// </summary>
		public int DebuggerListenPort { get; private set; }

		/// <summary>
		/// Returns <code>true</code> if the client VM is DDM-aware.
		/// </summary>
		/// <remarks>Calling here is only allowed after the connection has been established.</remarks>
		public bool IsDdmAware {
			get {
				switch ( ConnectionState ) {
					case ClientConnectionState.Init:
					case ClientConnectionState.NotJDWP:
					case ClientConnectionState.AwaitShake:
					case ClientConnectionState.NeedDDMPacket:
					case ClientConnectionState.NotDDM:
					case ClientConnectionState.Error:
					case ClientConnectionState.Disconnected:
						return false;
					case ClientConnectionState.Ready:
						return true;
					default:
						Log.e ( "ddm", "wtf are we doing in here? You shouldn't see this." );
						return false;
				}
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is debugger attached.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is debugger attached; otherwise, <c>false</c>.
		/// </value>
		public bool IsDebuggerAttached {
			get {
				return Debugger != null && Debugger.IsDebuggerAttached;
			}
		}

		/// <summary>
		/// Gets the debugger.
		/// </summary>
		public Debugger Debugger { get; private set; }

		/// <summary>
		/// Gets the client data.
		/// </summary>
		public ClientData ClientData { get; private set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance is thread update enabled.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is thread update enabled; otherwise, <c>false</c>.
		/// </value>
		public bool IsThreadUpdateEnabled { get; set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance is heap update enabled.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is heap update enabled; otherwise, <c>false</c>.
		/// </value>
		public bool IsHeapUpdateEnabled { get; set; }

		/// <summary>
		/// Gets or sets a value indicating whether this instance is selected client.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is selected client; otherwise, <c>false</c>.
		/// </value>
		public bool IsSelectedClient { get; set; }

		/// <summary>
		/// Gets a value indicating whether this instance is valid.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance is valid; otherwise, <c>false</c>.
		/// </value>
		public bool IsValid { get; private set; }

		/// <summary>
		/// Executes the garbage collector.
		/// </summary>
		public void ExecuteGarbageCollector ( ) {
			throw new NotImplementedException ( );

			/*try {
				HandleHeap.SendHPGC ( this );
			} catch ( IOException ioe ) {
				Log.w ( "ddms", "Send of HPGC message failed" );
			}*/
		}

		/// <summary>
		/// Dumps the hprof.
		/// </summary>
		public void DumpHprof ( ) {
			throw new NotImplementedException ( );

			/*bool canStream = ClientData.HasFeature ( ClientData.FEATURE_HPROF_STREAMING );
			try {
				if ( canStream ) {
					HandleHeap.SendHPDS ( this );
				} else {
					String file = String.Format("/sdcard/{0}.hprof", ClientData.ClientDescription.ReplaceAll ( "\\:.*", "" ) );
					HandleHeap.SendHPDU ( this, file );
				}
			} catch ( IOException e ) {
				Log.w ( "ddms", "Send of HPDU message failed" );
			}*/
		}

		/// <summary>
		/// Toggles the method profiling.
		/// </summary>
		public void ToggleMethodProfiling ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the method profiling status.
		/// </summary>
		public void RequestMethodProfilingStatus ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the thread update.
		/// </summary>
		public void RequestThreadUpdate ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the thread stack trace.
		/// </summary>
		/// <param name="threadID">The thread ID.</param>
		public void RequestThreadStackTrace ( int threadID ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the native heap information.
		/// </summary>
		/// <returns></returns>
		public bool RequestNativeHeapInformation ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Enables the allocation tracker.
		/// </summary>
		/// <param name="enable">if set to <c>true</c> [enable].</param>
		public void EnableAllocationTracker ( bool enable ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the allocation status.
		/// </summary>
		public void RequestAllocationStatus ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Requests the allocation details.
		/// </summary>
		public void RequestAllocationDetails ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Kills this instance.
		/// </summary>
		public void Kill ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Registers the specified selector.
		/// </summary>
		/// <param name="selector">The selector.</param>
		public void Register ( object selector ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Listens for debugger.
		/// </summary>
		/// <param name="listenPort">The listen port.</param>
		public void ListenForDebugger ( int listenPort ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Sends the and consume.
		/// </summary>
		/// <param name="packet">The packet.</param>
		/// <param name="replyHandler">The reply handler.</param>
		public void SendAndConsume ( object packet, ChunkHandler replyHandler ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Adds the request id.
		/// </summary>
		/// <param name="id">The id.</param>
		/// <param name="handler">The handler.</param>
		public void AddRequestId ( int id, ChunkHandler handler ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Removes the request id.
		/// </summary>
		/// <param name="id">The id.</param>
		public void RemoveRequestId ( int id ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Determines whether [is response to us] [the specified id].
		/// </summary>
		/// <param name="id">The id.</param>
		/// <returns></returns>
		public ChunkHandler IsResponseToUs ( int id ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Packets the failed.
		/// </summary>
		/// <param name="packet">The packet.</param>
		public void PacketFailed ( object packet ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// DDMs the seen.
		/// </summary>
		/// <returns></returns>
		public bool DdmSeen ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Closes the specified notify.
		/// </summary>
		/// <param name="notify">if set to <c>true</c> [notify].</param>
		public void Close ( bool notify ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Updates the specified change mask.
		/// </summary>
		/// <param name="changeMask">The change mask.</param>
		public void Update ( ClientChangeMask changeMask ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Reads this instance.
		/// </summary>
		public void Read ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Gets the JDWP packet.
		/// </summary>
		/// <returns></returns>
		public object GetJdwpPacket ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Forwards the packet to client.
		/// </summary>
		/// <param name="packet">The packet.</param>
		public void ForwardPacketToClient ( object packet ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Sends the handshake.
		/// </summary>
		/// <returns></returns>
		public bool SendHandshake ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Sends the and consume.
		/// </summary>
		/// <param name="packet">The packet.</param>
		public void SendAndConsume ( object packet ) {
			throw new NotImplementedException ( );
		}


		/// <summary>
		/// Returns a <see cref="System.String"/> that represents this instance.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String"/> that represents this instance.
		/// </returns>
		public override String ToString ( ) {
			return String.Format ( "[Client pid: {0}]", ClientData.Pid );
		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForByteOrder/ByteOrder.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIO.ForByteOrder {
	public class ByteOrder {
		[Fact]
		public void WhenBigEdianName_ShouldReturnBigEdian ( ) {
			var fixture = new Fixture ( );

			var be = IO.ByteOrder.BIG_ENDIAN;
			Assert.Equal ( be.Name, "BIG_ENDIAN" );
		}

		[Fact]
		public void WhenBigEdianToString_ShouldReturnBigEdian ( ) {
			var fixture = new Fixture ( );

			var be = IO.ByteOrder.BIG_ENDIAN;
			Assert.Equal ( be.ToString(), "BIG_ENDIAN" );
		}


		[Fact]
		public void WhenLittleEdianName_ShouldReturnBigEdian ( ) {
			var fixture = new Fixture ( );

			var be = IO.ByteOrder.LITTLE_ENDIAN;
			Assert.Equal ( be.Name, "LITTLE_ENDIAN" );
		}

		[Fact]
		public void WhenLittleEdianToString_ShouldReturnBigEdian ( ) {
			var fixture = new Fixture ( );

			var be = IO.ByteOrder.LITTLE_ENDIAN;
			Assert.Equal ( be.ToString ( ), "LITTLE_ENDIAN" );
		}

	}
}


<|start_filename|>Madb.Site/Views/Shared/_AdPartial.cshtml<|end_filename|>
﻿<div class="center">
	@(Html.Partial("AdSense", new Madb.Site.Models.AdSenseModel {
	PublisherId = "ca-pub-9157593394596390",
	Slot = "4102865437",
	Name = "responsivewin8"
}))
</div>

<|start_filename|>Managed.AndroidDebugBridge/ILogOutput.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public interface ILogOutput {
		/// <summary>
		/// Writes the specified log level.
		/// </summary>
		/// <param name="logLevel">The log level.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="message">The message.</param>
		void Write ( LogLevel.LogLevelInfo logLevel, String tag, String message );
		/// <summary>
		/// Writes the and prompt log.
		/// </summary>
		/// <param name="logLevel">The log level.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="message">The message.</param>
		void WriteAndPromptLog ( LogLevel.LogLevelInfo logLevel, String tag, String message );
	}

}


<|start_filename|>Madb.Site/Services/DocumentationService.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using Madb.Site.Models.Documentation;
using MoreLinq;
using Camalot.Common.Extensions;
using Madb.Site.Extensions;
using System.Configuration;
using System.Reflection;
using System.Web.Hosting;
using System.IO;
using System.Security.AccessControl;
using System.ComponentModel;

namespace Madb.Site.Services {
	public class DocumentationService {

		/// <summary>
		/// You should call GetDocumentationDomain()
		/// </summary>
		/// <value>
		/// The documentation domain.
		/// </value>
		private AppDomain DocumentationDomain { get; set; }
		private IEnumerable<Assembly> DocumentationAssemblies {
			get {
				return GetDocumentationDomain().GetAssemblies().Where(a => !a.IsDynamic);
			}
		}
		/// <summary>
		/// Builds the specified assembly name.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly.</param>
		/// <returns></returns>
		public NamespaceModel Build(string assemblyName) {
			var alternateName = GetAlternateName(assemblyName);
			var nm = new NamespaceModel {
				Name = assemblyName,
			};
			var exclude = this.GetType().Assembly;

			var xml = LoadXml(assemblyName);
			var NSIgnoreList = ConfigurationManager.AppSettings["site:NamespacesIgnoreList"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

			DocumentationAssemblies.Where(a => a != exclude &&
					(a.GetName().Name.Equals(alternateName, StringComparison.InvariantCultureIgnoreCase) || a.GetName().Name.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase))
				).ForEach(a => {
				a.GetTypes()
					.Where(t => ((t.IsInNamespace(alternateName) || t.IsInNamespace(assemblyName)) || (t.IsInChildNamespace(alternateName) || t.IsInChildNamespace(assemblyName))) && !NSIgnoreList.Contains(t.Namespace))
					.Select(t => t.Namespace)
					.Distinct()
					.ForEach(ns => {
						if(string.IsNullOrWhiteSpace(nm.AssemblyVersion)) {
							nm.AssemblyVersion = a.GetName().Version.ToString();
						}
						var processedNS = ProcessNamespace(ns, xml);
						if(processedNS != null && processedNS.Classes.Count > 0) {
							nm.Namespaces.Add(processedNS);
						}
					});
			});
			return nm;
		}

		/// <summary>
		/// Gets the documentation domain.
		/// </summary>
		/// <returns></returns>
		private AppDomain GetDocumentationDomain() {
			if(DocumentationDomain == null) {
				// create a new app domain for processing.
				DocumentationDomain = AppDomain.CreateDomain("Documentation");

				var dir = new DirectoryInfo(HostingEnvironment.MapPath("~/app_data/"));
				dir.GetFiles("*.dll").ForEach(a => {
					DocumentationDomain.Load(AssemblyName.GetAssemblyName(a.FullName));
				});
			}
			return DocumentationDomain;
		}

		/// <summary>
		/// Loads the XML.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly.</param>
		/// <returns></returns>
		/// <exception cref="System.IO.FileNotFoundException"></exception>
		private XmlDocument LoadXml(string assemblyName) {
			var file = DocumentationPathFromAssemblyName(assemblyName);
			if(file.Exists) {
				var doc = new XmlDocument();
				using(var fs = new FileStream(file.FullName, FileMode.Open, FileSystemRights.Read, FileShare.Read, 2048, FileOptions.None)) {
					doc.Load(fs);
				}
				return doc;
			} else {
				throw new FileNotFoundException();
			}
		}


		private FileInfo DocumentationPathFromAssemblyName(string assemblyName) {

			var overrideName = GetAlternateName(assemblyName);

			var fn = "{0}.xml".With(overrideName.Or(assemblyName));
			var dir = HostingEnvironment.MapPath("~/app_data/");
			var file = new FileInfo(Path.Combine(dir, fn));
			if(file.Exists) {
				return file;
			} else {
				throw new FileNotFoundException();
			}
		}

		private string GetAlternateName(string namespaceName) {
			var overrideName = ConfigurationManager.AppSettings[namespaceName];
			return overrideName.Or(namespaceName);
		}

		/// <summary>
		/// Processes the namespace.
		/// </summary>
		/// <param name="namespace">The namespace.</param>
		/// <param name="xml">The XML.</param>
		/// <returns></returns>
		private NamespaceModel ProcessNamespace(string @namespace, XmlDocument xml) {
			var nm = new NamespaceModel {
				Name = @namespace
			};
			DocumentationAssemblies.ForEach(a => {
				var classes = new List<ClassModel>();
				a.GetTypes().Where(t => t.IsPublic && t.IsClass && t.IsInNamespace(@namespace)).ForEach(t => {
					var pclass = ProcessType(t, xml);
					nm.Classes.Add(pclass);
				});
			});

			return nm;
		}

		/// <summary>
		/// Processes the type.
		/// </summary>
		/// <param name="type">The type.</param>
		/// <param name="xml">The XML.</param>
		/// <returns></returns>
		private ClassModel ProcessType(Type type, XmlDocument xml) {
			return new ClassModel {
				Name = type.ToSafeName(),
				Namespace = type.Namespace,
				Assembly = type.Assembly.GetName().Name,
				Description = type.GetCustomAttributeValue<DescriptionAttribute, String>(x => x.Description).Or(""),
				XmlName = type.GetXmlDocumentationName(),
				Documentation = xml.GetDocumenation(type),
				Methods = ProcessMethods(type, xml),
				IsStatic = type.IsAbstract && type.IsSealed,
				Properties = ProcessProperties(type,xml)
			};
		}

		private IList<PropertyModel> ProcessProperties(Type type, XmlDocument xml) {
			return type.GetProperties(System.Reflection.BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.SetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly)
				.Where(m => true).Select(m => new PropertyModel {
					Name = m.Name,
					Documentation = xml.GetDocumenation(m),
					XmlName = m.GetXmlDocumentationName(),
					IsStatic = m.GetSetMethod() != null ? m.GetSetMethod().IsStatic : m.GetGetMethod() != null ? m.GetGetMethod().IsStatic : false,
					IsReadOnly = m.GetSetMethod() == null,
					Parent = type,
					ReturnType = m.PropertyType
				}).OrderBy(x => x.Name).ToList();
		}

		/// <summary>
		/// Processes the methods.
		/// </summary>
		/// <param name="type">The type.</param>
		/// <param name="xml">The XML.</param>
		/// <returns></returns>
		private IList<MethodModel> ProcessMethods(Type type, XmlDocument xml) {

			return type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly).Where(m =>
				!m.IsConstructor &&
				!m.Name.StartsWith("get_", StringComparison.CurrentCulture) &&
				!m.Name.StartsWith("set_", StringComparison.CurrentCulture) &&
				!m.Name.StartsWith("add_", StringComparison.CurrentCulture) &&
				!m.Name.StartsWith("remove_", StringComparison.CurrentCulture) &&
					// exclude overrides because I don't care about them. Unless, base definition is in this assembly.
				(m.GetBaseDefinition() == null || m.GetBaseDefinition() == m || m.GetBaseDefinition().DeclaringType.Assembly == type.Assembly)
				).Select(m => new MethodModel {
					Name = m.Name,
					Documentation = xml.GetDocumenation(m),
					XmlName = m.GetXmlDocumentationName(),
					GenericParameters = ProcessMethodGenericParameters(m),
					Parameters = ProcessParams(m),
					ExtensionOf = m.ExtensionOf(),
					Parent = type,
					IsStatic = m.IsStatic,
					ReturnType = m.ReturnType
				}).OrderBy(x => x.Name).ThenBy(x => x.ExtensionOf == null ? "" : x.ExtensionOf.ToSafeFullName()).ThenBy(x => x.Parameters.Count).ToList();
		}

		/// <summary>
		/// Processes the method generic parameters.
		/// </summary>
		/// <param name="m">The m.</param>
		/// <returns></returns>
		private IList<TypeModel> ProcessMethodGenericParameters(System.Reflection.MethodInfo m) {
			if(m.IsGenericMethod) {
				return m.GetGenericArguments().Select(t => new TypeModel { BaseType = t, Name = t.ToSafeName() }).ToList();
			} else {
				return default(IList<TypeModel>);
			}
		}

		/// <summary>
		/// Processes the parameters.
		/// </summary>
		/// <param name="m">The m.</param>
		/// <returns></returns>
		private IList<ParameterModel> ProcessParams(System.Reflection.MethodInfo m) {
			return m.GetParameters().Select(p => new ParameterModel {
				Type = new TypeModel { BaseType = p.ParameterType, Name = p.ParameterType.ToSafeName() },
				Name = p.Name,
				IsOut = p.IsOut,
				IsIn = p.IsIn,
				IsOptional = p.IsOptional
			}).ToList();
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Device.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using Managed.Adb.Exceptions;
using Managed.Adb.IO;
using Managed.Adb.Logs;
using System.Net;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public enum DeviceState {
		/// <summary>
		/// 
		/// </summary>
		Recovery,
		/// <summary>
		/// 
		/// </summary>
		BootLoader,
		/// <summary>
		/// 
		/// </summary>
		Offline,
		/// <summary>
		/// 
		/// </summary>
		Online,
		/// <summary>
		/// 
		/// </summary>
		Download,
		/// <summary>
		/// 
		/// </summary>
		Unknown
	}

	/// <summary>
	/// 
	/// </summary>
	public sealed class Device : IDevice {
		/// <summary>
		/// The mnt external storage
		/// </summary>
		public const String MNT_EXTERNAL_STORAGE = "EXTERNAL_STORAGE";
		/// <summary>
		/// mnt data
		/// </summary>
		public const String MNT_DATA = "ANDROID_DATA";
		/// <summary>
		/// The mnt root
		/// </summary>
		public const String MNT_ROOT = "ANDROID_ROOT";

		/// <summary>
		/// Occurs when [state changed].
		/// </summary>
		public event EventHandler<EventArgs> StateChanged;
		/// <summary>
		/// Occurs when [build info changed].
		/// </summary>
		public event EventHandler<EventArgs> BuildInfoChanged;
		/// <summary>
		/// Occurs when [client list changed].
		/// </summary>
		public event EventHandler<EventArgs> ClientListChanged;

		/// <summary>
		/// 
		/// </summary>
		public const String TEMP_DIRECTORY_FOR_INSTALL = "/storage/sdcard0/tmp/";

		/// <summary>
		/// 
		/// </summary>
		public const String PROP_BUILD_VERSION = "ro.build.version.release";

		/// <summary>
		/// 
		/// </summary>
		public const String PROP_BUILD_API_LEVEL = "ro.build.version.sdk";

		/// <summary>
		/// 
		/// </summary>
		public const String PROP_BUILD_CODENAME = "ro.build.version.codename";

		/// <summary>
		/// 
		/// </summary>
		public const String PROP_DEBUGGABLE = "ro.debuggable";

		/// <summary>
		/// Serial number of the first connected emulator. 
		/// </summary>
		public const String FIRST_EMULATOR_SN = "emulator-5554";

		/** @deprecated Use {@link #PROP_BUILD_API_LEVEL}. */
		[Obsolete ( "Use PROP_BUILD_API_LEVEL" )]
		public const String PROP_BUILD_VERSION_NUMBER = PROP_BUILD_API_LEVEL;

		/// <summary>
		///  Emulator Serial Number regexp.
		/// </summary>
		private const String RE_EMULATOR_SN = @"emulator-(\d+)";

		/// <summary>
		/// Device list info regex
		/// </summary>
		/// <workitem>21136</workitem>
		private const String RE_DEVICELIST_INFO = @"^([a-z0-9_-]+(?:\s?[\.a-z0-9_-]+)?(?:\:\d{1,})?)\s+(device|offline|unknown|bootloader|recovery|download|host)(?:(?:\s+product:([\S]+)\s+model\:([\S]+)\s+device\:([\S]+))|(?:\s+features:\S+))?$";
		/// <summary>
		/// Tag
		/// </summary>
		private const String LOG_TAG = "Device";

		private const int BATTERY_TIMEOUT = 2 * 1000; //2 seconds
		private const int GETPROP_TIMEOUT = 2 * 1000; //2 seconds
		private const int INSTALL_TIMEOUT = 2 * 60 * 1000; // 2 minutes
																											 /// <summary>
																											 /// 
																											 /// </summary>
		private string _avdName;
		private bool _canSU = false;
		private BatteryInfo _lastBatteryInfo = null;
		private DateTime _lastBatteryCheckTime = DateTime.MinValue;

		/// <summary>
		/// Initializes a new instance of the <see cref="Device"/> class.
		/// </summary>
		/// <param name="serial">The serial.</param>
		/// <param name="state">The state.</param>
		/// <param name="model">The model.</param>
		/// <param name="product">The product.</param>
		/// <param name="device">The device.</param>
		public Device ( string serial, DeviceState state, string model, string product, string device ) {
			this.SerialNumber = serial;
			this.State = state;
			MountPoints = new Dictionary<String, MountPoint> ( );
			Properties = new Dictionary<string, string> ( );
			EnvironmentVariables = new Dictionary<string, string> ( );
			Clients = new List<IClient> ( );
			FileSystem = new FileSystem ( this );
			BusyBox = new BusyBox ( this );

			Model = model;
			Product = product;
			DeviceProperty = device;

			RetrieveDeviceInfo ( );
		}

		/// <summary>
		/// Retrieves the device info.
		/// </summary>
		private void RetrieveDeviceInfo ( ) {
			RefreshMountPoints ( );
			RefreshEnvironmentVariables ( );
			RefreshProperties ( );
		}

		/// <summary>
		/// Get the device state from the string value
		/// </summary>
		/// <param name="state">The device state string</param>
		/// <returns></returns>
		private static DeviceState GetStateFromString ( String state ) {
			String tstate = state;

			if ( String.Compare ( state, "device", false ) == 0 ) {
				tstate = "online";
			}

			if ( Enum.IsDefined ( typeof ( DeviceState ), tstate ) ) {
				return (DeviceState)Enum.Parse ( typeof ( DeviceState ), tstate, true );
			} else {
				foreach ( var fi in typeof ( DeviceState ).GetFields ( ) ) {
					if ( string.Compare ( fi.Name, tstate, true ) == 0 ) {
						return (DeviceState)fi.GetValue ( null );
					}
				}
			}

			return DeviceState.Unknown;
		}


		/// <summary>
		/// Create a device from Adb Device list data
		/// </summary>
		/// <param name="data">the line data for the device</param>
		/// <returns></returns>
		public static Device CreateFromAdbData ( String data ) {
			Regex re = new Regex ( RE_DEVICELIST_INFO, RegexOptions.Compiled | RegexOptions.IgnoreCase );
			Match m = re.Match ( data );
			if ( m.Success ) {
				if ( m.Groups[2].Value != "host" ) {
					return new Device ( m.Groups[1].Value, GetStateFromString ( m.Groups[2].Value ), m.Groups[4].Value, m.Groups[3].Value, m.Groups[5].Value );
				}
				return null;
			} else {
				throw new ArgumentException ( "Invalid device list data" );
			}
		}

		/// <summary>
		/// Determines whether this device can perform a backup.
		/// </summary>
		/// <returns>
		///   <c>true</c> if this device can perform a backup; otherwise, <c>false</c>.
		/// </returns>
		public bool CanBackup ( ) {
			return this.FileSystem.Exists ( "/system/bin/bu" );
		}

		/// <summary>
		/// Backups this device.
		/// </summary>
#pragma warning disable 618
		public void Backup ( ) {
			AdbHelper.Instance.Backup ( AndroidDebugBridge.SocketAddress );
		}
#pragma warning restore
		/// <summary>
		/// Determines whether this instance can use the SU shell.
		/// </summary>
		/// <returns>
		///   <c>true</c> if this instance can use the SU shell; otherwise, <c>false</c>.
		/// </returns>
		public bool CanSU ( ) {
			if ( _canSU ) {
				return _canSU;
			}

			try {
				// workitem: 16822
				// this now checks if permission was denied and accounts for that. 
				// The nulloutput receiver is fine here because it doesn't need to send the output anywhere,
				// the execute command can still handle the output with the null output receiver.
				this.ExecuteRootShellCommand ( "echo \\\"I can haz root\\\"", NullOutputReceiver.Instance );
				_canSU = true;
			} catch ( PermissionDeniedException ) {
				_canSU = false;
			} catch ( FileNotFoundException ) {
				_canSU = false;
			}

			return _canSU;
		}

		/// <summary>
		/// Gets or sets the client monitoring socket.
		/// </summary>
		/// <value>
		/// The client monitoring socket.
		/// </value>
		public Socket ClientMonitoringSocket { get; set; }

		/// <summary>
		/// Gets the device serial number
		/// </summary>
		public String SerialNumber { get; private set; }

		/// <summary>
		/// Gets the TCP endpoint defined when the transport is TCP.
		/// </summary>
		/// <value>
		/// The endpoint.
		/// </value>
		public IPEndPoint Endpoint { get; private set; }

		/// <summary>
		/// Gets the type of the transport used to connect to this device.
		/// </summary>
		/// <value>
		/// The type of the transport.
		/// </value>
		public TransportType TransportType { get; private set; }


		/// <summary>
		/// Gets or sets the Avd name.
		/// </summary>
		public String AvdName {
			get { return _avdName; }
			set {
				if ( !IsEmulator ) {
					throw new ArgumentException ( "Cannot set the AVD name of the device is not an emulator" );
				}
				_avdName = value;
			}
		}


		/// <summary>
		/// Gets the product.
		/// </summary>
		/// <value>
		/// The product.
		/// </value>
		public string Product { get; private set; }
		/// <summary>
		/// Gets the model.
		/// </summary>
		/// <value>
		/// The model.
		/// </value>
		public string Model { get; private set; }
		/// <summary>
		/// Gets the device.
		/// </summary>
		/// <value>
		/// The device identifier.
		/// </value>
		public string DeviceProperty { get; private set; }

		/// <summary>
		/// Gets the device state
		/// </summary>
		public DeviceState State { get; internal set; }

		/// <summary>
		/// Gets the device mount points.
		/// </summary>
		public Dictionary<String, MountPoint> MountPoints { get; set; }


		/// <summary>
		/// Returns the device properties. It contains the whole output of 'getprop'
		/// </summary>
		/// <value>The properties.</value>
		public Dictionary<String, String> Properties { get; private set; }

		/// <summary>
		/// Gets the environment variables.
		/// </summary>
		/// <value>The environment variables.</value>
		public Dictionary<String, String> EnvironmentVariables { get; private set; }

		/// <summary>
		/// Gets the property value.
		/// </summary>
		/// <param name="name">The name of the property.</param>
		/// <returns>
		/// the value or <code>null</code> if the property does not exist.
		/// </returns>
		public String GetProperty ( String name ) {
			return GetProperty ( new String[] { name } );
		}

		/// <summary>
		/// Gets the first property that exists in the array of property names.
		/// </summary>
		/// <param name="name">The array of property names.</param>
		/// <returns></returns>
		public String GetProperty ( params String[] name ) {
			foreach ( var item in name ) {
				if ( Properties.ContainsKey ( item ) ) {
					return Properties[item];
				}
			}

			return null;
		}

		/// <summary>
		/// Gets the file system for this device.
		/// </summary>
		public FileSystem FileSystem { get; private set; }

		/// <summary>
		/// Gets the busy box object for this device.
		/// </summary>
		public BusyBox BusyBox { get; private set; }

		/// <summary>
		/// Gets a value indicating whether the device is online.
		/// </summary>
		/// <value><c>true</c> if the device is online; otherwise, <c>false</c>.</value>
		public bool IsOnline {
			get {
				return State == DeviceState.Online;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this device is emulator.
		/// </summary>
		/// <value><c>true</c> if this device is emulator; otherwise, <c>false</c>.</value>
		public bool IsEmulator {
			get {
				return Regex.Match ( SerialNumber, RE_EMULATOR_SN ).Success;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this device is offline.
		/// </summary>
		/// <value><c>true</c> if this device is offline; otherwise, <c>false</c>.</value>
		public bool IsOffline {
			get {
				return State == DeviceState.Offline;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this device is in boot loader mode.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this device is in boot loader mode; otherwise, <c>false</c>.
		/// </value>
		public bool IsBootLoader {
			get {
				return State == DeviceState.BootLoader;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is recovery.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is recovery; otherwise, <c>false</c>.
		/// </value>
		public bool IsRecovery {
			get { return State == DeviceState.Recovery; }
		}

		/// <summary>
		/// Remounts the mount point.
		/// </summary>
		/// <param name="mnt">The mount point.</param>
		/// <param name="readOnly">if set to <c>true</c> the mount poine will be set to read-only.</param>
		public void RemountMountPoint ( MountPoint mnt, bool readOnly ) {
			String command = String.Format ( "mount -o {0},remount -t {1} {2} {3}", readOnly ? "ro" : "rw", mnt.FileSystem, mnt.Block, mnt.Name );
			this.ExecuteShellCommand ( command, NullOutputReceiver.Instance );
			RefreshMountPoints ( );
		}

		/// <summary>
		/// Remounts the mount point.
		/// </summary>
		/// <param name="mountPoint">the mount point</param>
		/// <param name="readOnly">if set to <c>true</c> the mount poine will be set to read-only.</param>
		/// <exception cref="IOException">Throws if the mount point does not exist.</exception>
		public void RemountMountPoint ( String mountPoint, bool readOnly ) {
			if ( MountPoints.ContainsKey ( mountPoint ) ) {
				MountPoint mnt = MountPoints[mountPoint];
				RemountMountPoint ( mnt, readOnly );
			} else {
				throw new IOException ( "Invalid mount point" );
			}
		}


		/// <summary>
		/// Refreshes the mount points.
		/// </summary>
		public void RefreshMountPoints ( ) {
			if ( !IsOffline ) {
				try {
					this.ExecuteShellCommand ( MountPointReceiver.MOUNT_COMMAND, new MountPointReceiver ( this ) );
				} catch ( AdbException ) {

				}
			}
		}

		/// <summary>
		/// Refreshes the environment variables.
		/// </summary>
		public void RefreshEnvironmentVariables ( ) {
			if ( !IsOffline ) {
				try {
					this.ExecuteShellCommand ( EnvironmentVariablesReceiver.ENV_COMMAND, new EnvironmentVariablesReceiver ( this ) );
				} catch ( AdbException ) {

				}
			}
		}

		/// <summary>
		/// Refreshes the properties.
		/// </summary>
		public void RefreshProperties ( ) {
			if ( !IsOffline ) {
				try {
					this.ExecuteShellCommand ( GetPropReceiver.GETPROP_COMMAND, new GetPropReceiver ( this ) );
				} catch ( AdbException aex ) {
					Log.w ( LOG_TAG, aex );
				}
			}
		}

		/// <summary>
		/// Reboots the device in to the specified state
		/// </summary>
		/// <param name="into">The reboot state</param>
		public void Reboot ( String into ) {
			AdbHelper.Instance.Reboot ( into, AndroidDebugBridge.SocketAddress, this );
		}

		/// <summary>
		/// Reboots the device in to the specified state
		/// </summary>
		public void Reboot ( ) {
			Reboot ( String.Empty );
		}

		/// <summary>
		/// Gets the battery level.
		/// </summary>
		/// <returns></returns>
		public BatteryInfo GetBatteryInfo ( ) {
			return GetBatteryInfo ( 5 * 60 * 1000 );
		}

		/// <summary>
		/// Gets the battery level.
		/// </summary>
		/// <param name="freshness">The freshness.</param>
		/// <returns></returns>
		public BatteryInfo GetBatteryInfo ( long freshness ) {
			if ( _lastBatteryInfo != null
								&& this._lastBatteryCheckTime > ( DateTime.Now.AddMilliseconds ( -freshness ) ) ) {
				return _lastBatteryInfo;
			}
			var receiver = new BatteryReceiver ( );
			ExecuteShellCommand ( "dumpsys battery", receiver, BATTERY_TIMEOUT );
			_lastBatteryInfo = receiver.BatteryInfo;
			_lastBatteryCheckTime = DateTime.Now;
			return _lastBatteryInfo;
		}

		/// <summary>
		/// Gets a value indicating whether this instance has clients.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance has clients; otherwise, <c>false</c>.
		/// </value>
		public bool HasClients {
			get {
				return Clients.Count > 0;
			}
		}


		/// <summary>
		/// Gets the list of clients
		/// </summary>
		public List<IClient> Clients { get; private set; }

		/// <summary>
		/// Returns a <see cref="SyncService"/> object to push / pull files to and from the device.
		/// </summary>
		/// <value></value>
		/// <remarks>
		/// 	<code>null</code> if the SyncService couldn't be created. This can happen if adb
		/// refuse to open the connection because the {@link IDevice} is invalid (or got disconnected).
		/// </remarks>
		/// <exception cref="IOException">Throws IOException if the connection with adb failed.</exception>
		public SyncService SyncService {
			get {
				SyncService syncService = new SyncService ( AndroidDebugBridge.SocketAddress, this );
				if ( syncService.Open ( ) ) {
					return syncService;
				}

				return null;
			}
		}

		/// <summary>
		/// Returns a <see cref="PackageManager"/> for this device.
		/// </summary>
		public PackageManager PackageManager {
			get {
				return new PackageManager ( this );
			}
		}

		/// <summary>
		/// Returns a <see cref="FileListingService"/> for this device.
		/// </summary>
		/// <value></value>
		public FileListingService FileListingService {
			get {
				return new FileListingService ( this );
			}
		}

		/// <summary>
		/// Takes a screen shot of the device and returns it as a <see cref="RawImage"/>
		/// </summary>
		/// <value>The screenshot.</value>
		public RawImage Screenshot {
			get {
				return AdbHelper.Instance.GetFrameBuffer ( AndroidDebugBridge.SocketAddress, this );
			}
		}

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		public void ExecuteShellCommand ( String command, IShellOutputReceiver receiver ) {
			ExecuteShellCommand ( command, receiver, new object[] { } );
		}

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="timeout">The timeout.</param>
		public void ExecuteShellCommand ( String command, IShellOutputReceiver receiver, int timeout ) {
			ExecuteShellCommand ( command, receiver, new object[] { } );
		}


		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="commandArgs">The command args.</param>
		public void ExecuteShellCommand ( String command, IShellOutputReceiver receiver, params object[] commandArgs ) {
			AdbHelper.Instance.ExecuteRemoteCommand ( AndroidDebugBridge.SocketAddress, string.Format ( command, commandArgs ), this, receiver );
		}

		/// <summary>
		/// Executes a shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="timeout">The timeout.</param>
		/// <param name="commandArgs">The command args.</param>
		public void ExecuteShellCommand ( String command, IShellOutputReceiver receiver, int timeout, params object[] commandArgs ) {
			AdbHelper.Instance.ExecuteRemoteCommand ( AndroidDebugBridge.SocketAddress, string.Format ( command, commandArgs ), this, receiver );
		}


		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="timeout">The timeout.</param>
		public void ExecuteRootShellCommand ( String command, IShellOutputReceiver receiver, int timeout ) {
			ExecuteRootShellCommand ( command, receiver, timeout, new object[] { } );
		}

		/// <summary>
		/// Executes a shell command on the device as root, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command to execute</param>
		/// <param name="receiver">The receiver object getting the result from the command.</param>
		public void ExecuteRootShellCommand ( String command, IShellOutputReceiver receiver ) {
			ExecuteRootShellCommand ( command, receiver, int.MaxValue );
		}

		/// <summary>
		/// Executes a root shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="commandArgs">The command args.</param>
		public void ExecuteRootShellCommand ( String command, IShellOutputReceiver receiver, params object[] commandArgs ) {
			ExecuteRootShellCommand ( command, receiver, int.MaxValue, commandArgs );
		}

		/// <summary>
		/// Executes a root shell command on the device, and sends the result to a receiver.
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="timeout">The timeout.</param>
		/// <param name="commandArgs">The command args.</param>
		public void ExecuteRootShellCommand ( String command, IShellOutputReceiver receiver, int timeout, params object[] commandArgs ) {
			AdbHelper.Instance.ExecuteRemoteRootCommand ( AndroidDebugBridge.SocketAddress, string.Format ( command, commandArgs ), this, receiver, timeout );
		}


		/// <summary>
		/// Runs the event log service.
		/// </summary>
		/// <param name="receiver">The receiver.</param>
		public void RunEventLogService ( LogReceiver receiver ) {
			AdbHelper.Instance.RunEventLogService ( AndroidDebugBridge.SocketAddress, this, receiver );
		}

		/// <summary>
		/// Runs the log service.
		/// </summary>
		/// <param name="logname">The logname.</param>
		/// <param name="receiver">The receiver.</param>
		public void RunLogService ( String logname, LogReceiver receiver ) {
			AdbHelper.Instance.RunLogService ( AndroidDebugBridge.SocketAddress, this, logname, receiver );
		}

		/// <summary>
		/// Creates a port forwarding between a local and a remote port.
		/// </summary>
		/// <param name="localPort">the local port to forward</param>
		/// <param name="remotePort">the remote port.</param>
		/// <returns><code>true</code> if success.</returns>
		public bool CreateForward ( int localPort, int remotePort ) {
			try {
				return AdbHelper.Instance.CreateForward ( AndroidDebugBridge.SocketAddress, this, localPort, remotePort );
			} catch ( IOException e ) {
				Log.w ( "ddms", e );
				return false;
			}
		}
	
		
		/// <summary>
 		/// Creates a reverse port forwarding between a local and a remote port.
 		/// </summary>
 		/// <param name="remotePort">the remote port to forward</param>
 		/// <param name="localPort">the local port.</param>
 		/// <returns><code>true</code> if success.</returns>
 		public bool CreateReverseForward ( int remotePort, int localPort )
 		{
 			try {
 				return AdbHelper.Instance.CreateReverseForward(AndroidDebugBridge.SocketAddress, this, remotePort, localPort);
 			} catch(IOException e) {
 				Log.w("ddms", e);
 				return false;
 			}
 		}
 
		/// <summary>
		/// Removes a port forwarding between a local and a remote port.
		/// </summary>
		/// <param name="localPort">the local port to forward</param>
		/// <returns>
		///   <code>true</code> if success.
		/// </returns>
		public bool RemoveForward ( int localPort ) {
			try {
				return AdbHelper.Instance.RemoveForward ( AndroidDebugBridge.SocketAddress, this, localPort );
			} catch ( IOException e ) {
				Log.w ( "ddms", e );
				return false;
			}
		}

		/*
		public String GetClientName ( int pid ) {
			lock ( ClientList ) {
				foreach ( Client c in ClientList ) {
					if ( c.ClientData ( ).Pid == pid ) {
						return c.ClientData.ClientDescription;
					}
				}
			}

			return null;
		}

		DeviceMonitor Monitor { get; private set; }

		void AddClient ( Client client ) {
			lock ( ClientList ) {
				ClientList.Add ( client );
			}
		}

		List<Client> ClientList { get; private set; }

		bool HasClient ( int pid ) {
			lock ( ClientList ) {
				foreach ( Client client in ClientList ) {
					if ( client.ClientData.Pid == pid ) {
						return true;
					}
				}
			}

			return false;
		}

		void ClearClientList ( ) {
			lock ( ClientList ) {
				ClientList.Clear ( );
			}
		}
		
		SocketChannel ClientMonitoringSocket { get; set; }

		void RemoveClient ( Client client, bool notify ) {
			Monitor.AddPortToAvailableList ( client.DebuggerListenPort );
			lock ( ClientList ) {
				ClientList.Remove ( client );
			}
			if ( notify ) {
				Monitor.Server.DeviceChanged ( this, CHANGE_CLIENT_LIST );
			}
		}

		void Update ( int changeMask ) {
			Monitor.Server.DeviceChanged ( this, changeMask );
		}

		void Update ( Client client, int changeMask ) {
			Monitor.Server.ClientChanged ( client, changeMask );
		}
*/

		/// <summary>
		/// Installs an Android application on device.
		/// This is a helper method that combines the syncPackageToDevice, installRemotePackage,
		/// and removePackage steps
		/// </summary>
		/// <param name="packageFilePath">the absolute file system path to file on local host to install</param>
		/// <param name="reinstall">set to <code>true</code>if re-install of app should be performed</param>
		public void InstallPackage ( String packageFilePath, bool reinstall ) {
			String remoteFilePath = SyncPackageToDevice ( packageFilePath );
			InstallRemotePackage ( remoteFilePath, reinstall );
			RemoveRemotePackage ( remoteFilePath );
		}

		/// <summary>
		/// Pushes a file to device
		/// </summary>
		/// <param name="localFilePath">the absolute path to file on local host</param>
		/// <returns>destination path on device for file</returns>
		/// <exception cref="IOException">if fatal error occurred when pushing file</exception>
		public String SyncPackageToDevice ( String localFilePath ) {
			try {
				String packageFileName = Path.GetFileName ( localFilePath );
				// only root has access to /data/local/tmp/... not sure how adb does it then...
				// workitem: 16823
				// workitem: 19711
				String remoteFilePath = LinuxPath.Combine ( TEMP_DIRECTORY_FOR_INSTALL, packageFileName );
				Log.d ( packageFileName, String.Format ( "Uploading {0} onto device '{1}'", packageFileName, SerialNumber ) );

				SyncService sync = SyncService;
				if ( sync != null ) {
					String message = String.Format ( "Uploading file onto device '{0}'", SerialNumber );
					Log.d ( LOG_TAG, message );
					SyncResult result = sync.PushFile ( localFilePath, remoteFilePath, SyncService.NullProgressMonitor );

					if ( result.Code != ErrorCodeHelper.RESULT_OK ) {
						throw new IOException ( String.Format ( "Unable to upload file: {0}", result.Message ) );
					}
				} else {
					throw new IOException ( "Unable to open sync connection!" );
				}
				return remoteFilePath;
			} catch ( IOException e ) {
				Log.e ( LOG_TAG, String.Format ( "Unable to open sync connection! reason: {0}", e.Message ) );
				throw;
			}
		}

		/// <summary>
		/// Installs the application package that was pushed to a temporary location on the device.
		/// </summary>
		/// <param name="remoteFilePath">absolute file path to package file on device</param>
		/// <param name="reinstall">set to <code>true</code> if re-install of app should be performed</param>
		public void InstallRemotePackage ( String remoteFilePath, bool reinstall ) {
			InstallReceiver receiver = new InstallReceiver ( );
			FileEntry entry = FileListingService.FindFileEntry ( remoteFilePath );
			String cmd = String.Format ( "pm install {1}{0}", entry.FullEscapedPath, reinstall ? "-r " : String.Empty );
			ExecuteShellCommand ( cmd, receiver );

			if ( !String.IsNullOrEmpty ( receiver.ErrorMessage ) ) {
				throw new PackageInstallationException ( receiver.ErrorMessage );
			}
		}


		/// <summary>
		/// Remove a file from device
		/// </summary>
		/// <param name="remoteFilePath">path on device of file to remove</param>
		/// <exception cref="IOException">if file removal failed</exception>
		public void RemoveRemotePackage ( String remoteFilePath ) {
			// now we delete the app we sync'ed
			try {
				ExecuteShellCommand ( "rm " + remoteFilePath, NullOutputReceiver.Instance );
			} catch ( IOException e ) {
				Log.e ( LOG_TAG, String.Format ( "Failed to delete temporary package: {0}", e.Message ) );
				throw e;
			}
		}

		/// <summary>
		/// Uninstall an package from the device.
		/// </summary>
		/// <param name="packageName">Name of the package.</param>
		/// <exception cref="PackageInstallationException"></exception>
		/// <exception cref="IOException"></exception>
		public void UninstallPackage ( String packageName ) {
			InstallReceiver receiver = new InstallReceiver ( );
			ExecuteShellCommand ( String.Format ( "pm uninstall {0}", packageName ), receiver );
			if ( !String.IsNullOrEmpty ( receiver.ErrorMessage ) ) {
				throw new PackageInstallationException ( receiver.ErrorMessage );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:StateChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		internal void OnStateChanged ( EventArgs e ) {
			if ( this.StateChanged != null ) {
				this.StateChanged ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:BuildInfoChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		internal void OnBuildInfoChanged ( EventArgs e ) {
			if ( this.BuildInfoChanged != null ) {
				this.BuildInfoChanged ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:ClientListChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		internal void OnClientListChanged ( EventArgs e ) {
			if ( this.ClientListChanged != null ) {
				this.ClientListChanged ( this, e );
			}
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Log.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public sealed class Log {
		/// <summary>
		/// Gets or sets the level.
		/// </summary>
		/// <value>The level.</value>
		public static LogLevel.LogLevelInfo Level { get; set; }

		/// <summary>
		/// Gets or sets the <see cref="ILogOutput">LogOutput</see>
		/// </summary>
		public static ILogOutput LogOutput { get; set; }

		/// <summary>
		/// 
		/// </summary>
		private static char[] SpaceLine = new char[72];
		/// <summary>
		/// 
		/// </summary>
		private static readonly char[] HEXDIGIT = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		/// <summary>
		/// Static Initializer for the <see cref="Log"/> class.
		/// </summary>
		static Log ( ) {
			/* prep for hex dump */
			int i = SpaceLine.Length - 1;
			while ( i >= 0 )
				SpaceLine[i--] = ' ';
			SpaceLine[0] = SpaceLine[1] = SpaceLine[2] = SpaceLine[3] = '0';
			SpaceLine[4] = '-';
			Level = DdmPreferences.LogLevel;
		}

		/// <summary>
		/// Cerates a new Instance of <see cref="Log"/>
		/// </summary>
		private Log ( ) {

		}

		/// <summary>
		/// 
		/// </summary>
		sealed class Config {
			/// <summary>
			/// Log Verbose
			/// </summary>
			public const bool LOGV = true;
			/// <summary>
			/// Log Debug
			/// </summary>
			public const bool LOGD = true;
		};

		/// <summary>
		/// Outputs a Verbose level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output</param>
		public static void v ( String tag, String message ) {
			WriteLine ( LogLevel.Verbose, tag, message );
		}

		/// <summary>
		/// Outputs a Verbose level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="format">The message to output format string.</param>
		/// <param name="args">The values for the format message</param>
		public static void v ( String tag, String format, params object[] args ) {
			WriteLine ( LogLevel.Verbose, tag, String.Format ( format, args ) );
		}

		/// <summary>
		/// Outputs a Debug level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output</param>
		public static void d ( String tag, String message ) {
			WriteLine ( LogLevel.Debug, tag, message );
		}

		/// <summary>
		/// Outputs a Debug level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="format">The message to output format string.</param>
		/// <param name="args">The values for the format message</param>
		public static void d ( String tag, String format, params object[] args ) {
			WriteLine ( LogLevel.Debug, tag, String.Format ( format, args ) );
		}

		/// <summary>
		/// Outputs a Info level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message.</param>
		public static void i ( String tag, String message ) {
			WriteLine ( LogLevel.Info, tag, message );
		}

		/// <summary>
		/// Outputs a Info level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="format">The message to output format string.</param>
		/// <param name="args">The values for the format message</param>
		public static void i ( String tag, String format, params object[] args ) {
			WriteLine ( LogLevel.Info, tag, String.Format ( format, args ) );
		}

		/// <summary>
		/// Outputs a Warn level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output.</param>
		public static void w ( String tag, String message ) {
			WriteLine ( LogLevel.Warn, tag, message );
		}

		/// <summary>
		/// Outputs a Warn level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="format">The message to output format string.</param>
		/// <param name="args">The values for the format message</param>
		public static void w ( String tag, String format, params object[] args ) {
			WriteLine ( LogLevel.Warn, tag, String.Format ( format, args ) );
		}

		/// <summary>
		/// Outputs a Warn level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="exception">The exception to warn</param>
		public static void w ( String tag, Exception exception ) {
			if ( exception != null ) {
				w ( tag, exception.ToString ( ) );
			}
		}

		/// <summary>
		/// Outputs a Warn level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output.</param>
		/// <param name="exception">The exception to warn</param>
		public static void w ( String tag, String message, Exception exception ) {
			w ( tag, "{0}\n{1}", message, exception );
		}

		/// <summary>
		/// Outputs a Error level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output.</param>
		/// <gist id="f4fa3525f899e5461d4e" />
		public static void e ( String tag, String message ) {
			WriteLine ( LogLevel.Error, tag, message );
		}

		/// <summary>
		/// Outputs a Error level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="format">The message to output format string.</param>
		/// <param name="args">The values for the format message</param>
		/// <gist id="16a731d7e4f074fca809" />
		public static void e ( String tag, String format, params object[] args ) {
			WriteLine ( LogLevel.Error, tag, String.Format ( format, args ) );
		}

		/// <summary>
		/// Outputs a Error level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="exception">The exception to warn</param>
		/// <gist id="4e0438f59a00d57af4ef"/>
		public static void e ( String tag, Exception exception ) {
			if ( exception != null ) {
				e ( tag, exception.ToString ( ) );
			}
		}

		/// <summary>
		/// Outputs a Error level message.
		/// </summary>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output.</param>
		/// <param name="exception">The exception to warn</param>
		/// <gist id="90b6664f4dd84da50b27" />
		public static void e ( String tag, String message, Exception exception ) {
			e ( tag, "{0}\n{1}", message, exception );
		}


		/// <summary>
		/// Outputs a log message and attempts to display it in a dialog.
		/// </summary>
		/// <param name="logLevel">The log level</param>
		/// <param name="tag">The tag associated with the message.</param>
		/// <param name="message">The message to output.</param>
		public static void LogAndDisplay ( LogLevel.LogLevelInfo logLevel, String tag, String message ) {
			if ( LogOutput != null ) {
				LogOutput.WriteAndPromptLog ( logLevel, tag, message );
			} else {
				WriteLine ( logLevel, tag, message );
			}
		}


		/// <summary>
		/// Dump the entire contents of a byte array with DEBUG priority.
		/// </summary>
		/// <param name="tag"></param>
		/// <param name="level"></param>
		/// <param name="data"></param>
		/// <param name="offset"></param>
		/// <param name="length"></param>
		/// <remarks>
		/// Local addition.  Output looks like:
		/// 1230- 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff  0123456789abcdef
		/// Uses no string concatenation; creates one String object per line.
		/// </remarks>
		internal static void HexDump ( String tag, LogLevel.LogLevelInfo level, byte[] data, int offset, int length ) {

			int kHexOffset = 6;
			int kAscOffset = 55;
			char[] line = new char[SpaceLine.Length];
			int addr, baseAddr, count;
			int i, ch;
			bool needErase = true;

			//Log.w(tag, "HEX DUMP: off=" + offset + ", length=" + length);

			baseAddr = 0;
			while ( length != 0 ) {
				if ( length > 16 ) {
					// full line
					count = 16;
				} else {
					// partial line; re-copy blanks to clear end
					count = length;
					needErase = true;
				}

				if ( needErase ) {
					Array.Copy ( SpaceLine, 0, line, 0, SpaceLine.Length );
					needErase = false;
				}

				// output the address (currently limited to 4 hex digits)
				addr = baseAddr;
				addr &= 0xffff;
				ch = 3;
				while ( addr != 0 ) {
					line[ch] = HEXDIGIT[addr & 0x0f];
					ch--;
					addr >>= 4;
				}

				// output hex digits and ASCII chars
				ch = kHexOffset;
				for ( i = 0; i < count; i++ ) {
					byte val = data[offset + i];

					line[ch++] = HEXDIGIT[( val >> 4 ) & 0x0f];
					line[ch++] = HEXDIGIT[val & 0x0f];
					ch++;

					if ( val >= 0x20 && val < 0x7f )
						line[kAscOffset + i] = (char)val;
					else
						line[kAscOffset + i] = '.';
				}

				WriteLine ( level, tag, new String ( line ) );

				// advance to next chunk of data
				length -= count;
				offset += count;
				baseAddr += count;
			}

		}


		/// <summary>
		/// Dump the entire contents of a byte array with DEBUG priority.
		/// </summary>
		/// <param name="data"></param>
		internal static void HexDump ( byte[] data ) {
			HexDump ( "ddms", LogLevel.Debug, data, 0, data.Length );
		}

		/// <summary>
		/// prints to stdout; could write to a log window
		/// </summary>
		/// <param name="logLevel"></param>
		/// <param name="tag"></param>
		/// <param name="message"></param>
		private static void WriteLine ( LogLevel.LogLevelInfo logLevel, String tag, String message ) {
			if ( logLevel.Priority >= Level.Priority ) {
				if ( LogOutput != null ) {
					LogOutput.Write ( logLevel, tag, message );
				} else {
					Write ( logLevel, tag, message );
				}
			}
		}

		/// <summary>
		/// Prints a log message.
		/// </summary>
		/// <param name="logLevel"></param>
		/// <param name="tag"></param>
		/// <param name="message"></param>
		public static void Write ( LogLevel.LogLevelInfo logLevel, String tag, String message ) {
			Console.Write ( GetLogFormatString ( logLevel, tag, message ) );
		}

		/// <summary>
		/// Formats a log message.
		/// </summary>
		/// <param name="logLevel"></param>
		/// <param name="tag"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		public static String GetLogFormatString ( LogLevel.LogLevelInfo logLevel, String tag, String message ) {
			long msec = DateTime.UtcNow.ToUnixEpoch ( );
			return String.Format ( "{0:00}:{1:00} {2}/{3}: {4}\n", ( msec / 60000 ) % 60, ( msec / 1000 ) % 60,
							logLevel.Letter, tag, message );
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/BusyBox.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Managed.Adb.IO;
using MoreLinq;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;

namespace Managed.Adb {
	/// <summary>
	/// A class to help with working with BusyBox
	/// </summary>
	public class BusyBox {
		/// <summary>
		/// 
		/// </summary>
		private const String BUSYBOX_BIN = "/data/local/bin/";
		/// <summary>
		/// 
		/// </summary>
		private const String BUSYBOX_COMMAND = "busybox";

		/// <summary>
		/// Initializes a new instance of the <see cref="BusyBox"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public BusyBox ( Device device ) {
			this.Device = device;
			Version = new System.Version ( "0.0.0.0" );
			Commands = new List<String> ( );
			CheckForBusyBox ( );

		}

		/// <summary>
		/// Attempts to install on the device
		/// </summary>
		/// <param name="busybox">The path to the busybox binary to install.</param>
		/// <returns><c>true</c>, if successful; otherwise, <c>false</c></returns>
		public bool Install ( string busybox ) {
			busybox.ThrowIfNullOrWhiteSpace ( "busybox" );

			FileEntry bb = null;

			try {
				Device.ExecuteShellCommand ( BUSYBOX_COMMAND, NullOutputReceiver.Instance );
				return true;
			} catch {
				// we are just checking if it is already installed so we really expect it to wind up here.
			}

			try {
				MountPoint mp = Device.MountPoints["/data"];
				bool isRO = mp.IsReadOnly;
				Device.RemountMountPoint ( Device.MountPoints["/data"], false );

				FileEntry path = null;
				try {
					path = Device.FileListingService.FindFileEntry ( BUSYBOX_BIN );
				} catch ( FileNotFoundException ) {
					// path doesn't exist, so we make it.
					Device.FileSystem.MakeDirectory ( BUSYBOX_BIN );
					// attempt to get the FileEntry after the directory has been made
					path = Device.FileListingService.FindFileEntry ( BUSYBOX_BIN );
				}

				Device.FileSystem.Chmod ( path.FullPath, "0755" );

				String bbPath = LinuxPath.Combine ( path.FullPath, BUSYBOX_COMMAND );

				Device.FileSystem.Copy ( busybox, bbPath );


				bb = Device.FileListingService.FindFileEntry ( bbPath );
				Device.FileSystem.Chmod ( bb.FullPath, "0755" );

				Device.ExecuteShellCommand ( "{0}/busybox --install {0}", new ConsoleOutputReceiver ( ), path.FullPath );

				// check if this path exists in the path already
				if ( Device.EnvironmentVariables.ContainsKey ( "PATH" ) ) {
					var paths = Device.EnvironmentVariables["PATH"].Split ( ':' );
					var found = paths.Where ( p => String.Compare ( p, BUSYBOX_BIN, false ) == 0 ).Count ( ) > 0;

					// we didnt find it, so add it.
					if ( !found ) {
						// this doesn't seem to actually work
						Device.ExecuteShellCommand ( @"echo \ Mad Bee buxybox >> /init.rc", NullOutputReceiver.Instance );
						Device.ExecuteShellCommand ( @"echo export PATH={0}:\$PATH >> /init.rc", NullOutputReceiver.Instance, BUSYBOX_BIN );
					}
				}


				if ( mp.IsReadOnly != isRO ) {
					// Put it back, if we changed it
					Device.RemountMountPoint ( mp, isRO );
				}

				Device.ExecuteShellCommand ( "sync", NullOutputReceiver.Instance );
			} catch ( Exception ) {
				throw;
			}

			CheckForBusyBox ( );
			return true;
		}

		/// <summary>
		/// Checks for busy box.
		/// </summary>
		private void CheckForBusyBox ( ) {
			if ( this.Device.IsOnline ) {
				try {
					Commands.Clear ( );
					Device.ExecuteShellCommand ( BUSYBOX_COMMAND, new BusyBoxCommandsReceiver ( this ) );
					Available = true;
				} catch ( FileNotFoundException ) {
					Available = false;
				}
			} else {
				Available = false;
			}
		}

		/// <summary>
		/// Executes a busybox command on the device
		/// </summary>
		/// <param name="command"></param>
		/// <param name="receiver"></param>
		/// <param name="commandArgs"></param>
		public void ExecuteShellCommand( String command, IShellOutputReceiver receiver, params object[] commandArgs ) {
			command.ThrowIfNullOrWhiteSpace ( "command" );
			var cmd = String.Format ( "{0} {1}", BUSYBOX_COMMAND, String.Format ( command, commandArgs ) );
			Log.d ( "executing: {0}", cmd );
			AdbHelper.Instance.ExecuteRemoteCommand ( AndroidDebugBridge.SocketAddress, cmd, this.Device, receiver );
		}

		/// <summary>
		/// Executes a busybox command on the device as root
		/// </summary>
		/// <param name="command">The command.</param>
		/// <param name="receiver">The receiver.</param>
		/// <param name="commandArgs">The command args.</param>
		public void ExecuteRootShellCommand( String command, IShellOutputReceiver receiver, params object[] commandArgs ) {
			command.ThrowIfNullOrWhiteSpace ( "command" );
			var cmd = String.Format ( "{0} {1}", BUSYBOX_COMMAND, String.Format ( command, commandArgs ) );
			Log.d ( "executing (su): {0}", cmd );
			AdbHelper.Instance.ExecuteRemoteRootCommand ( AndroidDebugBridge.SocketAddress, cmd, this.Device, receiver );
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		public Device Device { get; set; }
		/// <summary>
		/// Gets if busybox is available on this device.
		/// </summary>
		public bool Available { get; private set; }
		/// <summary>
		/// Gets the version of busybox
		/// </summary>
		public Version Version { get; internal set; }
		/// <summary>
		/// Gets a collection of the supported commands
		/// </summary>
		public List<String> Commands { get; private set; }

		/// <summary>
		/// Gets if the specified command name is supported by this version of busybox
		/// </summary>
		/// <param name="command">The command name to check</param>
		/// <returns><c>true</c>, if supported; otherwise, <c>false</c>.</returns>
		public bool Supports ( String command ) {
			command.ThrowIfNullOrWhiteSpace ( "command" );

			if ( Available && ( Commands == null || Commands.Count == 0 ) ) {
				CheckForBusyBox ( );
			}

			return Commands.Where( c => String.Compare(c,command,false) == 0).FirstOrDefault() != null;
		}

		/// <summary>
		/// 
		/// </summary>
		private class BusyBoxCommandsReceiver : MultiLineReceiver {
			/// <summary>
			/// The busybox version regex pattern
			/// </summary>
			private const String BB_VERSION_PATTERN = @"^BusyBox\sv(\d{1,}\.\d{1,}\.\d{1,})";
			/// <summary>
			/// the busybox commands list regex pattern
			/// </summary>
			private const String BB_FUNCTIONS_PATTERN = @"(?:([\[a-z0-9]+)(?:,\s*))";

			public BusyBoxCommandsReceiver ( BusyBox bb )
				: base ( ) {
				TrimLines = true;
				BusyBox = bb;
			}

			/// <summary>
			/// Gets or sets the busy box.
			/// </summary>
			/// <value>
			/// The busy box.
			/// </value>
			private BusyBox BusyBox { get; set; }

			/// <summary>
			/// Processes the new lines.
			/// </summary>
			/// <param name="lines">The lines.</param>
			/// <workitem id="16000">Issues w/ BusyBox.cs/ProcessNewLines()</workitem>
			protected override void ProcessNewLines ( string[] lines ) {
				Match match = null;
				int state = 0;
				foreach ( var line in lines ) {
					if ( string.IsNullOrWhiteSpace(line) ) {
						continue;
					}
					switch ( state ) {
						case 0:
							match = line.Match ( BB_VERSION_PATTERN, RegexOptions.Compiled | RegexOptions.IgnoreCase );
							if ( match.Success ) {
								BusyBox.Version = new Version ( match.Groups[1].Value );
								state = 1;
								continue;
							}
							break;
						case 1:
							if ( line.Contains ( "defined functions" ) ) {
								state = 2;
							}
							break;
						case 2:
							match = line.Trim ( ).Match ( BB_FUNCTIONS_PATTERN, RegexOptions.Compiled );
							while ( match.Success ) {
								BusyBox.Commands.Add ( match.Groups[1].Value.Trim ( ) );
								match = match.NextMatch ( );
							}
							break;
					}
				}
			}
		}

	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/PermissionDeniedException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="System.Exception" />
	public class PermissionDeniedException : Exception {

		/// <summary>
		/// Initializes a new instance of the <see cref="PermissionDeniedException"/> class.
		/// </summary>
		public PermissionDeniedException( )
			: base ( "Permission to access the specified resource was denied." ) {
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="PermissionDeniedException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		public PermissionDeniedException( String message )
			: base ( message ) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="PermissionDeniedException"/> class.
		/// </summary>
		/// <param name="serializationInfo">The serialization info.</param>
		/// <param name="context">The context.</param>
		public PermissionDeniedException( SerializationInfo serializationInfo,StreamingContext context) : base(serializationInfo,context) {

		}

		/// <summary>
		/// Initializes a new instance of the <see cref="PermissionDeniedException"/> class.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="innerException">The inner exception.</param>
		public PermissionDeniedException( String message, Exception innerException )
			: base ( message, innerException ) {

		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/MethodModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Camalot.Common.Extensions;
using Madb.Site.Extensions;
namespace Madb.Site.Models.Documentation {
	public class MethodModel {
		public MethodModel() {
			Parameters = new List<ParameterModel>();
			GenericParameters = new List<TypeModel>();
		}
		public string Name { get; set; }
		public Xml.Member Documentation { get; set; }
		public string XmlName { get; set; }
		public bool Ignore { get { return Documentation != null && Documentation.Ignore; } }
		public Type ReturnType { get; set; }
		public Type Parent { get; set; }
		public IList<ParameterModel> Parameters { get; set; }
		public IList<TypeModel> GenericParameters { get; set; }
		public bool IsStatic { get; set; }
		public bool IsExtension {
			get {
				return ExtensionOf != null;
			}
		}
		public Type ExtensionOf { get; set; }

		public string Id {
			get {
				return "{0}.{1}".With(Parent.ToSafeFullName(), Name).Slug();
			}
		}

		public override string ToString() {
			if(ExtensionOf == null) {
				return "{0}{2} ( {1} )".With(Name, String.Join(", ", Parameters.Select(p => p.ToString())), GenericParameters != null && GenericParameters.Count > 0 ? "<{0}>".With(String.Join(", ", GenericParameters.Select(g => g.ToString()))) : "");
			} else {
				return "{0}{2} ( {1} )".With(
					Name,
					String.Join(", ", Parameters.Skip(1).Select(p => p.ToString())),
					GenericParameters != null && GenericParameters.Count > 0 ? "<{0}>".With(String.Join(", ", GenericParameters.Select(g => g.ToString()))) : ""
				);
			}
		}
	}
}

<|start_filename|>Managed.AndroidDebugBridge/ISyncProgressMonitor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// Classes which implement this interface provide methods that deal with displaying transfer progress.
	/// </summary>
	public interface ISyncProgressMonitor {
		/// <summary>
		/// Sent when the transfer starts
		/// </summary>
		/// <param name="totalWork">the total amount of work.</param>
		void Start ( long totalWork );

		/// <summary>
		/// Sent when the transfer is finished or interrupted.
		/// </summary>
		void Stop ( );

		/// <summary>
		/// Sent to query for possible cancellation.
		/// </summary>
		/// <returns><c>true</c> if the transfer should be stopped; otherwise, false</returns>
		bool IsCanceled { get; }

		/// <summary>
		/// Sent when a sub task is started.
		/// </summary>
		/// <param name="source">The source.</param>
		/// <param name="destination">the destination.</param>
		void StartSubTask ( string source, string destination );

		/// <summary>
		/// Sent when some progress have been made.
		/// </summary>
		/// <param name="work">the amount of work done.</param>
		void Advance ( long work );
	}
}


<|start_filename|>Madb.Site/Views/Shared/_DirectLink.cshtml<|end_filename|>
﻿@model string

<a href="#@(Model)" class="text-muted"><i class="fa fa-anchor"></i></a>

<|start_filename|>Managed.AndroidDebugBridge/Conversion/Endianness.cs<|end_filename|>
/*
"Miscellaneous Utility Library" Software License

Version 1.0

Copyright (c) 2004-2008 <NAME> and <NAME>.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if
any, must include the following acknowledgment:

"This product includes software developed by <NAME>
and <NAME>. Contact <EMAIL>, or see 
http://www.pobox.com/~skeet/)."

Alternately, this acknowledgment may appear in the software itself,
if and wherever such third-party acknowledgments normally appear.

4. The name "Miscellaneous Utility Library" must not be used to endorse 
or promote products derived from this software without prior written 
permission. For written permission, please contact <EMAIL>.

5. Products derived from this software may not be called 
"Miscellaneous Utility Library", nor may "Miscellaneous Utility Library"
appear in their name, without prior written permission of Jon Skeet.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. 

*/
namespace Managed.Adb.Conversion
{
	/// <summary>
	/// Endianness of a converter
	/// </summary>
	public enum Endianness
	{
		/// <summary>
		/// Little endian - least significant byte first
		/// </summary>
		LittleEndian,
		/// <summary>
		/// Big endian - most significant byte first
		/// </summary>
		BigEndian
	}
}


<|start_filename|>Madb.Site/Views/Documentation/_AboutPartial.cshtml<|end_filename|>
﻿<div id="about">
	@(Html.Partial("_AdPartial"))
	<div class="panel panel-success pan">
		<div class="panel-heading"><h1 class="zero lowercase"><i class="fa fa-question-circle mrm"></i>About</h1></div>
		<div class="panel-body">
			<p>
				This is a Managed port of the Android Debug Bridge to allow communication from .NET applications to Android devices.
				This wraps the same methods that the ddms uses to directly communicate with ADB. This gives more flexibility to the developer
				than launching an adb process and executing one of its built in commands.
			</p>
		</div>
	</div>
</div>


<|start_filename|>Managed.AndroidDebugBridge/DdmPreferences.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <ignore>true</ignore>
	public static class DdmPreferences {
		/** Default value for thread update flag upon client connection. */
		public const bool DEFAULT_INITIAL_THREAD_UPDATE = false;
		/** Default value for heap update flag upon client connection. */
		public const bool DEFAULT_INITIAL_HEAP_UPDATE = false;
		/** Default value for the selected client debug port */
		public const int DEFAULT_SELECTED_DEBUG_PORT = 8700;
		/** Default value for the debug port base */
		public const int DEFAULT_DEBUG_PORT_BASE = 8600;
		/** Default value for the logcat {@link LogLevel} */
		public static readonly LogLevel.LogLevelInfo DEFAULT_LOG_LEVEL = Managed.Adb.LogLevel.Error;
		/** Default timeout values for adb connection (milliseconds) */
		public const int DEFAULT_TIMEOUT = 5000; // standard delay, in ms

		private static int _selectedDebugPort;
		private static LogLevel.LogLevelInfo _logLevel;

		/// <summary>
		/// Initializes the <see cref="DdmPreferences"/> class.
		/// </summary>
		static DdmPreferences ( ) {
			Timeout = DEFAULT_TIMEOUT;
			LogLevel = DEFAULT_LOG_LEVEL;
			SelectedDebugPort = DEFAULT_SELECTED_DEBUG_PORT;
			DebugPortBase = DEFAULT_DEBUG_PORT_BASE;
			InitialThreadUpdate = DEFAULT_INITIAL_THREAD_UPDATE;
			InitialHeapUpdate = DEFAULT_INITIAL_HEAP_UPDATE;
		}

		/// <summary>
		/// Gets or sets the timeout.
		/// </summary>
		/// <value>
		/// The timeout.
		/// </value>
		public static int Timeout { get; set; }
		/// <summary>
		/// Gets or sets the log level.
		/// </summary>
		/// <value>
		/// The log level.
		/// </value>
		public static LogLevel.LogLevelInfo LogLevel {
			get {
				return _logLevel;
			}
			set {
				_logLevel = value;
				Log.Level = value ;
			}
		}
		/// <summary>
		/// Gets or sets the debug port base.
		/// </summary>
		/// <value>
		/// The debug port base.
		/// </value>
		public static int DebugPortBase { get; set; }
		/// <summary>
		/// Gets or sets the selected debug port.
		/// </summary>
		/// <value>
		/// The selected debug port.
		/// </value>
		public static int SelectedDebugPort {
			get {
				return _selectedDebugPort;
			}
			set {
				_selectedDebugPort = value;

				MonitorThread monitorThread = MonitorThread.Instance;
				if ( monitorThread != null ) {
					monitorThread.SetDebugSelectedPort ( value );
				}
			}
		}
		/// <summary>
		/// Gets or sets a value indicating whether [initial thread update].
		/// </summary>
		/// <value>
		///   <c>true</c> if [initial thread update]; otherwise, <c>false</c>.
		/// </value>
		public static bool InitialThreadUpdate { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether [initial heap update].
		/// </summary>
		/// <value>
		///   <c>true</c> if [initial heap update]; otherwise, <c>false</c>.
		/// </value>
		public static bool InitialHeapUpdate { get; set; }
	}
}


<|start_filename|>Madb.Site/assets/Scripts/system.toastr.js<|end_filename|>
﻿(function ($, toastr, document, window) {
	"use strict";

	$(function () {
		$("[data-toastr]").each(function (i, item) {
			var self = $(this);
			if (self.data("toastr-setup")) { return; }
			self.data("toastr-setup", true);

			var trigger = self.data("toastr") || "click";
			self.on(trigger, function (event,data) {
				var $t = $(this);
				var type = $t.data("toastr-type") || "success";
				var content = $t.data("toastr-content") || null;
				var text = $t.data("toastr-text") || $(content).html() || null;
				var close = $t.data("toastr-close") || false;
				var position = $t.data("toastr-position") || "top-full-width";
				var showDuration = parseInt($t.data("toastr-show-duration") || "300", 0);
				var hideDuration = parseInt($t.data("toastr-hide-duration") || "1000", 0);
				var timeout = parseInt($t.data("toastr-timeout") || "0", 0);
				var extendedTimeout = parseInt($t.data("toastr-extended-timeout") || "0", 0);
				var showEasing = $.data("toastr-show-easing") || "swing";
				var showMethod = $.data("toastr-show-method") || "slideDown";
				var hideEasing = $.data("toastr-hide-easing") || "linear";
				var hideMethod = $.data("toastr-hide-method") || "slideUp";
				toastr.options = {
					"closeButton": close,
					"debug": false,
					"positionClass": "toast-" + position,
					"onclick": null,
					"showDuration": showDuration,
					"hideDuration": hideDuration,
					"timeOut": timeout,
					"extendedTimeOut": extendedTimeout,
					"showEasing": showEasing,
					"hideEasing": hideEasing,
					"showMethod": showMethod,
					"hideMethod": hideMethod
				};

				toastr[type](text);

			});
		});
	});
	
})(jQuery, window.toastr, document, window);

<|start_filename|>Madb.Site/Models/Documentation/Xml/Assembly.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	public class Assembly {
		[XmlElement("name")]
		public string Name { get; set; }
	}
}

<|start_filename|>Managed.AndroidDebugBridge/Logs/LogEntry.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Logs {
	/// <summary>
	/// 
	/// </summary>
	public sealed class LogEntry {
		/// <summary>
		/// Gets or sets the length.
		/// </summary>
		/// <value>
		/// The length.
		/// </value>
		public int Length { get; set; }
		/// <summary>
		/// Gets or sets the process identifier.
		/// </summary>
		/// <value>
		/// The process identifier.
		/// </value>
		public int ProcessId { get; set; }
		/// <summary>
		/// Gets or sets the thread identifier.
		/// </summary>
		/// <value>
		/// The thread identifier.
		/// </value>
		public int ThreadId { get; set; }
		/// <summary>
		/// Gets or sets the time stamp.
		/// </summary>
		/// <value>
		/// The time stamp.
		/// </value>
		public DateTime TimeStamp { get; set; }
		/// <summary>
		/// Gets or sets the nano seconds.
		/// </summary>
		/// <value>
		/// The nano seconds.
		/// </value>
		public int NanoSeconds { get; set; }
		/// <summary>
		/// Gets or sets the data.
		/// </summary>
		/// <value>
		/// The data.
		/// </value>
		public byte[] Data { get; set; }
	}
}


<|start_filename|>Madb.Site/Models/Documentation/Xml/Simple.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	public class Simple {
		[XmlIgnore]
		public string Value { get; set; }

		[XmlText]
		public XmlNode[] CDataContent {
			get {
				var dummy = new XmlDocument();
				return new XmlNode[] { dummy.CreateCDataSection(Value) };
			}
			set {
				if(value == null) {
					Value = null;
					return;
				}
				Value = string.Join(" ", value.Select(a => a.OuterXml)).Trim();
			}
		}

		public override string ToString() {
			return Value;
		}
	}
}

<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/GetExtension.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class GetExtension {
		[Fact]
		public void WhenPathIsNull_ShouldReturnNull () {
			Assert.Null ( LinuxPath.GetExtension ( null ) );
		}

		[Fact]
		public void WhenPathContainsInvalidCharacter_ShouldThrowArgumentException () {
			var fixture = new Fixture ( );
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x ) {
				try {
					string result = LinuxPath.GetExtension ( "/some/path/{0}-{1}.ext".With ( LinuxPathConsts.InvalidPathChars[x], fixture.Create ( "file-" ) ) );
				} catch ( ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );
		}

		[Fact]
		public void WhenFilePathContainsExtension_ShouldReturnExtension () {
			var fixture = new Fixture ( );
			string result = LinuxPath.GetExtension ( "/some/path/{0}.ext".With (fixture.Create ( "file-" ) ) );
			Assert.Equal ( ".ext", result );
		}

		[Fact]
		public void WhenFilePathDoesNotContainsExtension_ShouldReturnEmpty ( ) {
			var fixture = new Fixture ( );
			string result = LinuxPath.GetExtension ( "/some/path/{0}".With ( fixture.Create ( "file-" ) ) );
			Assert.Equal ( string.Empty, result );
		}

		[Fact]
		public void WhenFilePathEndsWithDot_ShouldReturnEmpty ( ) {
			var fixture = new Fixture ( );
			string result = LinuxPath.GetExtension ( "/some/path/{0}.".With ( fixture.Create ( "file-" ) ) );
			Assert.Equal ( string.Empty, result );
		}

		[Fact]
		public void WhenPathDoesNotFile_ShouldReturnEmpty ( ) {
			var fixture = new Fixture ( );
			string result = LinuxPath.GetExtension ( "/some/path/{0}/".With ( fixture.Create ( "path-" ) ) );
			Assert.Equal ( string.Empty, result );
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/NamespaceModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Camalot.Common.Extensions;

namespace Madb.Site.Models.Documentation {
	public class NamespaceModel {
		public NamespaceModel() {
			Classes = new List<ClassModel>();
			Namespaces = new List<NamespaceModel>();
		}
		public string Name { get; set; }
		public IList<NamespaceModel> Namespaces { get; set; }
		public IList<ClassModel> Classes { get; set; }
		public bool Ignore { get { return Classes.Where(c => !c.Ignore).Count() == 0 && Namespaces.Where(c => !c.Ignore).Count() == 0; } }
		public String AssemblyVersion { get; set; }

		public string Id {
			get {
				return Name.Slug();
			}
		}

		public override string ToString() {
			return this.Name;
		}
	}
}

<|start_filename|>Managed.Adb.Tests/ForManagedAdbExtenstions/Swap32bitFromArray.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForManagedAdbExtenstions {
	public class Swap32bitFromArray {
		[Fact]
		public void WhenValueIsPositive_ShouldReturnInteger ( ) {
			var fixture = new Fixture ( );
			var value = fixture.Create<int> ( );
			var offset = fixture.Create<int> ( );
			var dest = new byte[offset + 4];
			Assert.True ( offset >= 0 );
			ManagedAdbExtenstions.Swap32bitsToArray ( value, dest, offset );

			var result = ManagedAdbExtenstions.Swap32bitFromArray ( dest, offset );
			Assert.Equal ( value, result );
		}


		[Fact]
		public void WhenValueIsZero_ShouldReturnInteger ( ) {
			var fixture = new Fixture ( );
			var value = 0;
			var offset = fixture.Create<int> ( );
			var dest = new byte[offset + 4];
			Assert.True ( offset >= 0 );
			ManagedAdbExtenstions.Swap32bitsToArray ( value, dest, offset );

			var result = ManagedAdbExtenstions.Swap32bitFromArray ( dest, offset );
			Assert.Equal ( value, result );
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/Xml/Param.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	public class Param {
		[XmlAttribute("name")]
		public string Name { get; set; }
		[XmlText]
		public string Value { get; set; }
	}
}


<|start_filename|>Madb.Site/Views/Documentation/Navigation.cshtml<|end_filename|>
﻿@using Madb.Site.Models.Documentation;

@model NamespaceModel
@{
	const int scrollTopOffset = -70;
	var id = ViewContext.ParentActionViewContext.RouteData.Values["id"] == null ? "" : ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString();
	var fullNav = Model.Name.Equals(id, StringComparison.InvariantCultureIgnoreCase);

}

@helper SafeNamespaceName(string ns) {
	if(ns.Equals(Model.Name)) {
		<text>@Model.Name</text>
	} else {
		<text>@ns.Substring(Model.Name.Length + 1)</text>
	}
}


@helper DisplayNamespace(NamespaceModel ns, int offset) {
	if(!ns.Ignore) {
		<li>
			<a data-expandable="click"
				 data-expandable-toggle="nav-expanded"
				 data-expandable-target="ul[data-id='@(ns.Id)']"
				 data-scroll="click"
				 data-scroll-offset="@(offset)"
				 href="@(Url.Action("Index", "Documentation", new { id = Model.Name }))#@ns.Id"
				 title="@ns.ToString()"
				 class="track"><i class="mll mrs fa fa-code"></i><span>@SafeNamespaceName(ns.Name)</span></a>
			@if(ns.Classes.Count > 0) {
				<ul class="nav nested mll" data-id="@ns.Id">
					@foreach(var nsx in ns.Namespaces.Where(m => m.Name != ns.Name)) {
						@DisplayNamespace(nsx, offset)
					}
					@foreach(var pm in ns.Classes) {
						@DisplayClass(pm, offset)
					}
				</ul>
			}
		</li>
	}
}


@helper DisplayRootNamespace(int offset) {
	var root = Model.Namespaces.First(m => m.Name == Model.Name);
	if(!root.Ignore) {
		<li>
			<a data-scroll="click" data-scroll-offset="@(offset)" href="@(Url.Action("Index", "Documentation", new { id = root.Name }))#@root.Id" class="track"><i class="mrs fa fa-code"></i><span>@root.Name</span></a>
			@if(root.Classes.Count > 0 || root.Namespaces.Count > 0) {
				<ul class="nav nested nav-always-expanded">
					@foreach(var ns in Model.Namespaces.Where(m => m.Name != root.Name)) {
						@DisplayNamespace(ns, offset)
					}
					@foreach(var c in root.Classes) {
						@DisplayClass(c,offset)
					}

				</ul>
			}
		</li>
	}
}
@helper DisplayClass(ClassModel cm, int offset) {
	if(!cm.Ignore) {
		<li>
			<a data-expandable="click" 
				 data-expandable-toggle="nav-expanded" 
				 data-expandable-target="ul[data-id='@(cm.Id)']" 
				 data-scroll="click" 
				 data-scroll-offset="@(offset)" 
				 href="@(Url.Action("Index", "Documentation", new { id = Model.Name }))#@cm.Id" title="@cm.ToString()" 
				 class="track"><i class="mll mrs fa fa-bolt"></i><span>@cm.Name</span></a>
			@if(cm.Properties.Count > 0 || cm.Methods.Count > 0) {
				<ul class="nav nested mll" data-id="@cm.Id">
					@foreach(var pm in cm.Properties) {
						@DisplayProperty(pm, offset)
					}
					@foreach(var m in cm.Methods) {
						@DisplayMethod(m, offset)
					}
				</ul>
			}
		</li>
	}
}

@helper DisplayProperty(PropertyModel pm, int offset) {
	if(!pm.Ignore) {
		<li><a data-scroll="click" data-scroll-offset="@(offset)" href="@(Url.Action("Index", "Documentation", new { id = Model.Name }))#@pm.Id" title="@pm.ToString()" class="track"><i class="mll mrs fa fa-asterisk"></i><span>@pm.Name</span></a></li>
	}
}

@helper DisplayMethod(MethodModel mm, int offset) {
	if(!mm.Ignore) {
		<li><a data-scroll="click" data-scroll-offset="@(offset)" href="@(Url.Action("Index", "Documentation", new { id = Model.Name }))#@mm.Id" title="@mm.ToString()" class="track"><i class="mll mrs fa fa-gavel"></i><span>@mm.Name</span></a></li>
	}
}

@if(fullNav) {
	<li>
		@DisplayRootNamespace(scrollTopOffset)
	</li>
} else {
	<li>
		<a data-scroll="click" data-scroll-offset="@(scrollTopOffset)" href="@(Url.Action("Index", "Documentation", new { id = Model.Name }))" class="track"><i class="mrs fa fa-code"></i><span>@Model.Name</span></a>
	</li>
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/ChangeExtensionTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class ChangeExtensionTests {

		[Fact]
		public void WhenPathIsNull_ShouldReturnNull () {
			string result = LinuxPath.ChangeExtension ( null, "ext" );
			Assert.Null ( result );
		}

		/// <summary>
		/// Whens the path contains invalid character_ should throw argument exception.
		/// </summary>
		[Fact]
		public void WhenPathContainsInvalidCharacter_ShouldThrowArgumentException ( ) {
			int errorCount = 0;
			for ( var x = 0; x < LinuxPathConsts.InvalidPathChars.Length; ++x  ) {
				try {
					string result = LinuxPath.ChangeExtension ("/my-invalid-path/f-{0}".With ( LinuxPathConsts.InvalidPathChars[x]), "ext" );
				} catch (ArgumentException ) {
					errorCount++;
				}
			}

			Assert.Equal ( LinuxPathConsts.InvalidPathChars.Length, errorCount );
		}

		[Fact]
		public void WhenPathLengthIsZero_ShouldReturnEmpty () {
			string result = LinuxPath.ChangeExtension ( string.Empty, "ext" );
			Assert.Equal ( string.Empty, result );
		}

		[Fact]
		public void WhenExtensionIsEmpty_ShouldReturnPath ( ) {
			string result = LinuxPath.ChangeExtension ( "/my-path/to/file.ext1", string.Empty );
			Assert.Equal ( "/my-path/to/file.ext1", result );
		}

		[Fact]
		public void WhenExtensionDoesNotStartWithDot_ShouldReturnChangedExtensionWithDot () {
			string result = LinuxPath.ChangeExtension ( "/my-path/to/file.ext1", "ext2" );
			Assert.Equal ( "/my-path/to/file.ext2", result );
		}

		[Fact]
		public void WhenExtensionStartsWithDot_ShouldReturnChangedExtension ( ) {
			string result = LinuxPath.ChangeExtension ( "/my-path/to/file.ext1", ".ext2" );
			Assert.Equal ( "/my-path/to/file.ext2", result );
		}

		[Fact]
		public void WhenPathHasNoExtension_ShouldReturnPathWithExtension ( ) {
			string result = LinuxPath.ChangeExtension ( "/my-path/to/file", ".ext2" );
			Assert.Equal ( "/my-path/to/file.ext2", result );
		}
	}
}


<|start_filename|>Madb.Site/Views/Assets/Gist.cshtml<|end_filename|>
﻿@model String
<div class="gist-container">
	<div class="gist-data-host">
		<div class="button-controls">
			<a title="copy" href="#" data-copy="click" data-copy-target="[data-id='@Model'] .file-data .line-data pre" class="btn btn-round btn-info z-depth-1 mtml mrs"><i class="fa fa-copy"></i></a>
			<a title="view raw" target="_blank" href="//gist.github.com/camalot/@Model/raw/" class="btn btn-round btn-info z-depth-1 mtml"><i class="fa fa-eye"></i></a>
		</div>
		<div data-id="@Model">
			<script src="https://gist.github.com/@(Model).js"></script>
		</div>
	</div>
</div>

<|start_filename|>Madb.Site/assets/Scripts/system.scroll.js<|end_filename|>
﻿(function ($, document, window) {
	"use strict";
	$(function () {
		// smooth scrolling if the jquery scrollTo plugin exists.
		$("a[data-scroll]").each(function () {
			var self = $(this);
			if (self.data("scroll-setup")) { return; }
			self.data("scroll-setup", true);
			var trigger = self.data("scroll") || "click";
			self.on(trigger, function (evt) {
				if ($.scrollTo) {
					var evtx = evt || event;
					var $s = $(this);
					var topOffset = parseInt($s.data("scroll-offset"), 0);
					var target = $(this.hash);
					$.scrollTo(target, { duration: 1000, offset: topOffset });
					evtx.preventDefault();
				}
			});
		});
	});
})(window.jQuery, window.document, window);

<|start_filename|>Managed.AndroidDebugBridge/Receivers/PackageManagerReceiver.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;
using Managed.Adb.Exceptions;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class PackageManagerReceiver : MultiLineReceiver {
		/// <summary>
		/// Pattern to parse the output of the 'pm -lf' command.
		/// The output format looks like:
		/// /data/app/myapp.apk=com.mypackage.myapp
		/// </summary>
		public const String PM_PACKAGE_PATTERN = "^package:(.+?)=(.+)$";

		/// <summary>
		/// Creates an instance of PackageManagerReceiver
		/// </summary>
		/// <param name="device"></param>
		/// <param name="pm"></param>
		public PackageManagerReceiver ( Device device, PackageManager pm ) {
			Device = device;
			PackageManager = pm;
		}

		/// <summary>
		/// Gets or sets the device.
		/// </summary>
		/// <value>
		/// The device.
		/// </value>
		public Device Device { get; set; }
		/// <summary>
		/// Gets or sets the package manager.
		/// </summary>
		/// <value>
		/// The package manager.
		/// </value>
		public PackageManager PackageManager { get; set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			PackageManager.Packages.Clear ( );
			lines.ForEach ( line => {
				if ( line.Trim ( ).Length > 0 ) {
					var m = line.Match ( PackageManagerReceiver.PM_PACKAGE_PATTERN, RegexOptions.Compiled );
					if ( m.Success ) {
						// get the children with that path
						FileEntry entry = null;
						if ( PackageManager.Packages.ContainsKey ( m.Groups[2].Value ) ) {
							entry = PackageManager.Packages[m.Groups[1].Value];
							if ( entry != null ) {
								entry.Info = m.Groups[2].Value;
							}
						} else {
							try {
								entry = FileEntry.Find ( Device, m.Groups[1].Value );
								entry.Info = m.Groups[2].Value;
								PackageManager.Packages.Add ( m.Groups[2].Value, entry );
							} catch ( PermissionDeniedException ) {
								// root required for device packages
								entry = FileEntry.CreateNoPermissions ( Device, m.Groups[1].Value );
								entry.Info = m.Groups[2].Value;
								PackageManager.Packages.Add ( m.Groups[2].Value, entry );
							}
						}
					}
				}
			} );

			/*
			foreach ( String line in lines ) {
				if ( line.Length > 0 ) {
					// get the filepath and package from the line
					Match m = Regex.Match ( line, PackageManagerReceiver.PM_PACKAGE_PATTERN, RegexOptions.Compiled );
					if ( m.Success ) {
						// get the children with that path
						FileEntry entry = null;
						if ( PackageManager.Packages.ContainsKey ( m.Groups[2].Value ) ) {
							entry = PackageManager.Packages[m.Groups[1].Value];
							if ( entry != null ) {
								entry.Info = m.Groups[2].Value;
							}
						} else {
							try {
								entry = FileEntry.Find ( Device, m.Groups[1].Value );
								entry.Info = m.Groups[2].Value;
								PackageManager.Packages.Add ( m.Groups[2].Value, entry );
							} catch ( PermissionDeniedException ) {
								// root required for device packages
								entry = FileEntry.CreateNoPermissions ( Device, m.Groups[1].Value );
								entry.Info = m.Groups[2].Value;
								PackageManager.Packages.Add ( m.Groups[2].Value, entry );
							}
						}
					}
				}
			}*/
		}
	}

	/// <summary>
	/// 
	/// </summary>
	public class PackageManagerListingReceiver : MultiLineReceiver {


		/// <summary>
		/// Initializes a new instance of the <see cref="PackageManagerReceiver"/> class.
		/// </summary>
		/// <param name="entryMap">The entry map.</param>
		/// <param name="receiver">The receiver.</param>
		public PackageManagerListingReceiver ( Dictionary<String, FileEntry> entryMap, IListingReceiver receiver ) {
			this.Map = entryMap;
			this.Receiver = receiver;
		}

		/// <summary>
		/// Gets or sets the map.
		/// </summary>
		/// <value>The map.</value>
		public Dictionary<String, FileEntry> Map { get; set; }
		/// <summary>
		/// Gets or sets the receiver.
		/// </summary>
		/// <value>The receiver.</value>
		public IListingReceiver Receiver { get; set; }

		/// <summary>
		/// Processes the new lines.
		/// </summary>
		/// <param name="lines">The lines.</param>
		protected override void ProcessNewLines ( string[] lines ) {
			foreach ( String line in lines ) {
				if ( line.Length > 0 ) {
					// get the filepath and package from the line
					Match m = Regex.Match ( line, PackageManagerReceiver.PM_PACKAGE_PATTERN, RegexOptions.Compiled );
					if ( m.Success ) {
						// get the children with that path
						FileEntry entry = Map[m.Groups[1].Value];
						if ( entry != null ) {
							entry.Info = m.Groups[2].Value;
							Receiver.RefreshEntry ( entry );
						}
					}
				}
			}

		}
	}
}


<|start_filename|>Madb.Site/Views/Shared/_SideNavPartial.cshtml<|end_filename|>
﻿@using Madb.Site.Models;
@{
	var navPosition = NavigationPositions.Right;
	var scrollTopOffset = -70;
}

<div class="epm-nav-host @(navPosition.ToString().ToLower()) expanded">
	<div class="epm-nav-toggle" title="Close" data-epm-target=".epm-nav" data-epm-toggle="expanded">
		<span class="icon-bar"></span>
		<span class="icon-bar"></span>
		<span class="icon-bar"></span>
	</div>
</div>
<div class="@(navPosition.ToString().ToLower()) epm-nav expanded epm-nav-primary">
	<ul class="nav nav-expanded">
		<li class="no-filter nav-search man mbs pan">
			<div class="form-group man pan">
				<input type="search" placeholder="Search" class="search-field man" />
				<button type="button" class="clear fa fa-search" data-search-icon="fa-search" data-search-title="Search" data-clear-icon="fa-close" data-clear-title="Clear"></button>
			</div>
		</li>
		<li class=""><a data-scroll="click" href="#home"><i class="mrs fa fa-home"></i><span>Home</span></a></li>
		<li class="divider"></li>
		<li><a data-scroll="click" data-scroll-offset="@(scrollTopOffset)" href="#about" class="track"><i class="mrs fa fa-question-circle"></i><span>About</span></a></li>
		<li><a data-scroll="click" data-scroll-offset="@(scrollTopOffset)" href="#nuget" class="track"><i class="mrs fa fa-download"></i><span>Nuget</span></a></li>
		<li class="divider"></li>
		<li><a data-scroll="click" data-scroll-offset="@(scrollTopOffset)" href="#license" class="track"><i class="mrs fa fa-certificate"></i><span>License</span></a></li>
		<li class="divider"></li>
		@Html.Action("Navigation", new { controller = "Documentation", id = "Managed.Adb" })
	</ul>
</div>



<|start_filename|>Madb.Site/assets/styles/google.adsense.css<|end_filename|>
﻿.responsivewin8 { width: 320px; height: 50px; }
@media(min-width: 500px) {
 .responsivewin8 { width: 468px; height: 60px; }
}
@media(min-width: 800px) {
 .responsivewin8 { width: 728px; height: 90px; }
}


<|start_filename|>MadBee.Console/Program.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Managed.Adb;
using System.IO;

namespace MadBee.Console {
	class Program {

		public enum Actions {
			Devices,
			Monitor,
			Start_Server,
			Kill_Server,
		}

		static void Main( string[] arguments ) {
			var args = new Arguments ( arguments );
			AndroidDebugBridge bridge = AndroidDebugBridge.CreateBridge(Path.Combine ( Environment.GetEnvironmentVariable ( "ANDROID_SDK" ), "platform-tools\\adb.exe" ),true);
			foreach ( var item in Enum.GetNames ( typeof ( Actions ) ) ) {
				var actionName = item.Replace ( '_', '-' ).ToLower().Trim();
				if ( args.ContainsKey ( actionName ) ) {
					Actions action = (Actions)Enum.Parse ( typeof ( Actions ), item, true );
					switch ( action ) {
						case Actions.Devices:
							GetDevices ( );
							break;
						case Actions.Monitor:
							bridge.DeviceChanged += delegate ( object sender, DeviceEventArgs e ) {
								System.Console.WriteLine ( "Changed: {0}\t{1}", e.Device.SerialNumber, e.Device.State );
							};
							bridge.DeviceConnected += delegate ( object sender, DeviceEventArgs e ) {
								System.Console.WriteLine ( "{0}\t{1}", e.Device.SerialNumber, e.Device.State );
							};
							bridge.DeviceDisconnected += delegate ( object sender, DeviceEventArgs e ) {
								System.Console.WriteLine ( "{0}\t{1}", e.Device.SerialNumber, e.Device.State );
							};
							System.Console.ReadLine ( );
							break;
						case Actions.Start_Server:
							StartServer ( );
							break;
						case Actions.Kill_Server:
							break;
						default:
							break;
					}
					try {
						AndroidDebugBridge.DisconnectBridge ( );
						bridge.Stop ( );
					} catch ( IOException e ) {
						System.Console.WriteLine ( e.ToString ( ) );
						// ignore
					}

					return;
				}
			}

			PrintUsage ( );
		}

		private static void StartServer( ) {
			
		}

		
		private static void PrintUsage( ) {
			System.Console.WriteLine ( "Print Usage: " );
		}

		private static void GetDevices( ) {
			foreach ( var device in AdbHelper.Instance.GetDevices ( AndroidDebugBridge.SocketAddress ) ) {
				System.Console.WriteLine ( "{0}\t{1}", device.SerialNumber, device.State );
			}
		}


	}
}


<|start_filename|>Managed.AndroidDebugBridge/IDebugPortProvider.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public interface IDebugPortProvider {
		/// <summary>
		/// Returns a non-random debugger port for the specified application running on the specified Device.
		/// </summary>
		/// <param name="device">The device the application is running on.</param>
		/// <param name="appName">The application name, as defined in the <code>AndroidManifest.xml</code> 
		/// <var>package</var> attribute of the <var>manifest</var> node.</param>
		/// <returns>The non-random debugger port or NO_STATIC_PORT if the Client
		/// should use the automatic debugger port provider.</returns>
		int getPort ( IDevice device, String appName );
	}
}


<|start_filename|>Managed.AndroidDebugBridge/AdbHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using Managed.Adb.Exceptions;
using MoreLinq;
using Managed.Adb.IO;
using Managed.Adb.Logs;
using Camalot.Common.Extensions;

// services that are supported by adb: https://github.com/android/platform_system_core/blob/master/adb/SERVICES.TXT
namespace Managed.Adb {

	/// <summary>
	/// 
	/// </summary>
	public enum TransportType {
		/// <summary>
		/// usb
		/// </summary>
		Usb,
		/// <summary>
		/// local
		/// </summary>
		Local,
		/// <summary>
		/// any
		/// </summary>
		Any,
		/// <summary>
		/// host
		/// </summary>
		Host
	}
#pragma warning disable 1584
	/// <summary>
	/// The ADB Helper class
	/// </summary>
	/// <seealso cref="https://github.com/android/platform_system_core/blob/master/adb/SERVICES.TXT">SERVICES.TXT</seealso>
	/// <seealso cref="https://github.com/android/platform_system_core/blob/master/adb/adb_client.c">adb_client.c</seealso>
	/// <seealso cref="https://github.com/android/platform_system_core/blob/master/adb/adb.c">adb.c</seealso>
#pragma warning restore
	public class AdbHelper {
		/// <summary>
		/// Logging tag
		/// </summary>
		private const string TAG = nameof ( AdbHelper );
		/// <summary>
		/// The time to wait
		/// </summary>
		private const int WAIT_TIME = 5;
		/// <summary>
		/// The default encoding
		/// </summary>
		public static String DEFAULT_ENCODING = "ISO-8859-1";

		/// <summary>
		/// Prevents a default instance of the <see cref="AdbHelper"/> class from being created.
		/// </summary>
		private AdbHelper ( ) {

		}

		/// <summary>
		/// 
		/// </summary>
		private static AdbHelper _instance = null;
		/// <summary>
		/// Gets an instance of the AdbHelper.
		/// </summary>
		public static AdbHelper Instance {
			get {
				if ( _instance == null ) {
					_instance = new AdbHelper ( );
				}
				return _instance;
			}
		}

		/// <summary>
		/// Opens the specified address on the device on the specified port.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <param name="port">The port.</param>
		/// <returns>The open socket</returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed submitting request to ADB
		/// or
		/// connection request rejected
		/// </exception>
		public Socket Open ( IPAddress address, IDevice device, int port ) {
			Socket s = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				s.Connect ( address, port );
				s.Blocking = true;
				s.NoDelay = false;

				SetDevice ( s, device );

				byte[] req = CreateAdbForwardRequest ( null, port );
				if ( !Write ( s, req ) ) {
					throw new AdbException ( "failed submitting request to ADB" );
				}
				AdbResponse resp = ReadAdbResponse ( s, false );
				if ( !resp.Okay ) {
					throw new AdbException ( "connection request rejected" );
				}
				s.Blocking = true;
			} catch ( AdbException ) {
				s.Close ( );
				throw;
			}
			return s;
		}

		/// <summary>
		/// Kills the running adb server.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <returns>0 for success; -1 for failure.</returns>
		/// <exception cref="System.IO.IOException">failed asking to kill adb</exception>
		/// <gist id="cbacc7b384ec7a4c27f7" />
		public int KillAdb ( IPEndPoint address ) {
			byte[] request = FormAdbRequest ( "host:kill" );
			using ( var socket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ) ) {
				socket.Connect ( address );
				socket.Blocking = true;
				if ( !Write ( socket, request ) ) {
					throw new IOException ( "failed asking to kill adb" );
				}
				var resp = ReadAdbResponse ( socket, false );
				if ( !resp.IOSuccess || !resp.Okay ) {
					Log.e ( TAG, "Got timeout or unhappy response from ADB req: " + resp.Message );
					socket.Close ( );
					return -1;
				}
				return 0;
			}
		}

#pragma warning disable 1584
		//https://github.com/android/platform_system_core/blob/master/adb/backup_service.c
		/// <summary>
		/// Backups the specified address.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <exception cref="System.IO.IOException">failed asking to backup device</exception>
		/// <seealso cref="https://github.com/android/platform_system_core/blob/master/adb/backup_service.c">backup_service.c</seealso>
#pragma warning restore
		[Obsolete ( "This is not yet functional" )]
		public void Backup ( IPEndPoint address ) {
			byte[] request = FormAdbRequest ( "backup:all" );
			using ( var socket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ) ) {
				socket.Connect ( address );
				socket.Blocking = true;
				if ( !Write ( socket, request ) ) {
					throw new IOException ( "failed asking to backup device" );
				}
				var resp = ReadAdbResponse ( socket, false );
				if ( !resp.IOSuccess || !resp.Okay ) {
					Log.e ( TAG, "Got timeout or unhappy response from ADB req: " + resp.Message );
					socket.Close ( );
					return;
				}

				var data = new byte[6000];
				int count = -1;
				while ( count != 0 ) {
					count = socket.Receive ( data );
					Console.Write ( "received: {0}", count );
				}
			}
		}
#pragma warning disable 1584
		// https://github.com/android/platform_system_core/blob/master/adb/backup_service.c
		/// <summary>
		/// Restores this instance.
		/// </summary>
		/// <exception cref="System.NotImplementedException"></exception>
		/// <seealso cref="https://github.com/android/platform_system_core/blob/master/adb/backup_service.c">backup_service.c</seealso>
#pragma warning restore
		[Obsolete ( "This is not yet functional" )]
		public void Restore ( ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Gets the adb version of the server.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <returns>The version number; or -1 if failure.</returns>
		/// <exception cref="System.IO.IOException">failed asking for adb version</exception>
		/// <gist id="3a130af63ca1f94d0152" />
		public int GetAdbVersion ( IPEndPoint address ) {
			byte[] request = FormAdbRequest ( "host:version" );
			byte[] reply;
			Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				adbChan.Connect ( address );
				adbChan.Blocking = true;
				if ( !Write ( adbChan, request ) )
					throw new IOException ( "failed asking for adb version" );

				AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
				if ( !resp.IOSuccess || !resp.Okay ) {
					Log.e ( TAG, "Got timeout or unhappy response from ADB fb req: " + resp.Message );
					adbChan.Close ( );
					return -1;
				}

				reply = new byte[4];
				if ( !Read ( adbChan, reply ) ) {
					Log.e ( TAG, "error in getting data length" );

					adbChan.Close ( );
					return -1;
				}

				String lenHex = reply.GetString ( AdbHelper.DEFAULT_ENCODING );
				int len = int.Parse ( lenHex, System.Globalization.NumberStyles.HexNumber );

				// the protocol version.
				reply = new byte[len];
				if ( !Read ( adbChan, reply ) ) {
					Log.e ( TAG, "did not get the version info" );

					adbChan.Close ( );
					return -1;
				}

				String sReply = reply.GetString ( AdbHelper.DEFAULT_ENCODING );
				return int.Parse ( sReply, System.Globalization.NumberStyles.HexNumber );

			} catch ( Exception ex ) {
				Log.e ( TAG, ex );
				throw;
			}
		}

		/// <summary>
		/// Creates and connects a new pass-through socket, from the host to a port on the device.
		/// </summary>
		/// <param name="endpoint">The endpoint.</param>
		/// <param name="device">the device to connect to. Can be null in which case the connection will be
		/// to the first available device.</param>
		/// <param name="pid">the process pid to connect to.</param>
		/// <returns>
		/// The Socket
		/// </returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed submitting request to ADB
		/// or
		/// connection request rejected:  + resp.Message
		/// </exception>
		public Socket CreatePassThroughConnection ( IPEndPoint endpoint, Device device, int pid ) {
			Socket socket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				socket.Connect ( endpoint );
				socket.NoDelay = true;

				// if the device is not -1, then we first tell adb we're looking to
				// talk to a specific device
				SetDevice ( socket, device );

				byte[] req = CreateJdwpForwardRequest ( pid );
				// Log.hexDump(req);

				if ( !Write ( socket, req ) )
					throw new AdbException ( "failed submitting request to ADB" ); //$NON-NLS-1$

				AdbResponse resp = ReadAdbResponse ( socket, false /* readDiagString */);
				if ( !resp.Okay )
					throw new AdbException ( "connection request rejected: " + resp.Message ); //$NON-NLS-1$

			} catch ( AdbException ioe ) {
				socket.Close ( );
				throw ioe;
			}

			return socket;
		}

		/// <summary>
		/// Creates the adb forward request.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="port">The port.</param>
		/// <returns></returns>
		public byte[] CreateAdbForwardRequest ( String address, int port ) {
			String request;

			if ( address == null )
				request = "tcp:" + port;
			else
				request = "tcp:" + port + ":" + address;
			return FormAdbRequest ( request );
		}

		/// <summary>
		/// Forms the adb request.
		/// </summary>
		/// <param name="req">The req.</param>
		/// <returns></returns>
		public byte[] FormAdbRequest ( String req ) {
			String resultStr = String.Format ( "{0}{1}\n", req.Length.ToString ( "X4" ), req );
			byte[] result;
			try {
				result = resultStr.GetBytes ( AdbHelper.DEFAULT_ENCODING );
			} catch ( EncoderFallbackException efe ) {
				Log.e ( TAG, efe );
				return null;
			}

			System.Diagnostics.Debug.Assert ( result.Length == req.Length + 5, String.Format ( "result: {1}{0}\nreq: {3}{2}", result.Length, result.GetString ( AdbHelper.DEFAULT_ENCODING ), req.Length, req ) );
			return result;
		}

		/// <summary>
		/// Writes the specified data to the specified socket.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="data">The data.</param>
		/// <returns></returns>
		public bool Write ( Socket socket, byte[] data ) {
			try {
				Write ( socket, data, -1, DdmPreferences.Timeout );
			} catch ( IOException e ) {
				Log.e ( TAG, e );
				return false;
			}

			return true;
		}

		/// <summary>
		/// Writes the specified data to the specified socket.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="data">The data.</param>
		/// <param name="length">The length.</param>
		/// <param name="timeout">The timeout.</param>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// channel EOF
		/// or
		/// timeout
		/// </exception>
		public void Write ( Socket socket, byte[] data, int length, int timeout ) {
			//using ( var buf = new MemoryStream ( data, 0, length != -1 ? length : data.Length ) ) {
			int numWaits = 0;
			int count = -1;

			//while ( buf.Position != buf.Length ) {
			try {
				count = socket.Send ( data, 0, length != -1 ? length : data.Length, SocketFlags.None );
				if ( count < 0 ) {
					throw new AdbException ( "channel EOF" );
				} else if ( count == 0 ) {
					// TODO: need more accurate timeout?
					if ( timeout != 0 && numWaits * WAIT_TIME > timeout ) {
						throw new AdbException ( "timeout" );
					}
					// non-blocking spin
					Thread.Sleep ( WAIT_TIME );
					numWaits++;
				} else {
					numWaits = 0;
				}
			} catch ( SocketException sex ) {
				Log.e ( TAG, sex );
				throw;
			}
			//}
			//}
		}

		/// <summary>
		/// Reads the adb response.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="readDiagString">if set to <c>true</c> [read diag string].</param>
		/// <returns></returns>
		public AdbResponse ReadAdbResponse ( Socket socket, bool readDiagString ) {

			AdbResponse resp = new AdbResponse ( );

			byte[] reply = new byte[4];
			if ( !Read ( socket, reply ) ) {
				return resp;
			}
			resp.IOSuccess = true;

			if ( IsOkay ( reply ) ) {
				resp.Okay = true;
			} else {
				readDiagString = true; // look for a reason after the FAIL
				resp.Okay = false;
			}

			// not a loop -- use "while" so we can use "break"
			while ( readDiagString ) {
				// length string is in next 4 bytes
				byte[] lenBuf = new byte[4];
				if ( !Read ( socket, lenBuf ) ) {
					Log.w ( TAG, "Expected diagnostic string not found" );
					break;
				}

				String lenStr = ReplyToString ( lenBuf );

				int len;
				try {
					len = int.Parse ( lenStr, System.Globalization.NumberStyles.HexNumber );

				} catch ( FormatException ) {
					Log.e ( TAG, "Expected digits, got '{0}' : {1} {2} {3} {4}", lenBuf[0], lenBuf[1], lenBuf[2], lenBuf[3] );
					Log.e ( TAG, "reply was {0}", ReplyToString ( reply ) );
					break;
				}

				byte[] msg = new byte[len];
				if ( !Read ( socket, msg ) ) {
					Log.e ( TAG, "Failed reading diagnostic string, len={0}", len );
					break;
				}

				resp.Message = ReplyToString ( msg );
				Log.e ( TAG, "Got reply '{0}', diag='{1}'", ReplyToString ( reply ), resp.Message );

				break;
			}

			return resp;
		}

		/// <summary>
		/// Reads the data from specified socket.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="data">The data.</param>
		/// <returns></returns>
		public bool Read ( Socket socket, byte[] data ) {
			try {
				Read ( socket, data, -1, DdmPreferences.Timeout );
			} catch ( AdbException ) {
				return false;
			}

			return true;
		}

		/// <summary>
		/// Reads the data from specified socket.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="data">The data.</param>
		/// <param name="length">The length.</param>
		/// <param name="timeout">The timeout.</param>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// EOF 
		/// or 
		/// No Data to read: exception.Message
		/// </exception>
		public void Read ( Socket socket, byte[] data, int length, int timeout ) {
			int expLen = length != -1 ? length : data.Length;
			int count = -1;
			int totalRead = 0;

			while ( count != 0 && totalRead < expLen ) {
				try {
					int left = expLen - totalRead;
					int buflen = left < socket.ReceiveBufferSize ? left : socket.ReceiveBufferSize;

					byte[] buffer = new byte[buflen];
					socket.ReceiveBufferSize = expLen;
					count = socket.Receive ( buffer, buflen, SocketFlags.None );
					if ( count < 0 ) {
						Log.e ( TAG, "read: channel EOF" );
						throw new AdbException ( "EOF" );
					} else if ( count == 0 ) {
						Log.d ( TAG, "DONE with Read" );
					} else {
						Array.Copy ( buffer, 0, data, totalRead, count );
						totalRead += count;
					}
				} catch ( SocketException sex ) {
					throw new AdbException ( String.Format ( "No Data to read: {0}", sex.Message ) );
				}
			}

		}

		/// <summary>
		/// Creates the JDWP forward request.
		/// </summary>
		/// <param name="pid">The pid.</param>
		/// <returns></returns>
		private byte[] CreateJdwpForwardRequest ( int pid ) {
			String req = String.Format ( "jdwp:{0}", pid );
			return FormAdbRequest ( req );
		}

		/// <summary>
		/// Creates the forward.
		/// </summary>
		/// <param name="adbSockAddr">The adb sock addr.</param>
		/// <param name="device">The device.</param>
		/// <param name="localPort">The local port.</param>
		/// <param name="remotePort">The remote port.</param>
		/// <returns></returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed to submit the forward command.
		/// or
		/// Device rejected command:  + resp.Message
		/// </exception>
		public bool CreateForward ( IPEndPoint adbSockAddr, Device device, int localPort, int remotePort ) {

			Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				adbChan.Connect ( adbSockAddr );
				adbChan.Blocking = true;

				// host-serial should be different based on the transport...


				byte[] request = FormAdbRequest ( String.Format ( "host-serial:{0}:forward:tcp:{1};tcp:{2}", //$NON-NLS-1$
								device.SerialNumber, localPort, remotePort ) );

				if ( !Write ( adbChan, request ) ) {
					throw new AdbException ( "failed to submit the forward command." );
				}

				AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
				if ( !resp.IOSuccess || !resp.Okay ) {
					throw new AdbException ( "Device rejected command: " + resp.Message );
				}
			} finally {
				if ( adbChan != null ) {
					adbChan.Close ( );
				}
			}

			return true;
		}

		/// <summary>
		/// Creates the reverse forward.
		/// </summary>
		/// <param name="adbSockAddr">The adb sock addr.</param>
		/// <param name="device">The device.</param>
		/// <param name="remotePort">The remote port.</param>
		/// <param name="localPort">The local port.</param>
		/// <returns></returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed to submit the forward command.
		/// or
		/// Device rejected command:  + resp.Message
		/// </exception>
		public bool CreateReverseForward ( IPEndPoint adbSockAddr, Device device, int remotePort, int localPort ) {

			Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				adbChan.Connect ( adbSockAddr );
				adbChan.Blocking = true;

				// if the device is not -1, then we first tell adb we're looking to talk
				// to a specific device
				SetDevice ( adbChan, device );

				byte[] request = FormAdbRequest ( String.Format ( "reverse:forward:tcp:{0};tcp:{1}", //$NON-NLS-1$
					remotePort, localPort ) );

				if ( !Write ( adbChan, request ) ) {
					throw new AdbException ( "failed to submit the reverse forward command." );
				}

				AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
				if ( !resp.IOSuccess || !resp.Okay ) {
					throw new AdbException ( "Device rejected command: " + resp.Message );
				}
			} finally {
				if ( adbChan != null ) {
					adbChan.Close ( );
				}
			}

			return true;
		}


		/// <summary>
		/// Lists the forward.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <exception cref="System.NotImplementedException"></exception>
		public void ListForward ( IPEndPoint address, Device device ) {
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// Removes the forward.
		/// </summary>
		/// <param name="address">The adb socket address.</param>
		/// <param name="device">The device.</param>
		/// <param name="localPort">The local port.</param>
		/// <returns></returns>
		public bool RemoveForward ( IPEndPoint address, Device device, int localPort ) {
			using ( var socket = ExecuteRawSocketCommand ( address, device, "host-serial:{0}:killforward:tcp:{1}".With ( device.SerialNumber, localPort ) ) ) {
				// do nothing...
				return true;
			}
		}

		/// <summary>
		/// Removes all forwards.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <returns></returns>
		public bool RemoveAllForward ( IPEndPoint address, Device device ) {
			using ( var socket = ExecuteRawSocketCommand ( address, device, "host-serial:{0}:killforward-all".With ( device.SerialNumber ) ) ) {
				// do nothing...
				return true;
			}
		}

		/// <summary>
		/// Determines whether the specified reply is okay.
		/// </summary>
		/// <param name="reply">The reply.</param>
		/// <returns>
		///   <c>true</c> if the specified reply is okay; otherwise, <c>false</c>.
		/// </returns>
		public bool IsOkay ( byte[] reply ) {
			return reply.GetString ( ).Equals ( "OKAY" );
		}

		/// <summary>
		/// Replies to string.
		/// </summary>
		/// <param name="reply">The reply.</param>
		/// <returns></returns>
		public string ReplyToString ( byte[] reply ) {
			String result;
			try {
				result = Encoding.Default.GetString ( reply );
			} catch ( DecoderFallbackException uee ) {
				Log.e ( TAG, uee );
				result = "";
			}
			return result;
		}

		/// <summary>
		/// Gets the devices that are available for communication.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <returns>A list of devices that are connected.</returns>
		/// <gist id="a8acf10d48370d138247" />
		public List<Device> GetDevices ( IPEndPoint address ) {
			// -l will return additional data
			using ( var socket = ExecuteRawSocketCommand ( address, "host:devices-l" ) ) {
				byte[] reply = new byte[4];

				if ( !Read ( socket, reply ) ) {
					Log.e ( TAG, "error in getting data length" );
					return null;
				}
				string lenHex = reply.GetString ( Encoding.Default );
				int len = int.Parse ( lenHex, System.Globalization.NumberStyles.HexNumber );

				reply = new byte[len];
				if ( !Read ( socket, reply ) ) {
					Log.e ( TAG, "error in getting data" );
					return null;
				}

				List<Device> s = new List<Device> ( );
				string[] data = reply.GetString ( Encoding.Default ).Split ( new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries );
				data.ForEach ( item => {
					var device = Device.CreateFromAdbData ( item );
					if ( device != null ) {
						s.Add ( device );
					}
				} );

				return s;
			}
		}

		/// <summary>
		/// Gets the frame buffer from the specified end point.
		/// </summary>
		/// <param name="adbSockAddr">The adb sock addr.</param>
		/// <param name="device">The device.</param>
		/// <returns>Returns the RawImage.</returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed asking for frame buffer
		/// or
		/// failed nudging
		/// </exception>
		public RawImage GetFrameBuffer ( IPEndPoint adbSockAddr, IDevice device ) {

			RawImage imageParams = new RawImage ( );
			byte[] request = FormAdbRequest ( "framebuffer:" ); //$NON-NLS-1$
			byte[] nudge = {
						0
				};
			byte[] reply;

			Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				adbChan.Connect ( adbSockAddr );
				adbChan.Blocking = true;

				// if the device is not -1, then we first tell adb we're looking to talk
				// to a specific device
				SetDevice ( adbChan, device );
				if ( !Write ( adbChan, request ) )
					throw new AdbException ( "failed asking for frame buffer" );

				AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
				if ( !resp.IOSuccess || !resp.Okay ) {
					Log.w ( TAG, "Got timeout or unhappy response from ADB fb req: " + resp.Message );
					adbChan.Close ( );
					return null;
				}

				// first the protocol version.
				reply = new byte[4];
				if ( !Read ( adbChan, reply ) ) {
					Log.w ( TAG, "got partial reply from ADB fb:" );

					adbChan.Close ( );
					return null;
				}
				BinaryReader buf;
				int version = 0;
				using ( MemoryStream ms = new MemoryStream ( reply ) ) {
					buf = new BinaryReader ( ms );
					version = buf.ReadInt16 ( );
				}

				// get the header size (this is a count of int)
				int headerSize = RawImage.GetHeaderSize ( version );
				// read the header
				reply = new byte[headerSize * 4];
				if ( !Read ( adbChan, reply ) ) {
					Log.w ( TAG, "got partial reply from ADB fb:" );

					adbChan.Close ( );
					return null;
				}

				using ( MemoryStream ms = new MemoryStream ( reply ) ) {
					buf = new BinaryReader ( ms );

					// fill the RawImage with the header
					if ( imageParams.ReadHeader ( version, buf ) == false ) {
						Log.w ( TAG, "Unsupported protocol: " + version );
						return null;
					}
				}

				Log.d ( TAG, "image params: bpp=" + imageParams.Bpp + ", size="
								+ imageParams.Size + ", width=" + imageParams.Width
								+ ", height=" + imageParams.Height );

				if ( !Write ( adbChan, nudge ) )
					throw new AdbException ( "failed nudging" );

				reply = new byte[imageParams.Size];
				if ( !Read ( adbChan, reply ) ) {
					Log.w ( TAG, "got truncated reply from ADB fb data" );
					adbChan.Close ( );
					return null;
				}

				imageParams.Data = reply;
			} finally {
				if ( adbChan != null ) {
					adbChan.Close ( );
				}
			}

			return imageParams;
		}

		/// <summary>
		/// Executes a shell command on the remote device
		/// </summary>
		/// <param name="endPoint">The end point.</param>
		/// <param name="command">The command.</param>
		/// <param name="device">The device.</param>
		/// <param name="rcvr">The RCVR.</param>
		/// <remarks>
		/// Should check if you CanSU before calling this.
		/// </remarks>
		public void ExecuteRemoteRootCommand ( IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr ) {
			ExecuteRemoteRootCommand ( endPoint, String.Format ( "su -c \"{0}\"", command ), device, rcvr, int.MaxValue );
		}

		/// <summary>
		/// Executes a shell command on the remote device
		/// </summary>
		/// <param name="endPoint">The end point.</param>
		/// <param name="command">The command.</param>
		/// <param name="device">The device.</param>
		/// <param name="rcvr">The RCVR.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		public void ExecuteRemoteRootCommand ( IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse ) {
			ExecuteRemoteCommand ( endPoint, String.Format ( "su -c \"{0}\"", command ), device, rcvr );
		}

		/// <summary>
		/// Executes the remote command.
		/// </summary>
		/// <param name="endPoint">The end point.</param>
		/// <param name="command">The command.</param>
		/// <param name="device">The device.</param>
		/// <param name="rcvr">The RCVR.</param>
		/// <param name="maxTimeToOutputResponse">The max time to output response.</param>
		/// <exception cref="System.OperationCanceledException"></exception>
		/// <exception cref="System.IO.FileNotFoundException">
		/// </exception>
		/// <exception cref="Managed.Adb.Exceptions.UnknownOptionException"></exception>
		/// <exception cref="Managed.Adb.Exceptions.CommandAbortingException"></exception>
		/// <exception cref="Managed.Adb.Exceptions.PermissionDeniedException"></exception>
		/// <exception cref="Managed.Adb.Exceptions.ShellCommandUnresponsiveException"></exception>
		/// <exception cref="AdbException">failed submitting shell command</exception>
		/// <exception cref="UnknownOptionException"></exception>
		/// <exception cref="CommandAbortingException"></exception>
		/// <exception cref="PermissionDeniedException"></exception>
		public void ExecuteRemoteCommand ( IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr, int maxTimeToOutputResponse ) {

			using ( var socket = ExecuteRawSocketCommand ( endPoint, device, "shell:{0}".With ( command ) ) ) {
				socket.ReceiveTimeout = maxTimeToOutputResponse;
				socket.SendTimeout = maxTimeToOutputResponse;

				try {
					byte[] data = new byte[16384];
					int count = -1;
					while ( count != 0 ) {

						if ( rcvr != null && rcvr.IsCancelled ) {
							Log.w ( TAG, "execute: cancelled" );
							throw new OperationCanceledException ( );
						}

						count = socket.Receive ( data );
						if ( count == 0 ) {
							// we're at the end, we flush the output
							rcvr.Flush ( );
							Log.w ( TAG, "execute '" + command + "' on '" + device + "' : EOF hit. Read: " + count );
						} else {
							string[] cmd = command.Trim ( ).Split ( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries );
							string sdata = data.GetString ( 0, count, AdbHelper.DEFAULT_ENCODING );

							var sdataTrimmed = sdata.Trim ( );
							if ( sdataTrimmed.EndsWith ( String.Format ( "{0}: not found", cmd[0] ) ) ) {
								Log.w ( TAG, "The remote execution returned: '{0}: not found'", cmd[0] );
								throw new FileNotFoundException ( string.Format ( "The remote execution returned: '{0}: not found'", cmd[0] ) );
							}

							if ( sdataTrimmed.EndsWith ( "No such file or directory" ) ) {
								Log.w ( TAG, "The remote execution returned: {0}", sdataTrimmed );
								throw new FileNotFoundException ( String.Format ( "The remote execution returned: {0}", sdataTrimmed ) );
							}

							// for "unknown options"
							if ( sdataTrimmed.Contains ( "Unknown option" ) ) {
								Log.w ( TAG, "The remote execution returned: {0}", sdataTrimmed );
								throw new UnknownOptionException ( sdataTrimmed );
							}

							// for "aborting" commands
							if ( sdataTrimmed.IsMatch ( "Aborting.$" ) ) {
								Log.w ( TAG, "The remote execution returned: {0}", sdataTrimmed );
								throw new CommandAbortingException ( sdataTrimmed );
							}

							// for busybox applets 
							// cmd: applet not found
							if ( sdataTrimmed.IsMatch ( "applet not found$" ) && cmd.Length > 1 ) {
								Log.w ( TAG, "The remote execution returned: '{0}'", sdataTrimmed );
								throw new FileNotFoundException ( string.Format ( "The remote execution returned: '{0}'", sdataTrimmed ) );
							}

							// checks if the permission to execute the command was denied.
							// workitem: 16822
							// I have decided that the receiver should handle this... maybe the others too?
							if ( sdataTrimmed.IsMatch ( "(permission|access) denied$" ) ) {
								Log.w ( TAG, "The remote execution returned: '{0}'", sdataTrimmed );
								//throw new PermissionDeniedException(String.Format("The remote execution returned: '{0}'", sdataTrimmed));
							}

							// Add the data to the receiver
							if ( rcvr != null ) {
								rcvr.AddOutput ( data, 0, count );
							}

						}
					}
				} catch ( SocketException ) {
					throw new ShellCommandUnresponsiveException ( );
				} finally {
					rcvr.Flush ( );
				}
			}

		}

		/// <summary>
		/// Executes a shell command on the remote device
		/// </summary>
		/// <param name="endPoint">The socket end point</param>
		/// <param name="command">The command to execute</param>
		/// <param name="device">The device to execute on</param>
		/// <param name="rcvr">The shell output receiver</param>
		/// <exception cref="FileNotFoundException">Throws if the result is 'command': not found</exception>
		/// <exception cref="IOException">Throws if there is a problem reading / writing to the socket</exception>
		/// <exception cref="OperationCanceledException">Throws if the execution was canceled</exception>
		/// <exception cref="EndOfStreamException">Throws if the Socket.Receice ever returns -1</exception>
		public void ExecuteRemoteCommand ( IPEndPoint endPoint, String command, Device device, IShellOutputReceiver rcvr ) {
			ExecuteRemoteCommand ( endPoint, command, device, rcvr, int.MaxValue );
		}


		/// <summary>
		/// Sets the device.
		/// </summary>
		/// <param name="adbChan">The adb chan.</param>
		/// <param name="device">The device.</param>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// failed submitting device ( + device + ) request to ADB
		/// or
		/// device ( + device + ) request rejected:  + resp.Message
		/// </exception>
		/// <exception cref="Managed.Adb.Exceptions.DeviceNotFoundException"></exception>
		public void SetDevice ( Socket adbChan, IDevice device ) {
			// if the device is not null, then we first tell adb we're looking to talk
			// to a specific device
			if ( device != null ) {
				String msg = "host:transport:" + device.SerialNumber;
				byte[] device_query = FormAdbRequest ( msg );

				if ( !Write ( adbChan, device_query ) ) {
					throw new AdbException ( "failed submitting device (" + device + ") request to ADB" );
				}

				AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
				if ( !resp.Okay ) {
					if ( String.Compare ( "device not found", resp.Message, true ) == 0 ) {
						throw new DeviceNotFoundException ( device.SerialNumber );
					} else {
						throw new AdbException ( "device (" + device + ") request rejected: " + resp.Message );
					}
				}
			}
		}

		/// <summary>
		/// Runs the Event log service on the Device, and provides its output to the LogReceiver.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <param name="rcvr">The RCVR.</param>
		public void RunEventLogService ( IPEndPoint address, Device device, LogReceiver rcvr ) {
			RunLogService ( address, device, "events", rcvr );
		}

		/// <summary>
		/// Runs the Event log service on the Device, and provides its output to the LogReceiver.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <param name="logName">Name of the log.</param>
		/// <param name="rcvr">The RCVR.</param>
		/// <exception cref="AdbException">failed asking for log</exception>
		/// <exception cref="Managed.Adb.Exceptions.AdbCommandRejectedException"></exception>
		public void RunLogService ( IPEndPoint address, Device device, String logName, LogReceiver rcvr ) {
			using ( var socket = ExecuteRawSocketCommand ( address, device, "log:{0}".With ( logName ) ) ) {
				byte[] data = new byte[16384];
				using ( var ms = new MemoryStream ( data ) ) {
					int offset = 0;

					while ( true ) {
						int count;
						if ( rcvr != null && rcvr.IsCancelled ) {
							break;
						}
						var buffer = new byte[4 * 1024];

						count = socket.Receive ( buffer );
						if ( count < 0 ) {
							break;
						} else if ( count == 0 ) {
							try {
								Thread.Sleep ( WAIT_TIME * 5 );
							} catch ( ThreadInterruptedException ) {
							}
						} else {
							ms.Write ( buffer, offset, count );
							offset += count;
							if ( rcvr != null ) {
								var d = ms.ToArray ( );
								rcvr.ParseNewData ( d, 0, d.Length );
							}
						}
					}
				}
			}
		}

		/// <summary>
		/// Reboots the specified adb socket address.
		/// </summary>
		/// <param name="adbSocketAddress">The adb socket address.</param>
		/// <param name="device">The device.</param>
		public void Reboot ( IPEndPoint adbSocketAddress, Device device ) {
			Reboot ( string.Empty, adbSocketAddress, device );
		}

		/// <summary>
		/// Reboots the specified device in to the specified mode.
		/// </summary>
		/// <param name="into">The into.</param>
		/// <param name="adbSockAddr">The adb sock addr.</param>
		/// <param name="device">The device.</param>
		public void Reboot ( String into, IPEndPoint adbSockAddr, Device device ) {
			byte[] request;
			if ( string.IsNullOrEmpty ( into ) ) {
				request = FormAdbRequest ( "reboot:" );
			} else {
				request = FormAdbRequest ( "reboot:" + into );
			}

			using ( ExecuteRawSocketCommand ( adbSockAddr, device, request ) ) {
				// nothing to do...
			}
		}

		/// <summary>
		/// Executes a raw socket command.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <param name="command">The command.</param>
		/// <returns></returns>
		/// <exception cref="AdbException">failed to submit the command: {0}.With(command)
		/// or
		/// Device rejected command: {0}.With(resp.Message)</exception>
		private Socket ExecuteRawSocketCommand ( IPEndPoint address, Device device, string command ) {
			return ExecuteRawSocketCommand ( address, device, FormAdbRequest ( command ) );
		}

		/// <summary>
		/// Executes the raw socket command.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="command">The command.</param>
		/// <returns></returns>
		private Socket ExecuteRawSocketCommand ( IPEndPoint address, string command ) {
			return ExecuteRawSocketCommand ( address, FormAdbRequest ( command ) );
		}

		/// <summary>
		/// Executes the raw socket command.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="command">The command.</param>
		/// <returns></returns>
		private Socket ExecuteRawSocketCommand ( IPEndPoint address, byte[] command ) {
			return ExecuteRawSocketCommand ( address, null, command );
		}
		/// <summary>
		/// Executes the raw socket command.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="device">The device.</param>
		/// <param name="command">The command. Should call FormAdbRequest on the string to create the byte array.</param>
		/// <returns></returns>
		/// <exception cref="Managed.Adb.Exceptions.AdbException">
		/// Device is offline
		/// or
		/// failed to submit the command: {0}..With(command.GetString().Trim())
		/// or
		/// Device rejected command: {0}.With(resp.Message)
		/// </exception>
		/// <exception cref="AdbException">Device is offline.
		/// or
		/// failed to submit the command: {0}.With(command)
		/// or
		/// Device rejected command: {0}.With(resp.Message)</exception>
		private Socket ExecuteRawSocketCommand ( IPEndPoint address, Device device, byte[] command ) {
			if ( device != null && !device.IsOnline ) {
				throw new AdbException ( "Device is offline" );
			}

			Socket adbChan = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			adbChan.Connect ( address );
			adbChan.Blocking = true;
			if ( device != null ) {
				SetDevice ( adbChan, device );
			}
			if ( !Write ( adbChan, command ) ) {
				throw new AdbException ( "failed to submit the command: {0}.".With ( command.GetString ( ).Trim ( ) ) );
			}

			AdbResponse resp = ReadAdbResponse ( adbChan, false /* readDiagString */);
			if ( !resp.IOSuccess || !resp.Okay ) {
				throw new AdbException ( "Device rejected command: {0}".With ( resp.Message ) );
			}
			return adbChan;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="device">The device.</param>
		/// <returns></returns>
		private string HostPrefixFromDevice ( IDevice device ) {
			switch ( device.TransportType ) {
				case TransportType.Host:
					return "host-serial";
				case TransportType.Usb:
					return "host-usb";
				case TransportType.Local:
					return "host-local";
				case TransportType.Any:
				default:
					return "host";
			}
		}
	}
}



<|start_filename|>Madb.Site/assets/styles/bootswatch-paper.css<|end_filename|>
﻿@import url("//fonts.googleapis.com/css?family=RobotoDraft:400italic,700italic,400,700");
html,
body {
  font-family: 'Roboto', sans-serif;
}
.z-depth-0 {
  box-shadow: none;
}
.z-depth-1 {
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.z-depth-2 {
  box-shadow: 0 0.2em 0.5em 0 rgba(0, 0, 0, 0.258824);
}
.z-depth-3 {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
}
.z-depth-4 {
  box-shadow: 0 0.7em 1.3em 0 rgba(0, 0, 0, 0.258824);
}
.z-depth-5 {
  box-shadow: 0 0.9em 1.3em 0 rgba(0, 0, 0, 0.258824);
}
/** popover **/
.popover {
  max-width: none;
}
/** dropdown-menu **/
.dropdown-menu {
  box-shadow: 0 0.2em 0.5em 0 rgba(0, 0, 0, 0.258824);
  background-color: #ffffff;
  border: solid 1px #cccccc;
  border: solid 1px rgba(0, 0, 0, 0.15);
  border-radius: 2px;
}
/** badge **/
.badge {
  box-shadow: none;
  border-radius: 2px;
  background-color: #607d8b;
  border: solid 1px #56767c;
  color: #ffffff;
  font-weight: bold;
  line-height: 1;
}
.badge.default {
  border-radius: 2px;
  background-color: #607d8b;
  border: solid 1px #56767c;
  color: #ffffff;
}
.badge.primary {
  background-color: #9c27b0;
  border: solid 1px #75229b;
  color: #ffffff;
}
.badge.success {
  background-color: #259b24;
  border: solid 1px #31861f;
  color: #f5fdf4;
}
.badge.info {
  background-color: #00bcd4;
  border: solid 1px #00bbb1;
  color: #ffffff;
}
.badge.warning {
  background-color: #ff5722;
  border: solid 1px #ff1b08;
  color: #ffffff;
}
.badge.danger {
  background-color: #e51c23;
  border: solid 1px #d0183d;
  color: #ffffff;
}
.badge a {
  color: #ffffff;
}
.badge a:hover,
.badge a:focus,
.badge a:active {
  color: #ffffff;
}
.navbar {
  border: none;
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
}
.navbar .form-control {
  color: #fff;
  border-color: #fff;
}
.navbar.navbar-default {
  background-color: #4285f4;
  border-color: #2371f2;
  color: #f1f1f1;
}
.navbar.navbar-default .navbar-brand {
  color: #f1f1f1;
  background-color: transparent;
}
.navbar.navbar-default .navbar-brand:hover,
.navbar.navbar-default .navbar-brand:focus {
  color: #f1f1f1;
  background-color: transparent;
}
.navbar.navbar-default .navbar-text {
  color: #f1f1f1;
}
.navbar.navbar-default .navbar-nav > li > a {
  color: #f1f1f1;
}
.navbar.navbar-default .navbar-nav > li > a:hover,
.navbar.navbar-default .navbar-nav > li > a:focus {
  color: #f1f1f1;
  background-color: #669cf6;
}
.navbar.navbar-default .navbar-nav > .active > a,
.navbar.navbar-default .navbar-nav > .active > a:hover,
.navbar.navbar-default .navbar-nav > .active > a:focus {
  color: #f1f1f1;
  background-color: #669cf6;
}
.navbar.navbar-default .navbar-nav > .disabled > a,
.navbar.navbar-default .navbar-nav > .disabled > a:hover,
.navbar.navbar-default .navbar-nav > .disabled > a:focus {
  color: #cccccc;
  background-color: transparent;
}
.navbar.navbar-default .navbar-toggle {
  border-color: #dddddd;
}
.navbar.navbar-default .navbar-toggle:hover,
.navbar.navbar-default .navbar-toggle:focus {
  background-color: #dddddd;
}
.navbar.navbar-default .navbar-toggle .icon-bar {
  background-color: #888888;
}
.navbar.navbar-default .navbar-collapse,
.navbar.navbar-default .navbar-form {
  border-color: #4285f4;
}
.navbar.navbar-default .navbar-nav > .open > a,
.navbar.navbar-default .navbar-nav > .open > a:hover,
.navbar.navbar-default .navbar-nav > .open > a:focus {
  background-color: #669cf6;
}
.navbar.navbar-default .navbar-nav .open .dropdown-menu > li > a {
  background-color: transparent;
}
.navbar.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
  color: #f1f1f1;
  background-color: #669cf6;
}
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
  color: #f1f1f1;
  background-color: #669cf6;
}
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
  color: #cccccc;
  background-color: transparent;
}
.navbar.navbar-default .navbar-link {
  color: #f1f1f1;
}
.navbar.navbar-default .navbar-link:hover {
  color: #f1f1f1;
}
.navbar.navbar-default .btn-link {
  color: #f1f1f1;
}
.navbar.navbar-default .btn-link:hover,
.navbar.navbar-default .btn-link:focus {
  color: #f1f1f1;
}
.navbar.navbar-default .btn-link[disabled]:hover,
.navbar.navbar-default .btn-link[disabled]:focus {
  color: #cccccc;
  background-color: transparent;
}
fieldset[disabled] .navbar-default .btn-link:focus,
fieldset[disabled] .navbar-default .btn-link:hover {
  color: #cccccc;
  background-color: transparent;
}
.btn {
  border-radius: 3px;
  background-color: #ffffff;
  border-color: #f7f7f7;
  border-width: 1px;
  color: #333333;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn:hover {
  background-color: #fafafa;
  border-color: #f5f5f5;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f7f7f7;
  border-color: #f2f2f2;
  outline: none;
}
.btn:active,
.btn.active,
.open > .dropdown-toggle.btn {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f2f2f2;
  border-color: #ededed;
  outline: none;
}
.btn[disabled],
.btn.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn:active,
.btn.active {
  box-shadow: 0 0.2em 0.5em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-round {
  border-radius: 100%;
  font-weight: bolder;
  background-color: #ffffff;
  border-color: #f7f7f7;
  border-width: 1px;
  color: #333333;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-round:hover {
  background-color: #fafafa;
  border-color: #f5f5f5;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-round:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f7f7f7;
  border-color: #f2f2f2;
  outline: none;
}
.btn.btn-round:active,
.btn.btn-round.active,
.open > .dropdown-toggle.btn.btn-round {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f2f2f2;
  border-color: #ededed;
  outline: none;
}
.btn.btn-round[disabled],
.btn.btn-round.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-default {
  background-color: #ffffff;
  border-color: #f7f7f7;
  border-width: 1px;
  color: #333333;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-default:hover {
  background-color: #fafafa;
  border-color: #f5f5f5;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-default:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f7f7f7;
  border-color: #f2f2f2;
  outline: none;
}
.btn.btn-default:active,
.btn.btn-default.active,
.open > .dropdown-toggle.btn.btn-default {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #f2f2f2;
  border-color: #ededed;
  outline: none;
}
.btn.btn-default[disabled],
.btn.btn-default.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-primary {
  background-color: #9c27b0;
  border-color: #9124a3;
  border-width: 1px;
  color: #ffffff;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-primary:hover {
  background-color: #9525a8;
  border-color: #8d239f;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-primary:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #9124a3;
  border-color: #89229b;
  outline: none;
}
.btn.btn-primary:active,
.btn.btn-primary.active,
.open > .dropdown-toggle.btn.btn-primary {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #89229b;
  border-color: #822193;
  outline: none;
}
.btn.btn-primary[disabled],
.btn.btn-primary.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-success {
  background-color: #259b24;
  border-color: #228f21;
  border-width: 1px;
  color: #ffffff;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-success:hover {
  background-color: #239322;
  border-color: #218a20;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-success:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #228f21;
  border-color: #20861f;
  outline: none;
}
.btn.btn-success:active,
.btn.btn-success.active,
.open > .dropdown-toggle.btn.btn-success {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #20861f;
  border-color: #1e7e1d;
  outline: none;
}
.btn.btn-success[disabled],
.btn.btn-success.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-info {
  background-color: #00bcd4;
  border-color: #00aec5;
  border-width: 1px;
  color: #ffffff;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-info:hover {
  background-color: #00b3ca;
  border-color: #00aac0;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-info:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #00aec5;
  border-color: #00a5bb;
  outline: none;
}
.btn.btn-info:active,
.btn.btn-info.active,
.open > .dropdown-toggle.btn.btn-info {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #00a5bb;
  border-color: #009cb0;
  outline: none;
}
.btn.btn-info[disabled],
.btn.btn-info.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-warning {
  background-color: #ff5722;
  border-color: #ff4b13;
  border-width: 1px;
  color: #ffffff;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-warning:hover {
  background-color: #ff4f18;
  border-color: #ff470e;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-warning:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #ff4b13;
  border-color: #ff4408;
  outline: none;
}
.btn.btn-warning:active,
.btn.btn-warning.active,
.open > .dropdown-toggle.btn.btn-warning {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #ff4408;
  border-color: #fd3d00;
  outline: none;
}
.btn.btn-warning[disabled],
.btn.btn-warning.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-danger {
  background-color: #e51c23;
  border-color: #d91920;
  border-width: 1px;
  color: #ffffff;
  outline: none;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-danger:hover {
  background-color: #dd1920;
  border-color: #d4181f;
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
}
.btn.btn-danger:focus {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #d91920;
  border-color: #d0181e;
  outline: none;
}
.btn.btn-danger:active,
.btn.btn-danger.active,
.open > .dropdown-toggle.btn.btn-danger {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
  background-color: #d0181e;
  border-color: #c7171d;
  outline: none;
}
.btn.btn-danger[disabled],
.btn.btn-danger.disabled {
  box-shadow: none;
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
}
.btn.btn-link {
  border: none;
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #050505;
  box-shadow: none;
  text-decoration: none;
  font-weight: bold;
}
.btn.btn-link:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link[disabled],
.btn.btn-link.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link:focus,
.btn.btn-link:active,
.btn.btn-link.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-default {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #ffffff;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-default:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-default[disabled],
.btn.btn-link.btn-default.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-default:focus,
.btn.btn-link.btn-default:active,
.btn.btn-link.btn-default.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-primary {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #9c27b0;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-primary:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-primary[disabled],
.btn.btn-link.btn-primary.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-primary:focus,
.btn.btn-link.btn-primary:active,
.btn.btn-link.btn-primary.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-success {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #259b24;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-success:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-success[disabled],
.btn.btn-link.btn-success.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-success:focus,
.btn.btn-link.btn-success:active,
.btn.btn-link.btn-success.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-info {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #00bcd4;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-info:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-info[disabled],
.btn.btn-link.btn-info.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-info:focus,
.btn.btn-link.btn-info:active,
.btn.btn-link.btn-info.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-warning {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #ff5722;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-warning:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-warning[disabled],
.btn.btn-link.btn-warning.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-warning:focus,
.btn.btn-link.btn-warning:active,
.btn.btn-link.btn-warning.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.btn.btn-link.btn-danger {
  border-color: transparent;
  background-color: transparent;
  outline: none;
  color: #e51c23;
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-danger:hover {
  background-color: rgba(153, 153, 153, 0.2);
  box-shadow: none;
  text-decoration: none;
}
.btn.btn-link.btn-danger[disabled],
.btn.btn-link.btn-danger.disabled {
  background-color: rgba(153, 153, 153, 0.1);
  color: #9e9e9e;
  box-shadow: none;
}
.btn.btn-link.btn-danger:focus,
.btn.btn-link.btn-danger:active,
.btn.btn-link.btn-danger.active {
  background-color: rgba(153, 153, 153, 0.4);
  box-shadow: none;
}
.form-group {
  position: relative;
}
.form-group label {
  color: #9e9e9e;
  font-weight: normal;
}
.form-group .form-control {
  z-index: 100;
}
.form-group .form-control::-moz-placeholder {
  color: #9e9e9e;
}
.form-group .form-control:-ms-input-placeholder {
  color: #9e9e9e;
}
.form-group .form-control::-webkit-input-placeholder {
  color: #9e9e9e;
}
.form-group .form-control:focus::-moz-placeholder {
  color: transparent;
}
.form-group .form-control:focus:-ms-input-placeholder {
  color: transparent;
}
.form-group .form-control:focus::-webkit-input-placeholder {
  color: transparent;
}
.form-group .form-control:not([disabled]) + label {
  display: inline-block;
  font-size: 1em;
  height: 1.09em;
  font-weight: normal;
  color: #9e9e9e;
  position: absolute;
  top: .5em;
  left: 150%;
  bottom: 0;
  opacity: 0;
  -moz-transition: all ease-in-out 300ms;
  -o-transition: all ease-in-out 300ms;
  -webkit-transition: all ease-in-out 300ms;
  transition: all ease-in-out 300ms;
  -moz-transition-property: top, color;
  -o-transition-property: top, color;
  -webkit-transition-property: top, color;
  transition-property: top, color;
  z-index: 1;
}
.form-group .form-control:focus + label {
  max-height: none;
  font-size: inherit;
  line-height: inherit;
  color: #03a9f4;
  top: -1em;
  left: 0;
  opacity: 1;
}
.form-group .form-control:focus:invalid + label {
  color: #e51c23;
}
.form-inline .form-group {
  width: auto !important;
}
.form-inline .form-group .input-group {
  width: auto !important;
  display: inline-block;
}
.form-inline .form-group .input-group .input-group-addon {
  display: inline-block;
  float: left;
  height: 34px;
  width: 36px;
  border: none;
  background: transparent;
  font-weight: bold;
}
.form-inline .form-group .input-group .input-group-addon + .form-control:focus + label {
  left: 36px;
}
.form-inline .form-control {
  width: auto !important;
}
select.form-control,
input.form-control,
textarea.form-control {
  box-shadow: none !important;
  border: 0 solid #9e9e9e;
  border-bottom-width: 1px;
  padding: 4px 0 4px 0;
  border-radius: 0;
  background-color: transparent;
}
select.form-control:focus,
input.form-control:focus,
textarea.form-control:focus {
  border-color: #03a9f4;
  border-bottom-width: 2px;
  padding: 4px 0 3px 0;
}
select.form-control[required],
input.form-control[required],
textarea.form-control[required] {
  border-color: #673ab7;
}
select.form-control:invalid,
input.form-control:invalid,
textarea.form-control:invalid,
select.form-control.invalid,
input.form-control.invalid,
textarea.form-control.invalid {
  border-color: #e51c23;
}
select.form-control:disabled,
input.form-control:disabled,
textarea.form-control:disabled {
  border-style: dotted;
  background-color: transparent;
}
select.form-control.input-lg,
input.form-control.input-lg,
textarea.form-control.input-lg {
  font-size: 1.6em;
}
select.form-control.input-sm,
input.form-control.input-sm,
textarea.form-control.input-sm {
  font-size: .9em;
}
textarea.form-control {
  resize: none;
}
textarea.form-control:focus {
  resize: none;
}
.progress {
  height: 4px;
}
.progress,
.progress-bar {
  box-shadow: none;
}
.progress-striped .progress-bar,
.progress-bar-striped {
  background-image: -webkit-linear-gradient(90deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
  background-image: -o-linear-gradient(90deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
  background-image: linear-gradient(90deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.panel {
  background-color: #ffffff;
  border-color: #dddddd;
}
.panel .panel-heading {
  background-color: #f5f5f5;
  color: #7c7c7c;
  border-color: #dddddd;
}
.panel .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #dddddd;
}
.panel .panel-footer {
  background-color: #f5f5f5;
  color: #7c7c7c;
  border-color: #dddddd;
}
.panel.panel-primary .panel-heading {
  background-color: #e6b5ee;
  color: #050505;
  border-color: #d3a0ea;
}
.panel.panel-primary .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #d3a0ea;
}
.panel.panel-primary .panel-footer {
  background-color: #e6b5ee;
  color: #050505;
  border-color: #d3a0ea;
}
.panel.panel-success .panel-heading {
  background-color: #a2e9a2;
  color: #186317;
  border-color: #9ce58d;
}
.panel.panel-success .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #9ce58d;
}
.panel.panel-success .panel-footer {
  background-color: #a2e9a2;
  color: #186317;
  border-color: #9ce58d;
}
.panel.panel-warning .panel-heading {
  background-color: #ffd3c5;
  color: #dc3500;
  border-color: #ffb2ac;
}
.panel.panel-warning .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #ffb2ac;
}
.panel.panel-warning .panel-footer {
  background-color: #ffd3c5;
  color: #dc3500;
  border-color: #ffb2ac;
}
.panel.panel-info .panel-heading {
  background-color: #caf9ff;
  color: #007f8f;
  border-color: #a6fffa;
}
.panel.panel-info .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #a6fffa;
}
.panel.panel-info .panel-footer {
  background-color: #caf9ff;
  color: #007f8f;
  border-color: #a6fffa;
}
.panel.panel-danger .panel-heading {
  background-color: #fad3d4;
  color: #a91319;
  border-color: #f7bcc8;
}
.panel.panel-danger .panel-body {
  background-color: #ffffff;
  color: #333333;
  border-color: #f7bcc8;
}
.panel.panel-danger .panel-footer {
  background-color: #fad3d4;
  color: #a91319;
  border-color: #f7bcc8;
}
.jumbotron,
.list-group,
.panel,
.well {
  box-shadow: 0 0.3em 1em 0 rgba(0, 0, 0, 0.258824);
}
.jumbotron {
  background-color: #ffffff;
  color: #333333;
  border: solid 1px #f2f2f2;
}
.jumbotron.jumbotron-primary {
  background-color: #9c27b0;
  color: #ffffff;
  border-color: #75229b;
}
.jumbotron.jumbotron-default {
  background-color: #ffffff;
  color: #333333;
  border-color: #f2f2f2;
}
.jumbotron.jumbotron-success {
  background-color: #259b24;
  color: #ffffff;
  border-color: #31861f;
}
.jumbotron.jumbotron-info {
  background-color: #00bcd4;
  color: #ffffff;
  border-color: #00bbb1;
}
.jumbotron.jumbotron-warning {
  background-color: #ff5722;
  color: #ffffff;
  border-color: #ff1b08;
}
.jumbotron.jumbotron-danger {
  background-color: #e51c23;
  color: #ffffff;
  border-color: #d0183d;
}
.alert {
  box-shadow: 0 0.1em 0.2em 0 rgba(0, 0, 0, 0.258824);
  border-color: #ffe2b9;
  background-color: #fff4d3;
  color: #050505;
}
.alert.alert-primary {
  border-color: #d3a0ea;
  background-color: #e6b5ee;
  color: #050505;
}
.alert.alert-success {
  border-color: #9ce58d;
  background-color: #a2e9a2;
  color: #186317;
}
.alert.alert-warning {
  border-color: #ffb2ac;
  background-color: #ffd3c5;
  color: #dc3500;
}
.alert.alert-danger {
  border-color: #d3a0ea;
  background-color: #e6b5ee;
  color: #050505;
}
.alert.alert-info {
  border-color: #a6fffa;
  background-color: #caf9ff;
  color: #007f8f;
}
.alert.alert-default {
  border-color: #ffe2b9;
  background-color: #fff4d3;
  color: #050505;
}
/** well **/
.well {
  border: none;
  box-shadow: none;
}
.well.primary {
  background-color: #9c27b0;
}
.well.warning {
  background-color: #ff5722;
}
.well.danger {
  background-color: #e51c23;
}
.well.success {
  background-color: #259b24;
}
.well.info {
  background-color: #00bcd4;
}
/** blockquote **/
blockquote.primary {
  border-left-color: #9c27b0;
}
blockquote.warning {
  border-left-color: #ff5722;
}
blockquote.danger {
  border-left-color: #e51c23;
}
blockquote.success {
  border-left-color: #259b24;
}
blockquote.info {
  border-left-color: #00bcd4;
}
/** callout **/
.callout {
  margin: 20px 0;
  padding: 15px 30px 15px 15px;
  border-left: 5px solid #c0c0c0;
  color: #6b6b6b;
  background-color: #d1d1d1;
}
.callout.callout-default {
  border-left-color: #c0c0c0;
  background-color: #d1d1d1;
  color: #6b6b6b;
}
.callout.callout-primary {
  border-left-color: #9c27b0;
  background-color: #d580e3;
  color: #6b6b6b;
}
.callout.callout-info {
  border-left-color: #00bcd4;
  background-color: #61edff;
  color: #6b6b6b;
}
.callout.callout-warning {
  border-left-color: #259b24;
  background-color: #6fdd6e;
  color: #6b6b6b;
}
.callout.callout-warning.callout-inverse {
  border-left-color: #ff5722;
  background-color: #ffc2ae;
  color: #6b6b6b;
}
.callout.callout-success {
  border-left-color: #259b24;
  background-color: #6fdd6e;
  color: #6b6b6b;
}
.callout.callout-danger {
  border-left-color: #e51c23;
  background-color: #f39a9d;
  color: #6b6b6b;
}
.callout.callout-inverse {
  color: #d1d1d1;
  border-left-color: #d1d1d1;
  background-color: #c0c0c0;
}
.callout.callout-inverse.callout-default {
  border-left-color: #d1d1d1;
  background-color: #c0c0c0;
  color: #d1d1d1;
}
.callout.callout-inverse.callout-primary {
  border-left-color: #d580e3;
  background-color: #9c27b0;
}
.callout.callout-inverse.callout-success {
  border-left-color: #6fdd6e;
  background-color: #259b24;
}
.callout.callout-inverse.callout-info {
  border-left-color: #61edff;
  background-color: #00bcd4;
}
.callout.callout-inverse.callout-warning {
  border-left-color: #ffc2ae;
  background-color: #ff5722;
}
.callout.callout-inverse.callout-danger {
  border-left-color: #f39a9d;
  background-color: #e51c23;
}
.text-muted {
  color: #c0c0c0;
}
.text-primary {
  color: #9c27b0;
}
.text-info {
  color: #00bcd4;
}
.text-success {
  color: #259b24;
}
.text-warning {
  color: #ff5722;
}
.text-danger {
  color: #e51c23;
}
.bg-primary {
  background-color: #d582e3;
  color: #ffffff;
}
.bg-info {
  background-color: #64edff;
  color: #333333;
}
.bg-success {
  background-color: #71de70;
  color: #333333;
}
.bg-warning {
  background-color: #ffc4b1;
  color: #333333;
}
.bg-danger {
  background-color: #f49c9f;
  color: #333333;
}
/*# sourceMappingURL=bootswatch-paper.css.map */

<|start_filename|>Madb.Site/assets/styles/spacing.css<|end_filename|>
﻿/* Spacing */
.zero {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.man,
.mtn,
.mvn {
  margin-top: 0;
}
.man,
.mbn,
.mvn {
  margin-bottom: 0;
}
.man,
.mln,
.mhn {
  margin-left: 0;
}
.man,
.mrn,
.mhn {
  margin-right: 0;
}
.mas,
.mts,
.mvs {
  margin-top: 5px;
}
.mas,
.mbs,
.mvs {
  margin-bottom: 5px;
}
.mas,
.mls,
.mhs {
  margin-left: 5px;
}
.mas,
.mrs,
.mhs {
  margin-right: 5px;
}
.mam,
.mtm,
.mvm {
  margin-top: 10px;
}
.mam,
.mbm,
.mvm {
  margin-bottom: 10px;
}
.mam,
.mlm,
.mhm {
  margin-left: 10px;
}
.mam,
.mrm,
.mhm {
  margin-right: 10px;
}
.mal,
.mtl,
.mvl {
  margin-top: 20px;
}
.mal,
.mbl,
.mvl {
  margin-bottom: 20px;
}
.mal,
.mll,
.mhl {
  margin-left: 20px;
}
.mal,
.mrl,
.mhl {
  margin-right: 20px;
}
.maml,
.mlml,
.mhml {
  margin-left: 30px;
}
.maml,
.mrml,
.mhml {
  margin-right: 30px;
}
.maml,
.mtml,
.mvml {
  margin-top: 30px;
}
.maml,
.mbml,
.mvxl {
  margin-bottom: 30px;
}
.maxl,
.mlxl,
.mhxl {
  margin-left: 40px;
}
.maxl,
.mrxl,
.mhxl {
  margin-right: 40px;
}
.maxl,
.mtxl,
.mvxl {
  margin-top: 40px;
}
.maxl,
.mbxl,
.mvxl {
  margin-bottom: 40px;
}
.pan,
.ptn,
.pvn {
  padding-top: 0;
}
.pan,
.pbn,
.pvn {
  padding-bottom: 0;
}
.pan,
.pln,
.phn {
  padding-left: 0;
}
.pan,
.prn,
.phn {
  padding-right: 0;
}
.pas,
.pts,
.pvs {
  padding-top: 5px;
}
.pas,
.pbs,
.pvs {
  padding-bottom: 5px;
}
.pas,
.pls,
.phs {
  padding-left: 5px;
}
.pas,
.prs,
.phs {
  padding-right: 5px;
}
.pam,
.ptm,
.pvm {
  padding-top: 10px;
}
.pam,
.pbm,
.pvm {
  padding-bottom: 10px;
}
.pam,
.plm,
.phm {
  padding-left: 10px;
}
.pam,
.prm,
.phm {
  padding-right: 10px;
}
.pal,
.ptl,
.pvl {
  padding-top: 20px;
}
.pal,
.pbl,
.pvl {
  padding-bottom: 20px;
}
.pal,
.pll,
.phl {
  padding-left: 20px;
}
.pal,
.prl,
.phl {
  padding-right: 20px;
}
.paxs,
.prxs,
.phxs {
  padding-right: 2.5px;
}
.paxs,
.plxs,
.phxs {
  padding-left: 2.5px;
}
.paxs,
.ptxs,
.pvxs {
  padding-top: 2.5px;
}
.paxs,
.pbxs,
.pvxs {
  padding-bottom: 2.5px;
}
.paml,
.prml,
.phml {
  padding-right: 30px;
}
.paml,
.plml,
.phml {
  padding-left: 30px;
}
.paml,
.ptml,
.pvml {
  padding-top: 30px;
}
.paml,
.pbml,
.pvml {
  padding-bottom: 30px;
}
.paxl,
.prxl,
.phxl {
  padding-right: 40px;
}
.paxl,
.plxl,
.phxl {
  padding-left: 40px;
}
.paxl,
.ptxl,
.pvxl {
  padding-top: 40px;
}
.paxl,
.pbxl,
.pvxl {
  padding-bottom: 40px;
}
.tva-super {
  vertical-align: super;
}
.mtn4 {
  margin-top: -4px;
}
/*# sourceMappingURL=spacing.css.map */

<|start_filename|>Madb.Site/Models/AdSenseModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Madb.Site.Models {
	public class AdSenseModel {
		public String PublisherId { get; set; }
		public String Slot { get; set; }
		public String Name { get; set; }
	}
}

<|start_filename|>Madb.Site/Models/Documentation/TypeModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Camalot.Common.Extensions;
using Madb.Site.Extensions;

namespace Madb.Site.Models.Documentation {
	public class TypeModel {
		public Type BaseType { get; set; }
		public string Name { get; set; }
		public override string ToString() {
			return BaseType.ToSafeName();
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Extensions/ArrayHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {

		/// <summary>
		/// Swaps an unsigned value around, and puts the result in an array that can be sent to a device.
		/// </summary>
		/// <param name="value">The value to swap.</param>
		/// <param name="dest">the destination array</param>
		/// <param name="offset">offset the offset in the array where to put the swapped value.</param>
		/// <remarks>Array length must be at least offset + 4</remarks>
		public static void Swap32bitsToArray (this int value, byte[] dest, int offset ) {
			dest[offset] = (byte)( value & 0x000000FF );
			dest[offset + 1] = (byte)( ( value & 0x0000FF00 ) >> 8 );
			dest[offset + 2] = (byte)( ( value & 0x00FF0000 ) >> 16 );
			dest[offset + 3] = (byte)( ( value & 0xFF000000 ) >> 24 );
		}

		/// <summary>
		/// Reads a signed 32 bit integer from an array coming from a device.
		/// </summary>
		/// <param name="value">the array containing the int</param>
		/// <param name="offset">the offset in the array at which the int starts</param>
		/// <returns>the integer read from the array</returns>
		public static int Swap32bitFromArray ( this byte[] value, int offset ) {
			int v = 0;
			v |= ( (int)value[offset] ) & 0x000000FF;
			v |= ( ( (int)value[offset + 1] ) & 0x000000FF ) << 8;
			v |= ( ( (int)value[offset + 2] ) & 0x000000FF ) << 16;
			v |= ( ( (int)value[offset + 3] ) & 0x000000FF ) << 24;

			return v;
		}

		/// <summary>
		/// Reads an unsigned 16 bit integer from an array coming from a device,
		/// and returns it as an 'int'
		/// </summary>
		/// <param name="value">the array containing the 16 bit int (2 byte).</param>
		/// <param name="offset">the offset in the array at which the int starts</param>
		/// <remarks>Array length must be at least offset + 2</remarks>
		/// <returns>the integer read from the array.</returns>
		public static int SwapU16bitFromArray ( this byte[] value, int offset ) {
			int v = 0;
			v |= ( (int)value[offset] ) & 0x000000FF;
			v |= ( ( (int)value[offset + 1] ) & 0x000000FF ) << 8;

			return v;
		}

		/// <summary>
		/// Reads a signed 64 bit integer from an array coming from a device.
		/// </summary>
		/// <param name="value">the array containing the int</param>
		/// <param name="offset">the offset in the array at which the int starts</param>
		/// <remarks>Array length must be at least offset + 8</remarks>
		/// <returns>the integer read from the array</returns>
		public static long Swap64bitFromArray ( this byte[] value, int offset ) {
			long v = 0;
			v |= ( (long)value[offset] ) & 0x00000000000000FFL;
			v |= ( ( (long)value[offset + 1] ) & 0x00000000000000FFL ) << 8;
			v |= ( ( (long)value[offset + 2] ) & 0x00000000000000FFL ) << 16;
			v |= ( ( (long)value[offset + 3] ) & 0x00000000000000FFL ) << 24;
			v |= ( ( (long)value[offset + 4] ) & 0x00000000000000FFL ) << 32;
			v |= ( ( (long)value[offset + 5] ) & 0x00000000000000FFL ) << 40;
			v |= ( ( (long)value[offset + 6] ) & 0x00000000000000FFL ) << 48;
			v |= ( ( (long)value[offset + 7] ) & 0x00000000000000FFL ) << 56;

			return v;
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Extensions/IntegerHelper.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <ignore>true</ignore>
	public static partial class ManagedAdbExtenstions {

		/// <summary>
		/// Bits the shift right.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <param name="bits">The bits.</param>
		/// <returns></returns>
		public static Int32 BitShiftRight( this Int32 value, int bits ) {
			return (Int32)( (UInt32)value >> bits );
		}

		/// <summary>
		/// Bits the shift right.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <param name="bits">The bits.</param>
		/// <returns></returns>
		public static Int16 BitShiftRight( this Int16 value, int bits ) {
			return (Int16)( (UInt16)value >> bits );
		}

		/// <summary>
		/// Bits the shift right.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <param name="bits">The bits.</param>
		/// <returns></returns>
		public static Int64 BitShiftRight( this Int64 value, int bits ) {
			return (Int64)( (UInt64)value >> bits );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this int value ) {
			return (T)Enum.ToObject(typeof(T), value);
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this uint value ) {
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this short value ) {
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this ushort value ) {
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this long value ) {
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this ulong value ) {
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this byte value ){
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Converts the value to enum
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T ToEnum<T> ( this sbyte value ){
			return (T)Enum.ToObject ( typeof ( T ), value );
		}

		/// <summary>
		/// Reverses the byte array.
		/// </summary>
		/// <param name="inArray">The in array.</param>
		/// <returns></returns>
		public static byte[] ReverseByteArray ( this byte[] inArray ) {
			byte temp;
			int highCtr = inArray.Length - 1;

			for ( int ctr = 0; ctr < inArray.Length / 2; ctr++ ) {
				temp = inArray[ctr];
				inArray[ctr] = inArray[highCtr];
				inArray[highCtr] = temp;
				highCtr -= 1;
			}
			return inArray;
		}
	}
}


<|start_filename|>Madb.Site/assets/styles/gist.css<|end_filename|>
﻿.gist-container .gist-data-host {
  position: relative;
}
.gist-container .gist-data-host > .button-controls {
  position: absolute;
  right: 10px;
  bottom: -15px;
}
.gist-container .gist .gist-file {
  border-width: 1px;
  border-radius: 0;
}
.gist-container .gist .gist-meta {
  background: #282424 !important;
  text-shadow: none !important;
}
.gist-container .gist .gist-meta a {
  color: #2b91af !important;
}
.gist-container .gist .gist-meta a:nth-child(1) {
  display: none !important;
}
.gist-container .gist .gist-syntax {
  background: #282424 !important;
  color: #f3f3f3 !important;
  border-bottom-color: #303030 !important;
}
.gist-container .gist .gist-syntax .sx,
.gist-container .gist .gist-syntax .s {
  color: #85fb82;
}
.gist-container .gist .gist-syntax .c1 {
  color: #85fb82;
}
.gist-container .gist .gist-syntax .n,
.gist-container .gist .gist-syntax .p,
.gist-container .gist .gist-syntax .o {
  color: #f3f3f3;
}
.gist-container .gist .gist-syntax .na {
  color: #686868;
}
.gist-container .gist .gist-syntax .kt,
.gist-container .gist .gist-syntax .k {
  color: #a2c4fd;
}
.gist-container .gist .gist-syntax .nn,
.gist-container .gist .gist-syntax .nc,
.gist-container .gist .gist-syntax .nf {
  color: #fdf8b9;
}
.gist-container .gist .gist-syntax .nt {
  color: #a2c4fd;
}
.gist-container .gist .line-numbers {
  background: #282424 !important;
  color: #2b91af !important;
  border-right-color: #303030 !important;
  border-right-width: 6px !important;
}
.gist-container .gist article.markdown-body {
  padding: 10px;
}
/*# sourceMappingURL=gist.css.map */

<|start_filename|>Managed.AndroidDebugBridge/ClientData.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	public class ClientData {
		/// <summary>
		/// 
		/// </summary>
		private const String PRE_INITIALIZED = "<pre-initialized>";

		/// <summary>
		/// 
		/// </summary>
		public enum DebuggerStatus {
			/// <summary>
			/// Debugger connection status: not waiting on one, not connected to one, but accepting
			/// new connections. This is the default value.
			/// </summary>
			DEFAULT,
			/// <summary>
			/// Debugger connection status: the application's VM is paused, waiting for a debugger to connect to it before resuming.
			/// </summary>
			WAITING,
			/// <summary>
			/// Debugger connection status : Debugger is connected
			/// </summary>
			ATTACHED,
			/// <summary>
			/// Debugger connection status: The listening port for debugger connection failed to listen.
			/// No debugger will be able to connect. 
			/// </summary>
			ERROR
		}

		/// <summary>
		/// 
		/// </summary>
		public enum AllocationTrackingStatus {
				/// <summary>
				/// Allocation tracking status: unknown.
				/// This happens right after a {@link Client} is discovered
				/// by the {@link AndroidDebugBridge}, and before the {@link Client} answered the query
				/// regarding its allocation tracking status.
				/// @see Client#requestAllocationStatus()
				/// </summary>
        UNKNOWN,
				/// <summary>
				/// Allocation tracking status: the {@link Client} is not tracking allocations.
				/// </summary>
        OFF,
				/// <summary>
				/// Allocation tracking status: the {@link Client} is tracking allocations.
				/// </summary>
        ON
    }

		/// <summary>
		/// 
		/// </summary>
    public enum MethodProfilingStatus {
				/// <summary>
				/// Method profiling status: unknown.
				/// This happens right after a {@link Client} is discovered
				/// by the {@link AndroidDebugBridge}, and before the {@link Client} answered the query
				/// regarding its method profiling status.
				/// @see Client#requestMethodProfilingStatus()
				/// </summary>
        UNKNOWN,
				/// <summary>
				///  Method profiling status: the {@link Client} is not profiling method calls.
				/// </summary>
        OFF,
				/// <summary>
				/// Method profiling status: the {@link Client} is profiling method calls.
				/// </summary>
        ON
    }

		/// <summary>
		/// Name of the value representing the max size of the heap, in the Map returned by
		/// GetVmHeapInfo(int)
		/// </summary>
    public const String HEAP_MAX_SIZE_BYTES = "maxSizeInBytes"; // $NON-NLS-1$
		/// <summary>
		/// Name of the value representing the size of the heap, in the {@link Map} returned by
		/// {@link #getVmHeapInfo(int)}
		/// </summary>
    public const String HEAP_SIZE_BYTES = "sizeInBytes"; // $NON-NLS-1$
		/// <summary>
		/// Name of the value representing the number of allocated bytes of the heap, in the
		/// {@link Map} returned by {@link #getVmHeapInfo(int)}
		/// </summary>
    public const String HEAP_BYTES_ALLOCATED = "bytesAllocated"; // $NON-NLS-1$
		/// <summary>
		/// Name of the value representing the number of objects in the heap, in the {@link Map}
		/// returned by {@link #getVmHeapInfo(int)}
		/// </summary>
    public const String HEAP_OBJECTS_ALLOCATED = "objectsAllocated"; // $NON-NLS-1$

		/// <summary>
		/// String for feature enabling starting/stopping method profiling
		/// @see #hasFeature(String)
		/// </summary>
    public const String FEATURE_PROFILING = "method-trace-profiling"; // $NON-NLS-1$

		/// <summary>
		/// String for feature enabling direct streaming of method profiling data
		/// @see #hasFeature(String)
		/// </summary>
    public const String FEATURE_PROFILING_STREAMING = "method-trace-profiling-streaming"; // $NON-NLS-1$

		/// <summary>
		/// String for feature allowing to dump hprof files
		/// @see #hasFeature(String)
		/// </summary>
    public const String FEATURE_HPROF = "hprof-heap-dump"; // $NON-NLS-1$

		/// <summary>
		/// String for feature allowing direct streaming of hprof dumps
		/// @see #hasFeature(String)		/// </summary>
    public const String FEATURE_HPROF_STREAMING = "hprof-heap-dump-streaming"; // $NON-NLS-1$

		/// <summary>
		/// Initializes a new instance of the <see cref="ClientData"/> class.
		/// </summary>
		/// <param name="pid">The pid.</param>
		public ClientData ( int pid ) {
			this.Pid = pid;

			DebuggerInterest = DebuggerStatus.DEFAULT;
			//ThreadMap = new Dictionary<Integer, ThreadInfo> ( );
		}

		/// <summary>
		/// Gets the pid.
		/// </summary>
		public int Pid { get; private set; }
		/// <summary>
		/// Gets or sets the debugger interest.
		/// </summary>
		/// <value>
		/// The debugger interest.
		/// </value>
		public DebuggerStatus DebuggerInterest { get; set; }
		/// <summary>
		/// Gets or sets a value indicating whether this instance is DDM aware.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is DDM aware; otherwise, <c>false</c>.
		/// </value>
		public bool IsDdmAware { get; set; }
		/// <summary>
		/// Gets or sets the vm identifier.
		/// </summary>
		/// <value>
		/// The vm identifier.
		/// </value>
		public String VmIdentifier { get; set; }
		/// <summary>
		/// Gets or sets the description.
		/// </summary>
		/// <value>
		/// The description.
		/// </value>
		public String Description { get; set; }
		/// <summary>
		/// Gets or sets the debugger connection status.
		/// </summary>
		/// <value>
		/// The debugger connection status.
		/// </value>
		public DebuggerStatus DebuggerConnectionStatus { get; set; }
	}
}


<|start_filename|>Madb.Site/Views/Shared/_AddThisSideBarPartial.cshtml<|end_filename|>
﻿@*<!-- Go to http://www.addthis.com/get/smart-layers to customize -->*@
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-526cb7306bf16b38"></script>
<script type="text/javascript">
	addthis.layers({
		'theme': 'transparent',
		'share': {
			'position': 'left',
			'numPreferredServices': 5,
			'services': 'google_plusone_share,facebook,twitter,more'
		}
	});
</script>

<|start_filename|>Managed.AndroidDebugBridge/AndroidDebugBridge.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace Managed.Adb {
	/// <summary>
	/// The android debug bridge
	/// </summary>
	public sealed class AndroidDebugBridge {

		/// <summary>
		/// Occurs when [bridge changed].
		/// </summary>
		/// <ignore>true</ignore>
		public event EventHandler<AndroidDebugBridgeEventArgs> BridgeChanged;
		/// <summary>
		/// Occurs when [device changed].
		/// </summary>
		/// <ignore>true</ignore>
		public event EventHandler<DeviceEventArgs> DeviceChanged;
		/// <summary>
		/// Occurs when [device connected].
		/// </summary>
		/// <ignore>true</ignore>
		public event EventHandler<DeviceEventArgs> DeviceConnected;
		/// <summary>
		/// Occurs when [device disconnected].
		/// </summary>
		/// <ignore>true</ignore>
		public event EventHandler<DeviceEventArgs> DeviceDisconnected;
		/// <summary>
		/// Occurs when [client changed].
		/// </summary>
		/// <ignore>true</ignore>
		public event EventHandler<ClientEventArgs> ClientChanged;

		/*
		 * Minimum and maximum version of adb supported. This correspond to
		 * ADB_SERVER_VERSION found in //device/tools/adb/adb.h
		 */

		/// <summary>
		/// 
		/// </summary>
		private const int ADB_VERSION_MICRO_MIN = 20;
		/// <summary>
		/// 
		/// </summary>
		private const int ADB_VERSION_MICRO_MAX = -1;


		/// <summary>
		/// The regex pattern for getting the adb version
		/// </summary>
		private const String ADB_VERSION_PATTERN = "^.*(\\d+)\\.(\\d+)\\.(\\d+)$";

		private const string TAG = "adb";
#if LINUX
		/// <summary>
		/// The ADB executive
		/// </summary>
		public const String ADB = "adb";
		/// <summary>
		/// The DDMS executive
		/// </summary>
		public const String DDMS = "monitor";
		/// <summary>
		/// The hierarchy viewer
		/// </summary>
		public const String HIERARCHYVIEWER = "hierarchyviewer";
		/// <summary>
		/// The AAPT executive
		/// </summary>
		public const String AAPT = "aapt";
#else
		/// <summary>
		/// The ADB executive
		/// </summary>
		public const String ADB = "adb.exe";
		/// <summary>
		/// The DDMS executive
		/// </summary>
		public const String DDMS = "monitor.bat";
		/// <summary>
		/// The hierarchy viewer
		/// </summary>
		public const String HIERARCHYVIEWER = "hierarchyviewer.bat";
		/// <summary>
		/// The AAPT executive
		/// </summary>
		public const String AAPT = "aapt.exe";

#endif


		// Where to find the ADB bridge.
		/// <summary>
		/// The default ADB bridge port
		/// </summary>
		public const int ADB_PORT = 5037;


		/// <summary>
		/// 
		/// </summary>
		private static AndroidDebugBridge _instance;
		// <summary>
		// 
		// </summary>
		//private static bool _clientSupport;

		/// <summary>
		/// Gets or sets the socket address.
		/// </summary>
		/// <value>The socket address.</value>
		public static IPEndPoint SocketAddress { get; private set; }
		/// <summary>
		/// Gets or sets the host address.
		/// </summary>
		/// <value>The host address.</value>
		public static IPAddress HostAddress { get; private set; }

		/// <summary>
		/// Initializes the <see cref="AndroidDebugBridge"/> class.
		/// </summary>
		static AndroidDebugBridge ( ) {
			// built-in local address/port for ADB.
			try {
				HostAddress = IPAddress.Loopback;

				SocketAddress = new IPEndPoint ( HostAddress, ADB_PORT );
			} catch ( ArgumentOutOfRangeException ) {

			}
		}

		/*
		 * Initializes the <code>ddm</code> library.
		 * <p/>This must be called once <b>before</b> any call to
		 * {@link #createBridge(String, boolean)}.
		 * <p>The library can be initialized in 2 ways:
		 * <ul>
		 * <li>Mode 1: <var>clientSupport</var> == <code>true</code>.<br>The library monitors the
		 * devices and the applications running on them. It will connect to each application, as a
		 * debugger of sort, to be able to interact with them through JDWP packets.</li>
		 * <li>Mode 2: <var>clientSupport</var> == <code>false</code>.<br>The library only monitors
		 * devices. The applications are left untouched, letting other tools built on
		 * <code>ddmlib</code> to connect a debugger to them.</li>
		 * </ul>
		 * <p/><b>Only one tool can run in mode 1 at the same time.</b>
		 * <p/>Note that mode 1 does not prevent debugging of applications running on devices. Mode 1
		 * lets debuggers connect to <code>ddmlib</code> which acts as a proxy between the debuggers and
		 * the applications to debug. See {@link Client#getDebuggerListenPort()}.
		 * <p/>The preferences of <code>ddmlib</code> should also be initialized with whatever default
		 * values were changed from the default values.
		 * <p/>When the application quits, {@link #terminate()} should be called.
		 * @param clientSupport Indicates whether the library should enable the monitoring and
		 * interaction with applications running on the devices.
		 * @see AndroidDebugBridge#createBridge(String, boolean)
		 * @see DdmPreferences
		 */
		/// <summary>
		/// Initializes the <code>ddm</code> library.
		/// <para>This must be called once <b>before</b> any call to CreateBridge.</para>
		/// </summary>
		/// <param name="clientSupport">if set to <c>true</c> [client support].</param>
		public static void Initialize ( bool clientSupport ) {
			ClientSupport = clientSupport;

			/*MonitorThread monitorThread = MonitorThread.createInstance ( );
			monitorThread.start ( );

			HandleHello.register ( monitorThread );
			HandleAppName.register ( monitorThread );
			HandleTest.register ( monitorThread );
			HandleThread.register ( monitorThread );
			HandleHeap.register ( monitorThread );
			HandleWait.register ( monitorThread );
			HandleProfiling.register ( monitorThread );*/
		}

		/// <summary>
		/// Terminates the ddm library. This must be called upon application termination.
		/// </summary>
		public static void Terminate ( ) {
			// kill the monitoring services
			if ( Instance != null && Instance.DeviceMonitor != null ) {
				Instance.DeviceMonitor.Stop ( );
				Instance.DeviceMonitor = null;
			}

			/*MonitorThread monitorThread = MonitorThread.getInstance ( );
			if ( monitorThread != null ) {
				monitorThread.quit ( );
			}*/
		}


		/// <summary>
		/// Gets an instance of <see cref="AndroidDebugBridge"/>.
		/// </summary>
		/// <value>The instance.</value>
		public static AndroidDebugBridge Instance {
			get {
				if ( _instance == null ) {
					_instance = CreateBridge ( );
				}
				return _instance;
			}
		}

		/// <summary>
		/// Gets an instance of <see cref="AndroidDebugBridge"/>.
		/// </summary>
		public static AndroidDebugBridge Bridge {
			get { return Instance; }
		}

		/// <summary>
		/// Gets a value indicating whether there is client support.
		/// </summary>
		/// <value>
		///   <c>true</c> if there is client support; otherwise, <c>false</c>.
		/// </value>
		public static bool ClientSupport { get; private set; }



		/// <summary>
		/// Creates a {@link AndroidDebugBridge} that is not linked to any particular executable.
		/// This bridge will expect adb to be running. It will not be able to start/stop/restart</summary>
		/// adb.
		/// If a bridge has already been started, it is directly returned with no changes
		/// <returns></returns>
		public static AndroidDebugBridge CreateBridge ( ) {
			if ( _instance != null ) {
				return _instance;
			}

			try {
				_instance = new AndroidDebugBridge ( );
				_instance.Start ( );
				_instance.OnBridgeChanged ( new AndroidDebugBridgeEventArgs ( _instance ) );
			} catch ( ArgumentException ) {
				_instance.OnBridgeChanged ( new AndroidDebugBridgeEventArgs ( null ) );
				_instance = null;
			}

			return _instance;
		}

		/// <summary>
		/// Creates a new debug bridge from the location of the command line tool.
		/// </summary>
		/// <param name="osLocation">the location of the command line tool 'adb'</param>
		/// <param name="forceNewBridge">force creation of a new bridge even if one with the same location
		/// already exists.</param>
		/// <returns>a connected bridge.</returns>
		/// <remarks>Any existing server will be disconnected, unless the location is the same and
		/// <code>forceNewBridge</code> is set to false.
		/// </remarks>
		public static AndroidDebugBridge CreateBridge ( String osLocation, bool forceNewBridge ) {

			if ( _instance != null ) {
				if ( !String.IsNullOrEmpty ( AdbOsLocation ) && string.Compare ( AdbOsLocation, osLocation, true ) == 0 && !forceNewBridge ) {
					return _instance;
				} else {
					// stop the current server
					Log.d (TAG, "Stopping Current Instance" );
					_instance.Stop ( );
				}
			}

			try {
				_instance = new AndroidDebugBridge ( osLocation );
				_instance.Start ( );
				_instance.OnBridgeChanged ( new AndroidDebugBridgeEventArgs ( _instance ) );
			} catch ( ArgumentException ) {
				_instance.OnBridgeChanged ( new AndroidDebugBridgeEventArgs ( null ) );
				_instance = null;
			}

			return _instance;
		}

		/// <summary>
		/// Disconnects the current debug bridge, and destroy the object.
		/// </summary>
		/// <remarks>This also stops the current adb host server.</remarks>
		public static void DisconnectBridge ( ) {
			if ( _instance != null ) {
				_instance.Stop ( );

				_instance.OnBridgeChanged ( new AndroidDebugBridgeEventArgs ( null ) );
				_instance = null;
			}
		}

		/// <summary>
		/// Gets the lock.
		/// </summary>
		/// <returns></returns>
		public static object GetLock ( ) {
			return Instance;
		}

		/// <summary>
		/// Creates a new bridge.
		/// </summary>
		/// <param name="osLocation">the location of the command line tool</param>
		/// <exception cref="ArgumentException"></exception>
		/// <exception cref="FileNotFoundException"></exception>
		private AndroidDebugBridge ( String osLocation ) {
			if ( string.IsNullOrEmpty ( osLocation ) ) {
				throw new ArgumentException ( );
			}

			if ( !File.Exists ( osLocation ) ) {
				Log.w (TAG, "unable to locate adb in the specified location '{0}'", osLocation );
        throw new FileNotFoundException ( "unable to locate adb in the specified location" );
			}

			AdbOsLocation = osLocation;

			CheckAdbVersion ( );
		}

		/// <summary>
		/// Creates a new bridge not linked to any particular adb executable.
		/// </summary>
		private AndroidDebugBridge ( ) {
		}
		/// <summary>
		/// Raises the <see cref="E:BridgeChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Managed.Adb.AndroidDebugBridgeEventArgs"/> instance containing the event data.</param>
		internal void OnBridgeChanged ( AndroidDebugBridgeEventArgs e ) {
			if ( this.BridgeChanged != null ) {
				this.BridgeChanged ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:ClientChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Managed.Adb.ClientEventArgs"/> instance containing the event data.</param>
		internal void OnClientChanged ( ClientEventArgs e ) {
			if ( this.ClientChanged != null ) {
				this.ClientChanged ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:DeviceChanged"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Managed.Adb.DeviceEventArgs"/> instance containing the event data.</param>
		internal void OnDeviceChanged ( DeviceEventArgs e ) {
			if ( this.DeviceChanged != null ) {
				this.DeviceChanged ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:DeviceConnected"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Managed.Adb.DeviceEventArgs"/> instance containing the event data.</param>
		internal void OnDeviceConnected ( DeviceEventArgs e ) {
			if ( this.DeviceConnected != null ) {
				this.DeviceConnected ( this, e );
			}
		}

		/// <summary>
		/// Raises the <see cref="E:DeviceDisconnected"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Managed.Adb.DeviceEventArgs"/> instance containing the event data.</param>
		internal void OnDeviceDisconnected ( DeviceEventArgs e ) {
			if ( this.DeviceDisconnected != null ) {
				this.DeviceDisconnected ( this, e );
			}
		}

		/// <summary>
		/// Starts the debug bridge.
		/// </summary>
		/// <returns><c>true</c> if success.</returns>
		public bool Start ( ) {
			if ( String.IsNullOrEmpty(AdbOsLocation) || !VersionCheck || !StartAdb ( ) ) {
				return false;
			}

			Started = true;

			// now that the bridge is connected, we start the underlying services.
			DeviceMonitor = new DeviceMonitor ( this );
			DeviceMonitor.Start ( );

			return true;
		}

		/// <summary>
		/// Kills the debug bridge, and the adb host server.
		/// </summary>
		/// <returns><c>true</c> if success.</returns>
		public bool Stop ( ) {
			// if we haven't started we return false;
			if ( !Started ) {
				return false;
			}

			// kill the monitoring services
			if ( DeviceMonitor != null ) {
				DeviceMonitor.Stop ( );
				DeviceMonitor = null;
			}

			if ( !StopAdb ( ) ) {
				return false;
			}

			Started = false;
			return true;
		}

		/// <summary>
		/// Restarts adb, but not the services around it.
		/// </summary>
		/// <returns><c>true</c> if success.</returns>
		public bool Restart ( ) {
			if ( string.IsNullOrEmpty ( AdbOsLocation ) ) {
				Log.e ( ADB, "Cannot restart adb when AndroidDebugBridge is created without the location of adb." );
				return false;
			}

			if ( !VersionCheck ) {
				Log.LogAndDisplay ( LogLevel.Error, ADB, "Attempting to restart adb, but version check failed!" );
				return false;
			}
			lock ( this ) {
				StopAdb ( );

				bool restart = StartAdb ( );

				if ( restart && DeviceMonitor == null ) {
					DeviceMonitor = new DeviceMonitor ( this );
					DeviceMonitor.Start ( );
				}

				return restart;
			}
		}


		/// <summary>
		/// Gets or Sets the adb location on the OS.
		/// </summary>
		/// <value>The adb location on the OS.</value>
		public static string AdbOsLocation { get; set; }
		/// <summary>
		/// Gets the devices.
		/// </summary>
		/// <value>The devices.</value>
		public IList<Device> Devices {
			get {
				//if ( DeviceMonitor != null ) {
				//	return DeviceMonitor.Devices;
				//}
				//return new List<Device> ( );
				return AdbHelper.Instance.GetDevices(AndroidDebugBridge.SocketAddress);
			}
		}

		/// <summary>
		/// Returns whether the bridge has acquired the initial list from adb after being created.
		/// </summary>
		/// <remarks>
		/// <p/>Calling getDevices() right after createBridge(String, boolean) will
		/// generally result in an empty list. This is due to the internal asynchronous communication
		/// mechanism with <code>adb</code> that does not guarantee that the IDevice list has been
		/// built before the call to getDevices().
		/// <p/>The recommended way to get the list of IDevice objects is to create a
		/// IDeviceChangeListener object.
		/// </remarks>
		/// <returns>
		/// 	<c>true</c> if [has initial device list]; otherwise, <c>false</c>.
		/// </returns>
		public bool HasInitialDeviceList ( ) {
			if ( DeviceMonitor != null ) {
				return DeviceMonitor.HasInitialDeviceList;
			}
			return false;
		}

		/// <summary>
		/// Gets or sets the client to accept debugger connection on the custom "Selected debug port".
		/// </summary>
		/// <remarks>Not Yet Implemented</remarks>
		public IClient SelectedClient {
			get {
				/*MonitorThread monitorThread = MonitorThread.Instance;
				if ( monitorThread != null ) {
					return monitorThread.SelectedClient = selectedClient;
				}*/
				return null;
			}
			set {
				/*MonitorThread monitorThread = MonitorThread.Instance;
				if ( monitorThread != null ) {
					monitorThread.SelectedClient = value;
				}*/
			}
		}
		/// <summary>
		/// Returns whether the AndroidDebugBridge object is still connected to the adb daemon.
		/// </summary>
		/// <value><c>true</c> if this instance is connected; otherwise, <c>false</c>.</value>
		public bool IsConnected {
			get {
				//MonitorThread monitorThread = MonitorThread.Instance;
				if ( DeviceMonitor != null /* && monitorThread != null */ ) {
					return DeviceMonitor.IsMonitoring /* && monitorThread.State != State.TERMINATED*/;
				}
				return false;
			}
		}

		/// <summary>
		/// Returns the number of times the AndroidDebugBridge object attempted to connect
		/// </summary>
		/// <value>The connection attempt count.</value>
		public int ConnectionAttemptCount {
			get {
				if ( DeviceMonitor != null ) {
					return DeviceMonitor.ConnectionAttemptCount;
				}
				return -1;
			}
		}

		/// <summary>
		/// Returns the number of times the AndroidDebugBridge object attempted to restart
		/// the adb daemon.
		/// </summary>
		/// <value>The restart attempt count.</value>
		public int RestartAttemptCount {
			get {
				if ( DeviceMonitor != null ) {
					return DeviceMonitor.RestartAttemptCount;
				}
				return -1;
			}
		}

		/// <summary>
		/// Gets the device monitor
		/// </summary>
		public DeviceMonitor DeviceMonitor { get; private set; }

		/// <summary>
		/// Gets if the adb host has started
		/// </summary>
		private bool Started { get; set; }
		/// <summary>
		/// Gets the result of the version check
		/// </summary>
		private bool VersionCheck { get; set; }

		/// <summary>
		/// Queries adb for its version number and checks it against #MIN_VERSION_NUMBER and MAX_VERSION_NUMBER
		/// </summary>
		private void CheckAdbVersion ( ) {
			// default is bad check
			VersionCheck = false;

			if ( string.IsNullOrEmpty ( AdbOsLocation ) ) {
				Log.w(TAG, "AdbOsLocation is Empty" );
				return;
			}

			try {
				Log.d ( DDMS, String.Format ( "Checking '{0} version'", AdbOsLocation ) );

				ProcessStartInfo psi = new ProcessStartInfo ( AdbOsLocation, "version" );
				psi.WindowStyle = ProcessWindowStyle.Hidden;
				psi.CreateNoWindow = true;
				psi.UseShellExecute = false;
				psi.RedirectStandardError = true;
				psi.RedirectStandardOutput = true;

				List<String> errorOutput = new List<String> ( );
				List<String> stdOutput = new List<String> ( );
				using ( Process proc = Process.Start ( psi ) ) {
					int status = GrabProcessOutput ( proc, errorOutput, stdOutput, true /* waitForReaders */);
					if ( status != 0 ) {
						StringBuilder builder = new StringBuilder ( "'adb version' failed!" );
						builder.AppendLine ( string.Empty );
						foreach ( String error in errorOutput ) {
							builder.AppendLine ( error );
						}
						Log.LogAndDisplay ( LogLevel.Error, TAG, builder.ToString ( ) );
					}
				}

				// check both stdout and stderr
				bool versionFound = false;
				foreach ( String line in stdOutput ) {
					versionFound = ScanVersionLine ( line );
					if ( versionFound ) {
						break;
					}
				}

				if ( !versionFound ) {
					foreach ( String line in errorOutput ) {
						versionFound = ScanVersionLine ( line );
						if ( versionFound ) {
							break;
						}
					}
				}

				if ( !versionFound ) {
					// if we get here, we failed to parse the output.
					Log.LogAndDisplay ( LogLevel.Error, ADB, "Failed to parse the output of 'adb version'" ); 
				}

			} catch ( IOException e ) {
				Log.LogAndDisplay ( LogLevel.Error, ADB, "Failed to get the adb version: " + e.Message ); 
			} 
		}

		/// <summary>
		/// Scans a line resulting from 'adb version' for a potential version number.
		/// </summary>
		/// <param name="line">The line to scan.</param>
		/// <returns><c>true</c> if a version number was found (whether it is acceptable or not).</returns>
		/// <remarks>If a version number is found, it checks the version number against what is expected
		/// by this version of ddms.</remarks>
		private bool ScanVersionLine ( String line ) {
			if ( !string.IsNullOrEmpty ( line ) ) {
				Match matcher = Regex.Match ( line, ADB_VERSION_PATTERN );
				if ( matcher.Success ) {
					int majorVersion = int.Parse ( matcher.Groups[1].Value );
					int minorVersion = int.Parse ( matcher.Groups[2].Value );
					int microVersion = int.Parse ( matcher.Groups[3].Value );

					// check only the micro version for now.
					if ( microVersion < ADB_VERSION_MICRO_MIN ) {
						String message = String.Format ( "Required minimum version of adb: {0}.{1}.{2}. Current version is {0}.{1}.{3}",
										majorVersion, minorVersion, ADB_VERSION_MICRO_MIN, microVersion );
						Log.LogAndDisplay ( LogLevel.Error, ADB, message );
					} else if ( ADB_VERSION_MICRO_MAX != -1 && microVersion > ADB_VERSION_MICRO_MAX ) {
						String message = String.Format ( "Required maximum version of adb: {0}.{1}.{2}. Current version is {0}.{1}.{3}", 
										majorVersion, minorVersion, ADB_VERSION_MICRO_MAX, microVersion );
						Log.LogAndDisplay ( LogLevel.Error, ADB, message );
					} else {
						VersionCheck = true;
					}
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Starts the adb host side server.
		/// </summary>
		/// <returns>true if success</returns>
		private bool StartAdb ( ) {
			if ( string.IsNullOrEmpty ( AdbOsLocation ) ) {
				Log.e ( ADB, "Cannot start adb when AndroidDebugBridge is created without the location of adb." ); 
				return false;
			}

			int status = -1;

			try {
				String command = "start-server";
				Log.d ( DDMS, String.Format ( "Launching '{0} {1}' to ensure ADB is running.", AdbOsLocation, command ) );
				ProcessStartInfo psi = new ProcessStartInfo ( AdbOsLocation, command );
				psi.CreateNoWindow = true;
				psi.WindowStyle = ProcessWindowStyle.Hidden;
				psi.UseShellExecute = false;
				psi.RedirectStandardError = true;
				psi.RedirectStandardOutput = true;

				using ( Process proc = Process.Start ( psi ) ) {
					List<String> errorOutput = new List<String> ( );
					List<String> stdOutput = new List<String> ( );
					status = GrabProcessOutput ( proc, errorOutput, stdOutput, false /* waitForReaders */);
				}
			} catch ( IOException ioe ) {
				Log.d ( DDMS, "Unable to run 'adb': {0}", ioe.Message );
			} catch ( ThreadInterruptedException ie ) {
				Log.d ( DDMS, "Unable to run 'adb': {0}", ie.Message );
			} catch ( Exception e ) {
				Log.e ( DDMS, e );
			}

			if ( status != 0 ) {
				Log.w ( DDMS, "'adb start-server' failed -- run manually if necessary" );
				return false;
			}

			Log.d ( DDMS, "'adb start-server' succeeded" );
			return true;
		}

		/// <summary>
		/// Stops the adb host side server.
		/// </summary>
		/// <returns>true if success</returns>
		private bool StopAdb ( ) {
			if ( string.IsNullOrEmpty ( AdbOsLocation ) ) {
				Log.e ( ADB, "Cannot stop adb when AndroidDebugBridge is created without the location of adb." );
				return false;
			}
			int status = -1;

			try {
				String command = "kill-server";
				ProcessStartInfo psi = new ProcessStartInfo ( AdbOsLocation, command );
				psi.CreateNoWindow = true;
				psi.WindowStyle = ProcessWindowStyle.Hidden;
				psi.UseShellExecute = false;
				psi.RedirectStandardError = true;
				psi.RedirectStandardOutput = true;

				using ( Process proc = Process.Start ( psi ) ) {
					proc.WaitForExit ( );
					status = proc.ExitCode;
				}
			} catch ( IOException ) {
				// we'll return false;
			} catch ( Exception ) {
				// we'll return false;
			}

			if ( status != 0 ) {
				Log.w ( DDMS, "'adb kill-server' failed -- run manually if necessary" ); 
				return false;
			}

			Log.d ( DDMS, "'adb kill-server' succeeded" ); 
			return true;
		}

		/// <summary>
		/// Get the stderr/stdout outputs of a process and return when the process is done.
		/// Both <b>must</b> be read or the process will block on windows.
		/// </summary>
		/// <param name="process">The process to get the ouput from</param>
		/// <param name="errorOutput">The array to store the stderr output. cannot be null.</param>
		/// <param name="stdOutput">The array to store the stdout output. cannot be null.</param>
		/// <param name="waitforReaders">if true, this will wait for the reader threads.</param>
		/// <returns>the process return code.</returns>
		private int GrabProcessOutput ( Process process, List<String> errorOutput, List<String> stdOutput, bool waitforReaders ) {
			if ( errorOutput == null ) {
				throw new ArgumentNullException ( "errorOutput" );
			}
			if ( stdOutput == null ) {
				throw new ArgumentNullException ( "stdOutput" );
			}
			// read the lines as they come. if null is returned, it's
			// because the process finished
			Thread t1 = new Thread ( new ThreadStart ( delegate {
				// create a buffer to read the stdoutput
				try {
					using ( StreamReader sr = process.StandardError ) {
						while ( !sr.EndOfStream ) {
							String line = sr.ReadLine ( );
							if ( !String.IsNullOrEmpty ( line ) ) {
								Log.e ( ADB, line );
								errorOutput.Add ( line );
							}
						}
					}
				} catch ( Exception ) {
					// do nothing.
				}
			} ) );

			Thread t2 = new Thread ( new ThreadStart ( delegate {
				// create a buffer to read the std output
				try {
					using ( StreamReader sr = process.StandardOutput ) {
						while ( !sr.EndOfStream ) {
							String line = sr.ReadLine ( );
							if ( !String.IsNullOrEmpty ( line ) ) {
								stdOutput.Add ( line );
							}
						}
					}
				} catch ( Exception ) {
					// do nothing.
				}
			} ) );

			t1.Start ( );
			t2.Start ( );

			// it looks like on windows process#waitFor() can return
			// before the thread have filled the arrays, so we wait for both threads and the
			// process itself.
			if ( waitforReaders ) {
				try {
					t1.Join ( );
				} catch ( ThreadInterruptedException ) {
				}
				try {
					t2.Join ( );
				} catch ( ThreadInterruptedException ) {
				}
			}

			// get the return code from the process
			process.WaitForExit ( );
			return process.ExitCode;
		}

	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/DeviceNotFoundException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// Unable to connect to the device because it was not found in the list of available devices.
	/// </summary>
	public class DeviceNotFoundException : AdbException {
		/// <summary>
		/// Initializes a new instance of the <see cref="DeviceNotFoundException"/> class.
		/// </summary>
		public DeviceNotFoundException( ) : base("The device was not found.") {
				
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="DeviceNotFoundException"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public DeviceNotFoundException( String device )
			: base ( "The device '" + device + "' was not found." ) {

		}
	}
}


<|start_filename|>Madb.Site/Extensions/Type.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Camalot.Common.Extensions;

namespace Madb.Site.Extensions {
	public  static partial class MadbSiteExtensions {
		public static bool IsInNamespace(this Type type, string @namespace) {
			return type != null && !string.IsNullOrWhiteSpace(type.Namespace) && type.Namespace.Equals(@namespace, StringComparison.InvariantCulture);
		}

		public static bool IsInChildNamespace(this Type type, string rootNamespace) {
			return type != null && !string.IsNullOrWhiteSpace(type.Namespace) && type.Namespace.StartsWith(rootNamespace, StringComparison.InvariantCulture) && !type.Namespace.Equals(rootNamespace, StringComparison.InvariantCulture);
		}

		public static string ToSafeName(this Type type) {
			if(type.IsGenericType) {
				var gparams = type.GetGenericArguments();
				var len = type.Name.IndexOf("`");
				if(len <= 0) {
					len = type.Name.Length;
				}
				return "{0}{1}".With(gparams.Count() > 0 ? type.Name.Substring(0,len) : type.Name, gparams.Count() > 0 ? "<{0}>".With(String.Join(", ", gparams.Select(g => g.ToSafeName()))) : "");
			} else {
				return type.Name;
			}
		}



		public static string ToSafeFullName(this Type type) {
				return "{1}.{0}".With(ToSafeName(type), type.Namespace);
		}

		public static string ToSafeUrlFullName(this Type type) {
			return "{1}.{0}".With(type.Name.REReplace(@"\[|\]",""), type.Namespace);
		}
		
	}
}

<|start_filename|>Madb.Site/Views/Documentation/_NugetPartial.cshtml<|end_filename|>
﻿<div id="nuget">
	@(Html.Partial("_AdPartial"))
	<div class="panel panel-success pan">
		<div class="panel-heading"><h1 class="zero lowercase"><i class="fa fa-download mrm"></i>Nuget</h1></div>
		<div class="panel-body">
			<div class="nuget-badge mtl">
				<code class="">PM&gt; <span data-id="Managed.Adb">Install-Package Managed.Adb</span></code>
				<div class="pull-right mtn4 mrs">
					<a title="copy" href="#" data-copy="click" data-copy-target="[data-id='Managed.Adb']" class="btn btn-round btn-info z-depth-1 mtml mrs"><i class="fa fa-copy"></i></a>
					<a title="Visit nuget.org" href="https://nuget.org/packages/managed.adb/" target="_blank" class="btn btn-round btn-success z-depth-1 mtml"><i class="fa fa-external-link"></i></a>
				</div>
			</div>
			<div class="clearfix"></div>
		</div>
	</div>
</div>

<|start_filename|>Madb.Site/Views/Shared/_Layout.cshtml<|end_filename|>
﻿<!DOCTYPE html>
<html lang="en">
<head prefix="og:http://ogp.me/ns# fb:http://ogp.me/ns/fb#">
	<meta charset="utf-8" />
	<title>@(Html.SiteName()):@(ViewBag.Title)</title>

	<link href="~/assets/images/madbee-16.png" rel="shortcut icon" type="image/png" />
	<meta name="msapplication-TileColor" content="#FFFFFF">
	<meta name="msapplication-TileImage" content="~/assets/images/madbee-144.png">

	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="~/assets/images/madbee-152.png">
	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="~/assets/images/madbee-152.png">
	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="~/assets/images/madbee-144.png">
	<link rel="apple-touch-icon-precomposed" sizes="120x120" href="~/assets/images/madbee-120.png">
	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="~/assets/images/madbee-114.png">
	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="~/assets/images/madbee-72.png">
	<link rel="apple-touch-icon-precomposed" href="~/assets/images/madbee-57.png">
	<link href="~/assets/images/madbee-32.png" sizes="32x32" rel="icon" type="image/png" />

	<meta name="viewport" content="width=device-width" />
	<meta property="og:title" content="@(ViewBag.Title)" />
	<meta property="og:image" content="~/assets/images/madbee-152.png" />
	<meta property="og:description" content="A managed port of the Android Debug Bridge." />

	@(Styles.Render("~/css/site"))
	@(RenderSection("styles", required: false))
</head>

<body>
	<header>
		@(Html.Partial("_Navbar"))
	</header>
	<div class="container root epm-nav-expanded" data-spy="scroll" data-target=".epm-nav > .nav">
		@(RenderSection("featured", required: false))
		@(RenderBody())
	</div>
	<div class="clear-fix"></div>


	<footer class="navbar-fixed-bottom navbar navbar-default">
		<div class="container">
			<div class="center mts text-white">
				<p>Copyright &copy; <NAME> @DateTime.Now.Year. All Rights Reserved.</p>
			</div>
		</div>
	</footer>

	@(Scripts.Render("~/js/jquery"))
	@(Scripts.Render("~/js/bootstrap"))
	@(Scripts.Render("~/js/mousetrap"))
	@(Scripts.Render("~/js/system"))
	@(Html.Partial("_SideNavPartial"))
	@(RenderSection("scripts", required: false))
	@(Html.Partial("Analytics"))
	@*@(Html.Partial("_AddThisSideBarPartial"))*@

	<div class="go-to-top fade" data-scroll-show-low="265" data-scroll-toggle="fade">
		<a href="#home" data-scroll="click" class="btn btn-round btn-success btn-lg"><i class="fa fa-arrow-up"></i></a>
	</div>


</body>
</html>


<|start_filename|>Managed.AndroidDebugBridge/DeviceEventArgs.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="System.EventArgs" />
	public class DeviceEventArgs : EventArgs {

		/// <summary>
		/// Initializes a new instance of the <see cref="DeviceEventArgs"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public DeviceEventArgs ( IDevice device ) {
			this.Device = device;
		}

		/// <summary>
		/// Gets the device.
		/// </summary>
		/// <value>The device.</value>
		public IDevice Device { get; private set; }

	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/Escape.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camalot.Common.Extensions;
using Managed.Adb.IO;
using Ploeh.AutoFixture;
using Xunit;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	public class Escape {
		[Fact]
		public void WhenPathIsNull_ShouldReturnThrowArgumentNullException () {
			Assert.Throws<ArgumentException>(() => {
				LinuxPath.Escape ( null );
			} );
		}

		[Fact]
		public void WhenPathIsEmpty_ShouldReturnThrowArgumentNullException ( ) {
			Assert.Throws<ArgumentException> ( ( ) => {
				LinuxPath.Escape ( string.Empty );
			} );
		}


		[Fact]
		public void WhenPathDoesNotContainCharactersToEscape_ShouldReturnPathUnchanged ( ) {
			var fixture = new Fixture ( );
			var p1 = fixture.Create ( "p1-" );
			var result = LinuxPath.Escape ( p1 );
			Assert.Equal ( p1, result );
		}

		[Fact]
		public void WhenPathContiansCharacterToEscape_ShouldReturnEscapedString ( ) {
			var chars = @"\()*+?""'#/".ToCharArray();
			var fixture = new Fixture ( );

			foreach ( var c in chars ) {
				var b = "before-";
				var a = "-after";
				var check = "{0}{1}{2}".With ( b, c, a);
				var result = LinuxPath.Escape ( check );
				Assert.Equal ( "{0}\\{1}{2}".With ( b, c, a ), result );
			}
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/IO/LinuxPath.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Camalot.Common.Extensions;

namespace Managed.Adb.IO {
	/// <summary>
	/// Just like System.IO.Path, except it is geared for Linux
	/// </summary>
	public static class LinuxPath {

		/// <summary>
		/// Pattern to escape filenames for shell command consumption.
		/// </summary>
		private const string ESCAPEPATTERN = @"([\\\(\)*+?""'\#/])";

		/// <summary>
		/// The directory separator character
		/// </summary>
		public static readonly char DirectorySeparatorChar = '/';
		/// <summary>
		/// The directory separator alternate character
		/// </summary>
		public static readonly char AltDirectorySeparatorChar = '/';
		/// <summary>
		/// Invalid characters for a file name
		/// </summary>
		private static readonly char[] InvalidFileNameChars = new char[] {
						'"', '<', '>', '|', '\0', '\x0001', '\x0002', '\x0003', '\x0004', '\x0005', '\x0006', '\a', '\b', '\t', '\n', '\v',
						'\f', '\r', '\x000e', '\x000f', '\x0010', '\x0011', '\x0012', '\x0013', '\x0014', '\x0015', '\x0016', '\x0017', '\x0018', '\x0019', '\x001a', '\x001b',
						'\x001c', '\x001d', '\x001e', '\x001f', '*', '?', '\\', '/'
				 };
		/// <summary>
		/// The max length of a directory path
		/// </summary>
		internal const int MAX_DIRECTORY_PATH = 0xf8;
		/// <summary>
		/// the max length of a file path
		/// </summary>
		internal const int MAX_PATH = 260;
		/// <summary>
		/// the max length of a file path
		/// </summary>
		internal static readonly int MaxPath = 260;
		/// <summary>
		/// The character used to separate multiple paths
		/// </summary>
		public static readonly char PathSeparator = ';';
		/// <summary>
		/// Invalid characters for a file/directory path
		/// </summary>
		private static readonly char[] RealInvalidPathChars = new char[] {
						'"', '<', '>', '|', '\0', '\x0001', '\x0002', '\x0003', '\x0004', '\x0005', '\x0006', '\a', '\b', '\t', '\n', '\v',
						'\f', '\r', '\x000e', '\x000f', '\x0010', '\x0011', '\x0012', '\x0013', '\x0014', '\x0015', '\x0016', '\x0017', '\x0018', '\x0019', '\x001a', '\x001b',
						'\x001c', '\x001d', '\x001e', '\x001f'
				 };

		/// <summary>Changes the extension of a path string.</summary>
		/// <returns>A string containing the modified path information.On Windows-based desktop platforms, if path is null or an empty string (""), the path information is returned unmodified. If extension is null, the returned string contains the specified path with its extension removed. If path has no extension, and extension is not null, the returned path string contains extension appended to the end of path.</returns>
		/// <param name="extension">The new extension (with a leading period). Specify null to remove an existing extension from path. </param>
		/// <param name="path">The path information to modify. The path cannot contain any of the characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>. </param>
		/// <exception cref="T:System.ArgumentException">The path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static string ChangeExtension ( string path, string extension ) {
			if ( path == null ) {
				return null;
			}
			CheckInvalidPathChars ( path );
			string str = path;
			int length = path.Length;
			while ( --length >= 0 ) {
				char ch = path[length];
				if ( ch == '.' ) {
					str = path.Substring ( 0, length );
					break;
				}
				if ( IsDirectorySeparator(ch) ) {
					break;
				}
			}
			if ( string.IsNullOrWhiteSpace ( extension ) || path.Length == 0 ) {
				return path;
			}
			if ( extension.Length > 0 && extension[0] != '.' ) {
				str = str + ".";
			}

			return ( str + extension );
		}

		/// <summary>
		/// Checks the invalid path chars.
		/// </summary>
		/// <param name="path">The path.</param>
		internal static void CheckInvalidPathChars ( string path ) {
			for ( int i = 0; i < path.Length; i++ ) {
				int num2 = path[i];
				if ( ( ( num2 == 0x22 ) || ( num2 == 60 ) ) || ( ( ( num2 == 0x3e ) || ( num2 == 0x7c ) ) || ( num2 < 0x20 ) ) ) {
					throw new ArgumentException ( "Path contains invalid characters" );
				}
			}
		}

		/// <summary>
		/// Combine the specified paths to form one path
		/// </summary>
		/// <param name="paths">The paths.</param>
		/// <returns></returns>
		public static string Combine ( params string[] paths ) {
			if ( paths == null ) {
				throw new ArgumentNullException ( "paths" );
			}
			int capacity = 0;
			int num2 = 0;
			for ( int i = 0; i < paths.Length; i++ ) {
				if ( paths[i] == null ) {
					throw new ArgumentNullException ( "paths" );
				}
				if ( paths[i].Length != 0 ) {
					CheckInvalidPathChars ( paths[i] );
					if ( IsPathRooted ( paths[i] ) ) {
						num2 = i;
						capacity = paths[i].Length;
					} else {
						capacity += paths[i].Length;
					}
					char ch = paths[i][paths[i].Length - 1];
					if ( !IsDirectorySeparator(ch) ) {
						capacity++;
					}
				}
			}
			var builder = new StringBuilder ( capacity );
			for ( int j = num2; j < paths.Length; j++ ) {
				if ( paths[j].Length != 0 ) {
					if ( builder.Length == 0 ) {
						builder.Append ( FixupPath ( paths[j] ) );
					} else {
						char ch2 = builder[builder.Length - 1];
						if ( !IsDirectorySeparator(ch2) ) {
							builder.Append ( DirectorySeparatorChar );
						}
						builder.Append ( paths[j] );
					}
				}
			}
			return builder.ToString ( );

		}


		/// <summary>Returns the directory information for the specified path string.</summary>
		/// <returns>A <see cref="T:System.String"></see> containing directory information for path, or null if path denotes a root directory, is the empty string (""), or is null. Returns <see cref="F:System.String.Empty"></see> if path does not contain directory information.</returns>
		/// <param name="path">The path of a file or directory. </param>
		/// <exception cref="T:System.ArgumentException">The path parameter contains invalid characters, is empty, or contains only white spaces, or contains a wildcard character. </exception>
		/// <exception cref="T:System.IO.PathTooLongException">The path parameter is longer than the system-defined maximum length.</exception>
		/// <filterpriority>1</filterpriority>
		public static string GetDirectoryName ( string path ) {
			if ( path != null ) {
				CheckInvalidPathChars ( path );
				var tpath = path;
				if ( EndsWithDirectorySeparator(tpath) ) {
					return FixupPath ( tpath );
				} else {
					var end = tpath.LastIndexOfAny ( new char[] { DirectorySeparatorChar, AltDirectorySeparatorChar } );
					end = end < 0 ? tpath.Length : end;
					return FixupPath ( tpath.Substring ( 0, end ) );
				}
			}
			return null;
		}

		/// <summary>
		/// Gets the path without file name.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public static string GetPathWithoutFile ( string path ) {
			if ( path != null ) {
				CheckInvalidPathChars ( path );
				string tfilename = GetFileName ( path );
				string tpath = path.Substring ( 0, path.Length - tfilename.Length );
				tpath = FixupPath ( tpath );
				return tpath.Substring ( 0, tpath.LastIndexOfAny ( new char[] { DirectorySeparatorChar, AltDirectorySeparatorChar } ) + 1 );
			}
			return null;
		}

		/// <summary>
		/// Fixups the path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		private static string FixupPath ( string path ) {
			string sb = path;
			sb = sb.Replace ( System.IO.Path.DirectorySeparatorChar, DirectorySeparatorChar );


			if ( !StartsWithDirectorySeparator(sb) ) {
				sb = string.Format ( ".{0}{1}", DirectorySeparatorChar, sb );
			}

			if ( !EndsWithDirectorySeparator(sb) ) {
				sb = string.Format ( "{0}{1}", sb, DirectorySeparatorChar );
			}

			sb = sb.Replace ( "//", new byte[] { (byte)DirectorySeparatorChar }.GetString ( ) );

			return sb;
		}

		/// <summary>Returns the extension of the specified path string.</summary>
		/// <returns>A <see cref="T:System.String"></see> containing the extension of the specified path (including the "."), null, or <see cref="F:System.String.Empty"></see>. If path is null, GetExtension returns null. If path does not have extension information, GetExtension returns Empty.</returns>
		/// <param name="path">The path string from which to get the extension. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static string GetExtension ( string path ) {
			if ( path == null ) {
				return null;
			}
			CheckInvalidPathChars ( path );
			int length = path.Length;
			int startIndex = length;
			while ( --startIndex >= 0 ) {
				char ch = path[startIndex];
				if ( ch == '.' ) {
					if ( startIndex != ( length - 1 ) ) {
						return path.Substring ( startIndex, length - startIndex );
					}
					return string.Empty;
				}
				if ( IsDirectorySeparator ( ch ) ) {
					break;
				}
			}
			return string.Empty;
		}

		/// <summary>Returns the file name and extension of the specified path string.</summary>
		/// <returns>A <see cref="T:System.String"></see> consisting of the characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns <see cref="F:System.String.Empty"></see>. If path is null, this method returns null.</returns>
		/// <param name="path">The path string from which to obtain the file name and extension. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static string GetFileName ( string path ) {
			if ( path != null ) {
				CheckInvalidPathChars ( path );
				int length = path.Length;
				int num2 = length;
				while ( --num2 >= 0 ) {
					char ch = path[num2];
					if ( IsDirectorySeparator ( ch ) ) {
						return path.Substring ( num2 + 1, ( length - num2 ) - 1 );
					}
				}
			}
			return path;
		}

		/// <summary>Returns the file name of the specified path string without the extension.</summary>
		/// <returns>A <see cref="T:System.String"></see> containing the string returned by <see cref="M:System.IO.Path.GetFileName(System.String)"></see>, minus the last period (.) and all characters following it.</returns>
		/// <param name="path">The path of the file. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static string GetFileNameWithoutExtension ( string path ) {
			path = GetFileName ( path );
			if ( path == null ) {
				return null;
			}
			int length = path.LastIndexOf ( '.' );
			if ( length == -1 ) {
				return path;
			}
			return path.Substring ( 0, length );
		}


		/// <summary>Gets an array containing the characters that are not allowed in file names.</summary>
		/// <returns>An array containing the characters that are not allowed in file names.</returns>
		public static char[] GetInvalidFileNameChars ( ) {
			return (char[])InvalidFileNameChars.Clone ( );
		}

		/// <summary>Gets an array containing the characters that are not allowed in path names.</summary>
		/// <returns>An array containing the characters that are not allowed in path names.</returns>
		public static char[] GetInvalidPathChars ( ) {
			return (char[])RealInvalidPathChars.Clone ( );
		}

		/// <summary>Gets the root directory information of the specified path.</summary>
		/// <returns>A string containing the root directory of path, such as "C:\", or null if path is null, or an empty string if path does not contain root directory information.</returns>
		/// <param name="path">The path from which to obtain root directory information. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character.-or- <see cref="F:System.String.Empty"></see> was passed to path. </exception>
		/// <filterpriority>1</filterpriority>
		public static string GetPathRoot ( string path ) {
			if ( path == null ) {
				return null;
			}
			path = FixupPath ( path );
			return path.Substring ( 0, GetRootLength ( path ) );
		}

		/// <summary>
		/// Gets the length of the root.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		internal static int GetRootLength ( string path ) {
			CheckInvalidPathChars ( path );
			int num = 0;
			int length = path.Length;
			if ( ( length >= 1 ) && IsDirectorySeparator ( path[0] ) ) {
				num = 1;
				if ( ( length >= 2 ) && IsDirectorySeparator ( path[1] ) ) {
					num = 2;
					int num3 = 2;
					while ( ( num < length ) && !IsDirectorySeparator(path[num] ) || ( --num3 > 0 ) ) {
						num++;
					}
				}
				return num;
			}
			if ( ( length >= 2 ) ) {
				num = 2;
				if ( ( length >= 3 ) && IsDirectorySeparator ( path[2] ) ) {
					num++;
				}
			}
			return num;
		}

		/// <summary>Determines whether a path includes a file name extension.</summary>
		/// <returns>true if the characters that follow the last directory separator (\\ or /) or volume separator (:) in the path include a period (.) followed by one or more characters; otherwise, false.</returns>
		/// <param name="path">The path to search for an extension. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static bool HasExtension ( string path ) {
			if ( path != null ) {
				CheckInvalidPathChars ( path );
				if ( EndsWithDirectorySeparator ( path ) ) {
					return false;
				}

				int length = path.Length;
				while ( --length >= 0 ) {
					char ch = path[length];
					if ( ch == '.' ) {
						return ( length != ( path.Length - 1 ) );
					}
					if ( IsDirectorySeparator ( ch ) ) {
						break;
					}
				}
			}
			return false;
		}

		internal static bool IsDirectorySeparator ( char c ) {
			if ( c != DirectorySeparatorChar ) {
				return ( c == AltDirectorySeparatorChar );
			}
			return true;
		}

		internal static bool EndsWithDirectorySeparator ( string path ) {
			return path.EndsWith ( new string ( new char[] { DirectorySeparatorChar } ) ) || path.EndsWith ( new string ( new char[] { AltDirectorySeparatorChar } ) );
		}

		internal static bool StartsWithDirectorySeparator ( string path ) {
			return path.StartsWith ( new string ( new char[] { DirectorySeparatorChar } ) ) || path.StartsWith ( new string ( new char[] { AltDirectorySeparatorChar } ) );
		}

		/// <summary>Gets a value indicating whether the specified path string contains absolute or relative path information.</summary>
		/// <returns>true if path contains an absolute path; otherwise, false.</returns>
		/// <param name="path">The path to test. </param>
		/// <exception cref="T:System.ArgumentException">path contains one or more of the invalid characters defined in <see cref="F:System.IO.Path.InvalidPathChars"></see>, or contains a wildcard character. </exception>
		/// <filterpriority>1</filterpriority>
		public static bool IsPathRooted ( string path ) {
			if ( path != null ) {
				CheckInvalidPathChars ( path );
				int length = path.Length;
				if ( ( length >= 1 && IsDirectorySeparator ( path[0] ) ) ||
					( length == 1 ) ) {
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Returns an escaped version of the entry name.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		/// <exception cref="ArgumentNullException">When path is null.</exception>
		public static string Escape ( string path ) {
			return path.Require ( ).REReplace(ESCAPEPATTERN, new MatchEvaluator ( delegate ( Match m) {
				return m.Result ( "\\$1" );
			} ) );
		}

		/// <summary>
		/// Quotes the specified path.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public static string Quote ( string path ) {
			if ( string.IsNullOrEmpty(path) ) {
				return path;
			}

			if(path.IsMatch(@"\s")) {
				return "\"{0}\"".With ( path );
			} else {
				return path;
			}
		}


	}
}


<|start_filename|>Madb.Site/assets/Scripts/system.expandable.js<|end_filename|>
﻿(function ($, document, window) {
	"use strict";

	$(function () {
		$("[data-expandable]").each(function (i, item) {
			var self = $(this);
			if (self.data("expandable-setup")) { return; }
			self.data("expandable-setup", true);

			var trigger = self.data("expandable") || "click";
			self.on(trigger, function (event) {
				var $t = $(this);
				var target = $($t.data("expandable-target"));
				var toggle = $t.data("expandable-toggle");
				if (target.hasClass(toggle)) {
					target.removeClass(toggle);
				} else {
					target.addClass(toggle);
				}
			});

		});
	});
})(window.jQuery, window.document,window);

<|start_filename|>Managed.AndroidDebugBridge/DeviceMonitor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using MoreLinq;

namespace Managed.Adb {
	/// <summary>
	/// A Device monitor. This connects to the Android Debug Bridge and get device and
	/// debuggable process information from it.
	/// </summary>
	public class DeviceMonitor {
		/// <summary>
		/// 
		/// </summary>
		private const String TAG = "DeviceMonitor";

		/// <summary>
		/// 
		/// </summary>
		private byte[] LengthBuffer = null;
		/// <summary>
		/// 
		/// </summary>
		private byte[] LengthBuffer2 = null;


		/// <summary>
		/// Initializes a new instance of the <see cref="DeviceMonitor"/> class.
		/// </summary>
		/// <param name="bridge">The bridge.</param>
		public DeviceMonitor( AndroidDebugBridge bridge ) {
			Server = bridge;
			Devices = new List<Device> ( );
			DebuggerPorts = new List<int> ( );
			ClientsToReopen = new Dictionary<IClient, int> ( );
			DebuggerPorts.Add ( DdmPreferences.DebugPortBase );
			LengthBuffer = new byte[4];
			LengthBuffer2 = new byte[4];
		}

		/// <summary>
		/// Gets the devices.
		/// </summary>
		public IList<Device> Devices { get; private set; }
		/// <summary>
		/// Gets the debugger ports.
		/// </summary>
		public IList<int> DebuggerPorts { get; private set; }
		/// <summary>
		/// Gets the clients to reopen.
		/// </summary>
		public Dictionary<IClient, int> ClientsToReopen { get; private set; }
		/// <summary>
		/// Gets the server.
		/// </summary>
		public AndroidDebugBridge Server { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance is monitoring.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is monitoring; otherwise, <c>false</c>.
		/// </value>
		public bool IsMonitoring { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance is running.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is running; otherwise, <c>false</c>.
		/// </value>
		public bool IsRunning { get; private set; }
		/// <summary>
		/// Gets the connection attempt count.
		/// </summary>
		public int ConnectionAttemptCount { get; private set; }
		/// <summary>
		/// Gets the restart attempt count.
		/// </summary>
		public int RestartAttemptCount { get; private set; }
		/// <summary>
		/// Gets a value indicating whether this instance has initial device list.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance has initial device list; otherwise, <c>false</c>.
		/// </value>
		public bool HasInitialDeviceList { get; private set; }
		/// <summary>
		/// Gets or sets the main adb connection.
		/// </summary>
		/// <value>
		/// The main adb connection.
		/// </value>
		private Socket MainAdbConnection { get; set; }

		/// <summary>
		/// Adds the client to drop and reopen.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="port">The port.</param>
		public void AddClientToDropAndReopen( IClient client, int port ) {
			lock ( ClientsToReopen ) {
				Log.d ( TAG, "Adding {0} to list of client to reopen ({1})", client, port );
				if ( !ClientsToReopen.ContainsKey ( client ) ) {
					ClientsToReopen.Add ( client, port );
				}
			}
		}

		/// <summary>
		/// Starts the monitoring
		/// </summary>
		public void Start( ) {
			Thread t = new Thread ( new ThreadStart ( DeviceMonitorLoop ) );
			t.Name = "Device List Monitor";
			t.Start ( );
		}

		/// <summary>
		/// Stops the monitoring
		/// </summary>
		public void Stop( ) {
			IsRunning = false;

			// wakeup the main loop thread by closing the main connection to adb.
			try {
				if ( MainAdbConnection != null ) {
					MainAdbConnection.Close ( );
				}
			} catch ( IOException ) {
			}

			// wake up the secondary loop by closing the selector.
			/*if ( Selector != null ) {
				Selector.WakeUp ( );
			}*/
		}

		/// <summary>
		/// Monitors the devices. This connects to the Debug Bridge
		/// </summary>
		private void DeviceMonitorLoop( ) {
			IsRunning = true;
			do {
				try {
					if ( MainAdbConnection == null ) {
						Log.d ( TAG, "Opening adb connection" );
						MainAdbConnection = OpenAdbConnection ( );

						if ( MainAdbConnection == null ) {
							ConnectionAttemptCount++;
							Log.e ( TAG, "Connection attempts: {0}", ConnectionAttemptCount );

							if ( ConnectionAttemptCount > 10 ) {
								if ( Server.Start ( ) == false ) {
									RestartAttemptCount++;
									Log.e ( TAG, "adb restart attempts: {0}", RestartAttemptCount );
								} else {
									RestartAttemptCount = 0;
								}
							}
							WaitBeforeContinue ( );
						} else {
							Log.d ( TAG, "Connected to adb for device monitoring" );
							ConnectionAttemptCount = 0;
						}
					}
					if ( MainAdbConnection != null && !IsMonitoring && MainAdbConnection.Connected ) {
						IsMonitoring = SendDeviceListMonitoringRequest ( );
					}

					if ( IsMonitoring ) {
						// read the length of the incoming message
						int length = ReadLength ( MainAdbConnection, LengthBuffer );

						if ( length >= 0 ) {
							// read the incoming message
							ProcessIncomingDeviceData ( length );

							// flag the fact that we have build the list at least once.
							HasInitialDeviceList = true;
						}
					}
				} catch ( IOException ioe ) {
					if ( !IsRunning ) {
						Log.e ( TAG, "Adb connection Error: ", ioe );
						IsMonitoring = false;
						if ( MainAdbConnection != null ) {
							try {
								MainAdbConnection.Close ( );
							} catch ( IOException ) {
								// we can safely ignore that one.
							}
							MainAdbConnection = null;
						}
					}
				} catch ( Exception ex ) {
					Log.e ( TAG, ex );
				}
			} while ( IsRunning );
		}

		/// <summary>
		/// Waits before continuing.
		/// </summary>
		private void WaitBeforeContinue( ) {
			Thread.Sleep ( 1000 );
		}

		/// <summary>
		/// Sends the device list monitoring request.
		/// </summary>
		/// <returns></returns>
		private bool SendDeviceListMonitoringRequest( ) {
			byte[] request = AdbHelper.Instance.FormAdbRequest ( "host:track-devices" );

			if ( AdbHelper.Instance.Write ( MainAdbConnection, request ) == false ) {
				Log.e ( TAG, "Sending Tracking request failed!" );
				MainAdbConnection.Close ( );
				throw new IOException ( "Sending Tracking request failed!" );
			}

			AdbResponse resp = AdbHelper.Instance.ReadAdbResponse ( MainAdbConnection, false /* readDiagString */);

			if ( !resp.IOSuccess ) {
				Log.e ( TAG, "Failed to read the adb response!" );
				MainAdbConnection.Close ( );
				throw new IOException ( "Failed to read the adb response!" );
			}

			if ( !resp.Okay ) {
				// request was refused by adb!
				Log.e ( TAG, "adb refused request: {0}", resp.Message );
			}

			return resp.Okay;
		}

		/// <summary>
		/// Processes the incoming device data.
		/// </summary>
		/// <param name="length">The length.</param>
		private void ProcessIncomingDeviceData( int length ) {
			List<Device> list = new List<Device> ( );

			if ( length > 0 ) {
				byte[] buffer = new byte[length];
				String result = Read ( MainAdbConnection, buffer );

				String[] devices = result.Split ( new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries );
				devices.ForEach ( d => {
					try {
						var dv = Device.CreateFromAdbData ( d );
						if ( dv != null ) {
							list.Add ( dv );
						}
					} catch ( ArgumentException ae ) {
						Log.e ( TAG, ae );
					}
				} );
			}

			// now merge the new devices with the old ones.
			UpdateDevices ( list );
		}

		private void UpdateDevices( List<Device> list ) {
			// because we are going to call mServer.deviceDisconnected which will acquire this lock
			// we lock it first, so that the AndroidDebugBridge lock is always locked first.
			lock ( AndroidDebugBridge.GetLock ( ) ) {
				lock ( Devices ) {
					// For each device in the current list, we look for a matching the new list.
					// * if we find it, we update the current object with whatever new information
					//   there is
					//   (mostly state change, if the device becomes ready, we query for build info).
					//   We also remove the device from the new list to mark it as "processed"
					// * if we do not find it, we remove it from the current list.
					// Once this is done, the new list contains device we aren't monitoring yet, so we
					// add them to the list, and start monitoring them.

					for ( int d = 0; d < Devices.Count; ) {
						Device device = Devices[d];

						// look for a similar device in the new list.
						int count = list.Count;
						bool foundMatch = false;
						for ( int dd = 0; dd < count; dd++ ) {
							Device newDevice = list[dd];
							// see if it matches in id and serial number.
							if ( String.Compare ( newDevice.SerialNumber, device.SerialNumber, true ) == 0 ) {
								foundMatch = true;

								// update the state if needed.
								if ( device.State != newDevice.State ) {
									device.State = newDevice.State;
									device.OnStateChanged ( EventArgs.Empty );

									// if the device just got ready/online, we need to start
									// monitoring it.
									if ( device.IsOnline ) {
										if ( AndroidDebugBridge.ClientSupport ) {
											if ( StartMonitoringDevice ( device ) == false ) {
												Log.e ( TAG, "Failed to start monitoring {0}", device.SerialNumber );
											}
										}

										if ( device.Properties.Count == 0 ) {
											QueryNewDeviceForInfo ( device );
										}
									}
								}

								// remove the new device from the list since it's been used
								list.RemoveAt ( dd );
								break;
							}
						}

						if ( foundMatch == false ) {
							// the device is gone, we need to remove it, and keep current index
							// to process the next one.
							RemoveDevice ( device );
							device.State = DeviceState.Offline;
							device.OnStateChanged ( EventArgs.Empty );
							Server.OnDeviceDisconnected ( new DeviceEventArgs ( device ) );
						} else {
							// process the next one
							d++;
						}
					}

					// at this point we should still have some new devices in newList, so we
					// process them.
					foreach ( Device newDevice in list ) {
						// add them to the list
						Devices.Add ( newDevice );
						if ( Server != null ) {
							newDevice.State = DeviceState.Online;
							newDevice.OnStateChanged ( EventArgs.Empty );
							Server.OnDeviceConnected ( new DeviceEventArgs ( newDevice ) );
						}

						// start monitoring them.
						if ( AndroidDebugBridge.ClientSupport ) {
							if ( newDevice.IsOnline ) {
								StartMonitoringDevice ( newDevice );
							}
						}

						// look for their build info.
						if ( newDevice.IsOnline ) {
							QueryNewDeviceForInfo ( newDevice );
						}
					}
				}
			}
			list.Clear ( );
		}

		/// <summary>
		/// Removes the device.
		/// </summary>
		/// <param name="device">The device.</param>
		private void RemoveDevice( Device device ) {
			//device.Clients.Clear ( );
			Devices.Remove ( device );

			Socket channel = device.ClientMonitoringSocket;
			if ( channel != null ) {
				try {
					channel.Close ( );
				} catch ( IOException ) {
					// doesn't really matter if the close fails.
				}
			}
		}

		private void QueryNewDeviceForInfo( Device device ) {
			// TODO: do this in a separate thread.
			try {
				// first get the list of properties.
				if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
					// get environment variables
					QueryNewDeviceForEnvironmentVariables ( device );
					// instead of getting the 3 hard coded ones, we use mount command and get them all...
					// if that fails, then it automatically falls back to the hard coded ones.
					QueryNewDeviceForMountingPoint ( device );

					// now get the emulator Virtual Device name (if applicable).
					if ( device.IsEmulator ) {
						/*EmulatorConsole console = EmulatorConsole.getConsole ( device );
						if ( console != null ) {
							device.AvdName = console.AvdName;
						}*/
					}
				}
			} catch ( IOException ) {
				// if we can't get the build info, it doesn't matter too much
			}
		}

		/// <summary>
		/// Queries the new device for environment variables.
		/// </summary>
		/// <param name="device">The device.</param>
		private void QueryNewDeviceForEnvironmentVariables( Device device ) {
			try {
				if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
					device.RefreshEnvironmentVariables ( );
				}
			} catch ( IOException ) {
				// if we can't get the build info, it doesn't matter too much
			}
		}

		/// <summary>
		/// Queries the new device for mounting point.
		/// </summary>
		/// <param name="device">The device.</param>
		private void QueryNewDeviceForMountingPoint( Device device ) {
			try {
				if ( device.State != DeviceState.Offline && device.State != DeviceState.Unknown ) {
					device.RefreshMountPoints ( );
				}
			} catch ( IOException ) {
				// if we can't get the build info, it doesn't matter too much
			}
		}

		/// <summary>
		/// Starts the monitoring device.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <returns></returns>
		private bool StartMonitoringDevice( Device device ) {
			Socket socket = OpenAdbConnection ( );

			if ( socket != null ) {
				try {
					bool result = SendDeviceMonitoringRequest ( socket, device );
					if ( result ) {

						/*if ( Selector == null ) {
							StartDeviceMonitorThread ( );
						}*/

						device.ClientMonitoringSocket = socket;

						lock ( Devices ) {
							// always wakeup before doing the register. The synchronized block
							// ensure that the selector won't select() before the end of this block.
							// @see deviceClientMonitorLoop
							//Selector.wakeup ( );

							socket.Blocking = true;
							//socket.register(mSelector, SelectionKey.OP_READ, device);
						}

						return true;
					}
				} catch ( IOException e ) {
					try {
						// attempt to close the socket if needed.
						socket.Close ( );
					} catch ( IOException ) {
						// we can ignore that one. It may already have been closed.
					}
					Log.d ( TAG, "Connection Failure when starting to monitor device '{0}' : {1}", device, e.Message );
				}
			}

			return false;
		}

		/// <summary>
		/// Starts the device monitor thread.
		/// </summary>
		private void StartDeviceMonitorThread( ) {
			//Selector = Selector.Open();
			Thread t = new Thread ( new ThreadStart ( DeviceClientMonitorLoop ) );
			t.Name = "Device Client Monitor";
			t.Start ( );
		}

		/// <summary>
		/// Devices the client monitor loop.
		/// </summary>
		private void DeviceClientMonitorLoop( ) {
			do {
				try {
					// This synchronized block stops us from doing the select() if a new
					// Device is being added.
					// @see startMonitoringDevice()
					lock ( Devices ) {
					}

					//int count = Selector.Select ( );
					int count = 0;

					if ( !IsRunning ) {
						return;
					}

					lock ( ClientsToReopen ) {
						if ( ClientsToReopen.Count > 0 ) {
							Dictionary<IClient, int>.KeyCollection clients = ClientsToReopen.Keys;
							MonitorThread monitorThread = MonitorThread.Instance;

							foreach ( IClient client in clients ) {
								Device device = client.DeviceImplementation;
								int pid = client.ClientData.Pid;

								monitorThread.DropClient ( client, false /* notify */);

								// This is kinda bad, but if we don't wait a bit, the client
								// will never answer the second handshake!
								WaitBeforeContinue ( );

								int port = ClientsToReopen[client];

								if ( port == DebugPortManager.NO_STATIC_PORT ) {
									port = GetNextDebuggerPort ( );
								}
								Log.d ( "DeviceMonitor", "Reopening " + client );
								OpenClient ( device, pid, port, monitorThread );
								device.OnClientListChanged ( EventArgs.Empty );
							}

							ClientsToReopen.Clear ( );
						}
					}

					if ( count == 0 ) {
						continue;
					}

					/*List<SelectionKey> keys = Selector.selectedKeys();
					List<SelectionKey>.Enumerator iter = keys.GetEnumerator();

					while (iter.MoveNext()) {
							SelectionKey key = iter.next();
							iter.remove();

							if (key.isValid() && key.isReadable()) {
									Object attachment = key.attachment();

									if (attachment instanceof Device) {
											Device device = (Device)attachment;

											SocketChannel socket = device.getClientMonitoringSocket();

											if (socket != null) {
													try {
															int length = readLength(socket, mLengthBuffer2);

															processIncomingJdwpData(device, socket, length);
													} catch (IOException ioe) {
															Log.d("DeviceMonitor",
																			"Error reading jdwp list: " + ioe.getMessage());
															socket.close();

															// restart the monitoring of that device
															synchronized (mDevices) {
																	if (mDevices.contains(device)) {
																			Log.d("DeviceMonitor",
																							"Restarting monitoring service for " + device);
																			startMonitoringDevice(device);
																	}
															}
													}
											}
									}
							}
					}*/
				} catch ( IOException ) {
					if ( !IsRunning ) {

					}
				}

			} while ( IsRunning );
		}

		/// <summary>
		/// Sends the device monitoring request.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="device">The device.</param>
		/// <returns></returns>
		private bool SendDeviceMonitoringRequest( Socket socket, Device device ) {
			AdbHelper.Instance.SetDevice ( socket, device );
			byte[] request = AdbHelper.Instance.FormAdbRequest ( "track-jdwp" );
			if ( !AdbHelper.Instance.Write ( socket, request ) ) {
				Log.e ( TAG, "Sending jdwp tracking request failed!" );
				socket.Close ( );
				throw new IOException ( );
			}
			AdbResponse resp = AdbHelper.Instance.ReadAdbResponse ( socket, false /* readDiagString */);
			if ( resp.IOSuccess == false ) {
				Log.e ( TAG, "Failed to read the adb response!" );
				socket.Close ( );
				throw new IOException ( );
			}

			if ( resp.Okay == false ) {
				// request was refused by adb!
				Log.e ( TAG, "adb refused request: " + resp.Message );
			}

			return resp.Okay;
		}

		/// <summary>
		/// Opens the client.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="pid">The pid.</param>
		/// <param name="port">The port.</param>
		/// <param name="monitorThread">The monitor thread.</param>
		private void OpenClient( Device device, int pid, int port, MonitorThread monitorThread ) {

			Socket clientSocket;
			try {
				clientSocket = AdbHelper.Instance.CreatePassThroughConnection ( AndroidDebugBridge.SocketAddress, device, pid );

				clientSocket.Blocking = true;
			} catch ( IOException ioe ) {
				Log.w ( TAG, "Failed to connect to client {0}: {1}'", pid, ioe.Message );
				return;
			}

			CreateClient ( device, pid, clientSocket, port, monitorThread );
		}

		/// <summary>
		/// Creates the client.
		/// </summary>
		/// <param name="device">The device.</param>
		/// <param name="pid">The pid.</param>
		/// <param name="socket">The socket.</param>
		/// <param name="debuggerPort">The debugger port.</param>
		/// <param name="monitorThread">The monitor thread.</param>
		private void CreateClient( Device device, int pid, Socket socket, int debuggerPort, MonitorThread monitorThread ) {

			/*
			 * Successfully connected to something. Create a Client object, add
			 * it to the list, and initiate the JDWP handshake.
			 */

			Client client = new Client ( device, socket, pid );

			if ( client.SendHandshake ( ) ) {
				try {
					if ( AndroidDebugBridge.ClientSupport ) {
						client.ListenForDebugger ( debuggerPort );
					}
				} catch ( IOException ) {
					client.ClientData.DebuggerConnectionStatus = Managed.Adb.ClientData.DebuggerStatus.ERROR;
					Log.e ( "ddms", "Can't bind to local {0} for debugger", debuggerPort );
					// oh well
				}

				client.RequestAllocationStatus ( );
			} else {
				Log.e ( "ddms", "Handshake with {0} failed!", client );
				/*
				 * The handshake send failed. We could remove it now, but if the
				 * failure is "permanent" we'll just keep banging on it and
				 * getting the same result. Keep it in the list with its "error"
				 * state so we don't try to reopen it.
				 */
			}

			if ( client.IsValid ) {
				device.Clients.Add ( client );
				monitorThread.Clients.Add ( client );
			} else {
				client = null;
			}
		}

		/// <summary>
		/// Gets the next debugger port.
		/// </summary>
		/// <returns></returns>
		private int GetNextDebuggerPort( ) {
			// get the first port and remove it
			lock ( DebuggerPorts ) {
				if ( DebuggerPorts.Count > 0 ) {
					int port = DebuggerPorts[0];

					// remove it.
					DebuggerPorts.RemoveAt ( 0 );

					// if there's nothing left, add the next port to the list
					if ( DebuggerPorts.Count == 0 ) {
						DebuggerPorts.Add ( port + 1 );
					}

					return port;
				}
			}

			return -1;
		}

		/// <summary>
		/// Adds the port to available list.
		/// </summary>
		/// <param name="port">The port.</param>
		public void AddPortToAvailableList( int port ) {
			if ( port > 0 ) {
				lock ( DebuggerPorts ) {
					// because there could be case where clients are closed twice, we have to make
					// sure the port number is not already in the list.
					if ( DebuggerPorts.IndexOf ( port ) == -1 ) {
						// add the port to the list while keeping it sorted. It's not like there's
						// going to be tons of objects so we do it linearly.
						int count = DebuggerPorts.Count;
						for ( int i = 0; i < count; i++ ) {
							if ( port < DebuggerPorts[i] ) {
								DebuggerPorts.Insert ( i, port );
								break;
							}
						}
						// TODO: check if we can compact the end of the list.
					}
				}
			}
		}

		/// <summary>
		/// Reads the length of the next message from a socket.
		/// </summary>
		/// <param name="socket">The Socket to read from.</param>
		/// <param name="buffer"></param>
		/// <returns>the length, or 0 (zero) if no data is available from the socket.</returns>
		private int ReadLength( Socket socket, byte[] buffer ) {
			String msg = Read ( socket, buffer );
			if ( msg != null ) {
				try {
					int len = int.Parse ( msg, System.Globalization.NumberStyles.HexNumber );
					return len;
				} catch ( FormatException ) {
					// we'll throw an exception below.
				}
			}
			//throw new IOException ( "unable to read data length" );
			// we receive something we can't read. It's better to reset the connection at this point.
			return -1;
		}

		/// <summary>
		/// Reads the specified socket.
		/// </summary>
		/// <param name="socket">The socket.</param>
		/// <param name="data">The data.</param>
		/// <returns></returns>
		private string Read( Socket socket, byte[] data ) {
			int count = -1;
			int totalRead = 0;

			while ( count != 0 && totalRead < data.Length ) {
				try {
					int left = data.Length - totalRead;
					int buflen = left < socket.ReceiveBufferSize ? left : socket.ReceiveBufferSize;

					byte[] buffer = new byte[buflen];
					socket.ReceiveBufferSize = buffer.Length;
					count = socket.Receive ( buffer, buflen, SocketFlags.None );
					if ( count < 0 ) {
						throw new IOException ( "EOF" );
					} else if ( count == 0 ) {
					} else {
						Array.Copy ( buffer, 0, data, totalRead, count );
						totalRead += count;
					}
				} catch ( SocketException sex ) {
					if (!IsRunning || sex.Message.Contains ( "connection was aborted" ) ) {
						// ignore this?
						return String.Empty;
					} else {
						throw new IOException ( String.Format ( "No Data to read: {0}", sex.Message ) );
					}
				}
			}

			return data.GetString ( AdbHelper.DEFAULT_ENCODING );
		}

		/// <summary>
		/// Attempts to connect to the debug bridge server.
		/// </summary>
		/// <returns>a connect socket if success, null otherwise</returns>
		private Socket OpenAdbConnection( ) {
			Log.d ( TAG, "Connecting to adb for Device List Monitoring..." );
			Socket socket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			try {
				socket.Connect ( AndroidDebugBridge.SocketAddress );
				socket.NoDelay = true;
			} catch ( IOException e ) {
				Log.w ( TAG, e );
			}

			return socket;
		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/ShellCommandUnresponsiveException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// 
	/// </summary>
	/// <seealso cref="Managed.Adb.Exceptions.AdbException" />
	public class ShellCommandUnresponsiveException : AdbException {
		/// <summary>
		/// Initializes a new instance of the <see cref="ShellCommandUnresponsiveException"/> class.
		/// </summary>
		public ShellCommandUnresponsiveException ( ) : base("The shell command has become unresponsive"){

		}
	}
}


<|start_filename|>Managed.AndroidDebugBridge/Exceptions/BadPacketException.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb.Exceptions {
	/// <summary>
	/// 
	/// </summary>
	public class BadPacketException : Exception {
		/// <summary>
		/// Initializes a new instance of the <see cref="BadPacketException"/> class.
		/// </summary>
		public BadPacketException ( )
			: base ( ) {


		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BadPacketException"/> class.
		/// </summary>
		/// <param name="msg">The MSG.</param>
		public BadPacketException ( String msg )
			: base ( msg ) {

		}
	}
}


<|start_filename|>Managed.Adb.Tests/ForIO/ForLinuxPath/LinuxPathConsts.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Managed.Adb.Tests.ForIOLinuxPath {
	internal class LinuxPathConsts {
		internal static readonly char[] InvalidPathChars = new char[] {
			'"', '<', '>', '|', '\0', '\x0001', '\x0002', '\x0003', '\x0004', '\x0005', '\x0006', '\a', '\b', '\t', '\n', '\v',
				'\f', '\r', '\x000e', '\x000f', '\x0010', '\x0011', '\x0012', '\x0013', '\x0014', '\x0015', '\x0016', '\x0017', '\x0018', '\x0019', '\x001a', '\x001b',
				'\x001c', '\x001d', '\x001e', '\x001f'
		};

		internal static readonly char[] InvalidFileNameChars = new char[] {
			'"', '<', '>', '|', '\0', '\x0001', '\x0002', '\x0003', '\x0004', '\x0005', '\x0006', '\a', '\b', '\t', '\n', '\v',
			'\f', '\r', '\x000e', '\x000f', '\x0010', '\x0011', '\x0012', '\x0013', '\x0014', '\x0015', '\x0016', '\x0017', '\x0018', '\x0019', '\x001a', '\x001b',
			'\x001c', '\x001d', '\x001e', '\x001f', '*', '?', '\\', '/'
		};

	}
}


<|start_filename|>Madb.Site/Views/Documentation/DisplayTemplates/NamespaceModel.cshtml<|end_filename|>
﻿@using Madb.Site.Extensions;

@model Madb.Site.Models.Documentation.NamespaceModel

<div id="@(Model.Id)">
	<div class="page-header">
		<h2 class="zero"><i class="fa fa-code mrm"></i>@Model.Name<small class="mll text-muted pull-right">@Html.DirectLink(Model.Id)</small></h2>
	</div>
	<div class="mhl">
		@foreach(var c in Model.Classes) {
			if(!c.Ignore) {
				@Html.DisplayFor(d => c)
			}
		}
	</div>
</div>

<|start_filename|>Managed.AndroidDebugBridge/MountPoint.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Managed.Adb {
	/// <summary>
	/// Represents a mount point.
	/// </summary>
	public class MountPoint : ICloneable {
		/// <summary>
		/// Initializes a new instance of the <see cref="MountPoint"/> class.
		/// </summary>
		/// <param name="block">The block.</param>
		/// <param name="name">The name.</param>
		/// <param name="fs">The fs.</param>
		/// <param name="readOnly">if set to <c>true</c> [read only].</param>
		public MountPoint ( string block, string name, string fs, bool readOnly ) {
			this.Block = block;
			this.Name = name;
			this.FileSystem = fs;
			this.IsReadOnly = readOnly;
		}

		/// <summary>
		/// Gets the mount point block
		/// </summary>
		/// <value>The block.</value>
		public String Block { get; private set; }

		/// <summary>
		/// Gets the mount point name
		/// </summary>
		/// <value>The name.</value>
		public String Name { get; private set; }

		/// <summary>
		/// Gets the mount point file system
		/// </summary>
		/// <value>The file system.</value>
		public String FileSystem { get; private set; }

		/// <summary>
		/// Gets the mount point access
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is read only; otherwise, <c>false</c>.
		/// </value>
		public bool IsReadOnly { get; private set; }

		/// <summary>
		/// Returns a string representation of the mount point.
		/// </summary>
		/// <returns>
		/// A <see cref="System.String"/> that represents this instance.
		/// </returns>
		public override string ToString ( ) {
			return string.Format ( "{0}\t{1}\t{2}\t{3}", Block, Name, FileSystem, IsReadOnly ? "ro" : "rw" );
		}

		/// <summary>
		/// Creates a clone of this MountPoint
		/// </summary>
		/// <returns></returns>
		public MountPoint Clone ( ) {
			return this.MemberwiseClone ( ) as MountPoint;
		}

		/// <summary>
		/// Creates a new object that is a copy of the current instance.
		/// </summary>
		/// <returns>
		/// A new object that is a copy of this instance.
		/// </returns>
		object ICloneable.Clone ( ) {
			return this.MemberwiseClone ( );
		}
	}
}


<|start_filename|>Madb.Site/Models/Documentation/Xml/Member.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Madb.Site.Models.Documentation.Xml {
	[XmlRoot("member")]
	public class Member {
		[XmlAttribute("name")]
		public string Name { get; set; }
		[XmlElement("summary")]
		public List<Simple> Summary { get; set; }
		[XmlElement("typeparam")]
		public List<Param> TypeParams { get; set; }
		[XmlElement("param")]
		public List<Param> Params { get; set; }
		[XmlElement("returns")]
		public List<Simple> Returns { get; set; }
		[XmlElement("gist")]
		public List<Gist> Gists { get; set; }
		[XmlElement("remarks")]
		public List<Simple> Remarks { get; set; }
		[XmlElement("example")]
		public List<Simple> Examples { get; set; }
		[XmlElement("exception")]
		public List<Reference> Exceptions { get; set; }
		[XmlElement("permission")]
		public List<Reference> Permissions { get; set; }
		[XmlElement("see")]
		public List<Reference> Sees { get; set; }
		[XmlElement("seealso")]
		public List<Reference> SeeAlsos { get; set; }
		[XmlElement("value")]
		public List<Simple> Values { get; set; }
		[XmlElement("ignore")]
		[DefaultValue(false)]
		public bool Ignore { get; set; }
	}
}

<|start_filename|>Managed.AndroidDebugBridge/MonitorThread.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Managed.Adb {
	/// <summary>
	/// 
	/// </summary>
	class MonitorThread {

		/// <summary>
		/// 
		/// </summary>
		public enum ThreadState {
			/// <summary>
			/// 
			/// </summary>
			UNKNOWN = -1,
			/// <summary>
			/// 
			/// </summary>
			Ready = 2,
			/// <summary>
			/// 
			/// </summary>
			Disconnected = 3,
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MonitorThread"/> class.
		/// </summary>
		private MonitorThread ( ) {
			Clients = new List<IClient> ( );
		}

		/// <summary>
		/// 
		/// </summary>
		private static MonitorThread _instance;
		/// <summary>
		/// Gets the instance.
		/// </summary>
		/// <value>The instance.</value>
		public static MonitorThread Instance {
			get {
				if ( _instance == null ) {
					_instance = new MonitorThread ( );
				}
				return _instance;
			}
		}

		/// <summary>
		/// Gets or sets a value indicating whether this <see cref="MonitorThread"/> is quit.
		/// </summary>
		/// <value><c>true</c> if quit; otherwise, <c>false</c>.</value>
		public bool Quit { get; private set; }
		/// <summary>
		/// Gets or sets the clients.
		/// </summary>
		/// <value>The clients.</value>
		public List<IClient> Clients { get; private set; }

		/// <summary>
		/// Sets the debug selected port.
		/// </summary>
		/// <param name="value">The value.</param>
		internal void SetDebugSelectedPort ( int value ) {
			//throw new NotImplementedException ( );
		}

		/// <summary>
		/// Drops the client.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="notify">if set to <c>true</c> [notify].</param>
		public void DropClient ( IClient client, bool notify ) {

		}
	}
}
