yashsingh1/xdaforums huggingface dataset:
[Android Software Development] DVS_Sokar:
Any further thoughts Dan?
[Android Software Development] regaw_leinad:
Yes. Try out

ExecuteAdbShellCommandInputString

I'd recommend

string writeCmd = "echo -ne '\x00\x00\x00\x00' | dd of=/dev/block/mmcblk0p3 bs=1 seek=33796";
Adb.ExecuteAdbShellCommandInputString(device, "su", writeCmd, "exit", "exit");

I left it public in the API even though I just put it in there for a specific application I wrote (HTC Hero Rooter). It basically runs each of the params (commands) in order, but you have to exit out of the shell manually.
[Android Software Development] DVS_Sokar:
I tried what you suggested however it seems that that command when executed buy the button locks my program up and I get no response from my app any longer.
[Android Software Development] regaw_leinad:
Well, you should be running it on a background thread, that will stop the freezing, but are you sure you exited out of all the shells?
[Android Software Development] DVS_Sokar:
from what I know there should only be 2 exits

One from Root and one from shell itself.

---------- Post added at 08:59 PM ---------- Previous post was at 08:58 PM ----------

Though I think you on to something here because the Flag was changed on my phone in this last attempt.
[Android Software Development] regaw_leinad:
Yeah, exactly.. hmmm. Does the write usually take a bit of time with the dd? I wonder if the input is being written before the root shell is ready.

Look here and here for how that is executed. You may need to modify the RunProcessWriteInput method to wait before writing the next line to stdin
[Android Software Development] DVS_Sokar:
4 bytes transferred in 0.007 secs (571 bytes/sec) for the write in a normal command prompt.

---------- Post added at 09:22 PM ---------- Previous post was at 09:06 PM ----------

In this Process call the UseShellExecute = false; prevents it from running in shell. but in the later call under the ExecuteAdbShellCommandInputString it's passing a argument of "shell".

internal static void RunProcessWriteInput(string executable, string arguments, params string[] input)
{
using (Process p = new Process())
{
p.StartInfo.FileName = executable;
p.StartInfo.Arguments = arguments;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardInput = true;

p.Start();

using (StreamWriter w = p.StandardInput)
for (int i = 0; i < input.Length; i++)
w.WriteLine(input[i]);

p.WaitForExit();
}
}

public static void ExecuteAdbShellCommandInputString(Device device, params string[] inputLines)
{
lock (_lock)
{
Command.RunProcessWriteInput(AndroidController.Instance.ResourceDirectory + ADB_EXE, "shell", inputLines);
}
}
[Android Software Development] regaw_leinad:
Ah, yeah, those "shells" are different. The shell in my code is talking about the shell for executing in Windows, not on your device.
[Android Software Development] DVS_Sokar:
Ah yes I see that now looking over the code. I am getting tired lol. Been at it all day on just this part of the code. My last hurdle in my program.
[Android Software Development] regaw_leinad:
Technically, since the class/method isn't final, you could override Adb.ExecuteAdbShellCommandInputString() (or just make a new method) to use a custom version of the method in Command that calls adb.

You can get the AndroidLib resource folder using ResourceFolderManager.GetRegisteredFolderPath("AndroidLib"); (which gives you the path) and then use that path + "adb.exe" for the actual binary. and pass that to the Command method as the executable
[Android Software Development] DVS_Sokar:
Well I think I found my problem...

I wrote a rich text box to give me the output of the command using Process on the Lock button this is what the prompt shows when submitting the command via Std out.

The Code to lock is being interpreted incorrectly when written as Stdout;

Here is the output when run through StdOut;

C:\Users\Phoenix\Documents\Visual Studio 2013\Projects\HTC Max Bootloader Switcher\HTC Max Bootloader Switcher\bin\Debug>adb shell
shell@t6wl:/ $ su
root@t6wl:/ # echo -ne '' | dd of=/dev/block/mmcblk0p3 bs=1 seek=33796
0+0 records in
0+0 records out
0 bytes transferred in 0.001 secs (0 bytes/sec)
root@t6wl:/ # exit
shell@t6wl:/ $ exit

This Unlock Code works perfectly because it's plain text to Stdout. (Confirmed)

private void unlockboot_Click(object sender, EventArgs e)
{
button1.Enabled = false; // to prevent user from spamming the unlock button
button2.Enabled = false;
string serial;
android = AndroidController.Instance;
serial = android.ConnectedDevices[0];
device = android.GetConnectedDevice(serial);
AdbCommand adbCmd = Adb.FormAdbShellCommand(device, true,"echo -ne 'HTCU' | dd of=/dev/block/mmcblk0p3 bs=1 seek=33796");
Adb.ExecuteAdbCommand(adbCmd, true);
lblunlock.Visible = true;
lbllocked.Visible = false;
textboxcolor.BackColor = Color.Red;
android.Dispose();
button1.Enabled = true;
button2.Enabled = true;
}
[Android Software Development] DVS_Sokar:
It appears to be a encoding issue when the command is issued to Stdin
[Android Software Development] regaw_leinad:
Did you encode the string differently and retry sending the command?
[Android Software Development] DVS_Sokar:
- character literal escaping:	e.g. '\'', '\n', '\u20AC' (the Euro € currency sign), '\x9' (equivalent to \t))

- literal string escaping:	e.g. "...\t...\u0040...\U000000041...\x9..."

- verbatim string escaping:	e.g. @"...""..."

- string.Format escaping:	e.g. "...{{...}}..."

- keyword escaping:	e.g. [MENTION=219966]if[/MENTION] (for if as identifier)

- identifier escaping:	e.g. i\u0064 (for id)

I am able to do it using my own process and the @ for Verbatim String Escaping. Just need to use AndroidLib for it now.
[Android Software Development] DVS_Sokar:
I backtracked to using the executeShellCommandInputString method because this actually does issue the command. But as stated before it locked the application up.

You mentioned that I should run it as a background thread. Since I am pretty new at this I don't what you mean in the context of this command. Could you give me an example?
[Android Software Development] regaw_leinad:
That looks great! Do you think you could make a pull request on Github? I'll look over the changes and merge it in.
[Android Software Development] IceDragon59:
I submitted a pull request. I made a couple changes to reflect the original intention of the code, such as fixing my complete disregard for your forceRegular boolean. You can view it on your Github.
[Android Software Development] .torrented:
Fixed. Thank you Dan!
[Android Software Development] regaw_leinad:
Noted, and replied to your pms. You can submit a pull request with the changes I talked about in the pm if you'd like, or just let me know and I'll add them in myself when I can.

EDIT: I pushed a possible fix for this.
[Android Software Development] regaw_leinad:
Merged a pull request from @IceDragon59. Thanks for that! I ran a few tests and it worked out alright for me. I also refactored the changes a bit as well.

https://github.com/regaw-leinad/AndroidLib
[Android Software Development] .torrented:
It does not like the change in BuildProp.cs with the RegawMOD.Util; Thinks its missing.

I don't use VS enough to know how to fix this one.
[Android Software Development] regaw_leinad:
Fixed that, I forgot that I changed the namespace of Logger this morning... whoops.

Also, I'm merging in a pull request from OmarBizreh, so be sure to update and test it out as well. Some loading improvements.
[Android Software Development] .torrented:
I notice if I try to grab a logcat dump this happens. I notice it only occurs when I set the logcat filter to Verbose.

private static string HandleOutput(Process p, AutoResetEvent outputWaitHandle, AutoResetEvent errorWaitHandle, int timeout, bool forceRegular)
{
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();

p.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
[B][U][COLOR="Red"] outputWaitHandle.Set();[/COLOR][/U][/B] <- Throws "ObjectDisposedException was unhandled"
else
output.AppendLine(e.Data);
};
p.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
errorWaitHandle.Set();
else
error.AppendLine(e.Data);
};

p.Start();

p.BeginOutputReadLine();
p.BeginErrorReadLine();

if (p.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout))
{
string strReturn = "";

if (error.ToString().Trim().Length.Equals(0) || forceRegular)
strReturn = output.ToString().Trim();
else
strReturn = error.ToString().Trim();

return strReturn;
}
else
{
// Timed out.
return "PROCESS TIMEOUT";
}
}

System.ObjectDisposedException was unhandled
HResult=-2146232798
Message=Safe handle has been closed
Source=mscorlib
ObjectName=""
StackTrace:
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
at System.Threading.EventWaitHandle.Set()
at RegawMOD.Command.<>c__DisplayClass2.<HandleOutput>b__1(Object sender, DataReceivedEventArgs e)
at System.Diagnostics.AsyncStreamReader.FlushMessageQueue()
at System.Diagnostics.AsyncStreamReader.ReadBuffer(IAsyncResult ar)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.IO.Stream.ReadWriteTask.System.Threading.Tasks.ITaskCompletionAction.Invoke(Task completingTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task.Finish(Boolean bUserDelegateExecuted)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.ThreadPoolWorkQueue.Dispatch()
InnerException:
[Android Software Development] IceDragon59:
I'm noticing that now when attempting certain custom Fastboot commands, like "flash recovery recovery.img". It may be an inadvertent side-effect of my suggested changes.

I tested multiple simple ADB commands before submitting my changes to this thread, but didn't try any logcat or custom fastboot commands, because my problem lay in incorrect ADB commands and certain custom ones. Simple Fastboot commands like "fastboot reboot" work fine. I think this definitely needs further examination. It worked fine for just about everything before, maybe we need to leave it similar to how it was, but somehow implement a timeout so it will catch incorrect ADB commands.
[Android Software Development] regaw_leinad:
Hrm, I tested some fastboot commands as well before I pushed the changes, and I didn't notice any side effects. Looks like I'll have to investigate more in the morning. Sorry about that. I can implement a timeout pretty easily. Not sure why I didn't before :P
[Android Software Development] IceDragon59:
It definitely has something to do with the timeout I implemented. When trying to push or pull large files, including -v logcats, it either informs me that the process has ended, but has been disposed so I can't get the output/error data, or that the process is still ongoing and needs to end before it can write the output/error. Pushing small files and doing simple commands that are completed in less than 1000 milliseconds work fine, but not the longer processes.

Perhaps we can find another way to provide error correction for invalid commands, since it can't be known how long a process will take, depending on the size of the file and speed of the transfer. Since almost everything worked great before my proposed changes, reverting my changes might be the best course of action, and find a better way to handle invalid commands.
[Android Software Development] DVS_Sokar:
Dan if I want to pull the build.prop value from a specific key how do I pull it?

I am trying:

lblModelProp.Text = device.BuildProp.GetProp("so.product.model");

But it doesn't seem to pull the value for it.

Thanks,
[Android Software Development] regaw_leinad:
I'm still not sure the BuildProp update method parses every device's prop correctly. Are you using a Samsung device? Can you do an

adb shell getprop > "%USERPROFILE%\Desktop\prop.txt"

then compare that output to how the algorithm is parsing that data. You can also attach that file to a post here and I can look it over as well.
[Android Software Development] regaw_leinad:
What if you specify a longer timeout for those commands? I added a timeout parameter to the method signature.
[Android Software Development] IceDragon59:
It works if you edit the RunProcessReturnOutput methods in the library and increase the timeout, but you can't call the timeout when you're calling the execute ADB/Fastboot command. I could handle calling a timeout with my execute commands based on what the command is.

Maybe adding a timeout to the ExecuteAdbCommand and ExecuteFastbootCommand method calls would be easier than undoing my changes, since you already added the timeout parameter to the RunProcessReturnOutput methods.

public static string ExecuteAdbCommand(AdbCommand command, bool forceRegular = false, int timeout = 1000)
{
string result = "";

lock (_lock)
{
result = Command.RunProcessReturnOutput(AndroidController.Instance.ResourceDirectory + ADB_EXE, command.Command, forceRegular, timeout);
}

return result;
}

public static string ExecuteFastbootCommand(FastbootCommand command, int timeout = 1000)
{
return Command.RunProcessReturnOutput(AndroidController.Instance.ResourceDirectory + FASTBOOT_EXE, command.Command, timeout);
}

Something like this?
[Android Software Development] regaw_leinad:
I'll probably add it to the FormAdbCommand method set. I completely forgot that the Command class was internal :P whoops!
[Android Software Development] regaw_leinad:
Okay, now you can specify the timeout for your AdbCommand like this:

AdbCommand adbCmd = Adb.FormAdbCommand("devices").WithTimeout(5000);

The .WithTimeout(int) was added to allow specification of a timeout longer than the default of 1000 milliseconds.
[Android Software Development] IceDragon59:
That's great! However, Fastboot commands time out as well, so you should add a timeout handler to it, as well.
[Android Software Development] regaw_leinad:
Gah, will do in a few. Thanks for the reminder.
[Android Software Development] DVS_Sokar:
I am working on a Verizon HTC One Max

The Sample Project you have for pulling Props works. and I was able to export the commands and I can confirm that that is a property in the Build.Prop.

Am I not calling it correctly?
[Android Software Development] regaw_leinad:
Does it work with the newest build of AndroidLib?

Can you attach the output of that command to a post here?
[Android Software Development] IceDragon59:
I updated the Fastboot.cs with the same changes you made in ADB.cs and it seems to be working quite well. I went ahead and sent a pull request so you can check that out.
[Android Software Development] regaw_leinad:
I made a comment on the request, just change the documentation "AdbCommand" to "FastbootCommand"
[Android Software Development] IceDragon59:
Done.
[Android Software Development] regaw_leinad:
Merged, thanks for the additions. It's really cool to see this project building still after 2 years of being alive :)
[Android Software Development] IceDragon59:
I agree. I'm even more surprised that it's been around for 2 years and no one ever tried to enter an invalid command and saw that it filled the error buffer so that it infinitely looped. My program that I'm working on allows typing custom ADB commands, and when I release it, someone's bound to accidentally type something wrong in there eventually, assuming anyone uses it, of course.
[Android Software Development] DVS_Sokar:
I am pulling the new Code and compiling it today to try. The timeout might do the trick.
[Android Software Development] DVS_Sokar:
Pulled and compile the latest build of AndroidLib.

My prop pulls are working now and I am going to retry my original Echo command with the current build to see if the lockup issue has gone away with the time implementation.
[Android Software Development] IceDragon59:
Our work is never done! I have a feeling I'm going to put this entire library through the paces before I'm done with my program.

So, since we implemented timeouts, pushing and pulling files with the "Device.PushFile/PullFile/PullDirectory" methods are using the default 1000 millisecond timeout, which definitely will not work with files bigger than a few megabytes. When I tested the changes the other night, I tested push while manually typing the commands, and files small enough to transfer in less than 1 second with the "device.Push" method, but nothing as large as I tried when I discovered the error. It seems we need to make several changes for multiple methods to implement an optional timeout for all commands.

Command.RunProcessNoReturn, Command.RunProcessOutputCotains, and probably even Command.RunProcessWriteInput need to implement the timeout similarly to the others we already changed.

Device.PushFile, Device.PullFile, Device.PullDirectory, and Device.InstallApk (from the looks of it, haven't quite tested that one) all need to implement timeout in one form or another. The RunProcess methods shouldn't be that hard, but I'm not sure how you want to handle the Device methods. I like the "WithTimeOut" optional parameter as it works in ADBCommand and FastbootCommand, but I'm not entirely sure how to implement that without every method in Device being able to be called with a Timeout, including the reboot methods. While it probably wouldn't hurt anything, it just seems kind of odd to me. An overloaded constructor would work, but I'm not sure that fits with the style of the class, as there are no other overloads in that particular class.

I'm over-thinking things. Maybe it's time to go to bed. Too much thinking after I get off work and before I go to bed makes me go on tangents about programming. I'm sure this is just the tip of the iceberg. I've only been working on this in my spare time for a couple weeks, and it's already consuming my brain, and seems to be gaining pace the further I get.
[Android Software Development] regaw_leinad:
Yep. That's on the TODO list. Also, on the TODO list (if you want to take it upon yourselves ;) ) is implementing an event system for DeviceConnected, DeviceDisconnected, etc...

I'm a full-time student and a software developer for Hypixel (the largest Minecraft multiplayer server), so I don't always have time for all of these things on my todo list :p
[Android Software Development] IceDragon59:
Sounds like you've got your hands full. I'll see what I can do with what I mentioned, but I'm not entirely sure how to go about implementing the DeviceConnected/Disconnected. Maybe storing your list of devices, and having a background update method loop every 5 seconds or so, with a boolean check telling it when to stop looping, and compare the new list to the old one. If a device is missing or added, update the primary list.

If I get the other methods functioning properly, I'll update my GitHub and send a pull request. Probably won't have time to get any of it before I go to work in a little bit, but afterwards I'll give it a shot.
[Android Software Development] DVS_Sokar:
Do you guys know if there is Build.Prop On HTC phones that identifies the state of the Security Bootloader Mode while booted to Normal mode?

I.E. I want my C# WinForm app to check to see if the HTC phone is S-OFF or S-ON for Functionality.

ro.secure build.prop appears to be for SU only
[Android Software Development] IceDragon59:
The only way I know to find out if a phone is S-OFF programmatically is to be in Fastboot mode and run the command "fastboot getvar all" and read through all the lines until you get to the line that contains "security" and return the value after the colon.

I'm using a variation of that in my program where I check model number in ADB and Fastboot mode to determine what device is selected (as my program supports multiple devices selectable through a list box displaying their serial numbers and current state), and use the model number to set many variables in an instance of another class, such as what picture to display when I select the device, what resolution to use when I convert splash images, etc. I'm trying to make this a somewhat universal tool for devices that support everything the HTC One does, like flashing splash images, recoveries, and zips from Fastboot. I only have a few devices to test with, and not all support that. I know the HTC One Max is pretty much identical to the HTC One, so it probably supports all that, as well.

The core functionality of my program, like ADB commands, should be universal across most devices, but Fastboot commands like we use definitely aren't supported on Samsung phones, for example, which is why I need to check certain things and pass it to another class.
[Android Software Development] DVS_Sokar:
My application is pulling everything but the S-OFF status.

I am pulling the the Model Number and Product ID from the Build.Prop of the device with AndroidLib device.BuildProp.GetProp("Key you want");

But that is 1 of 2 things I can't get right now.

Can you tell me what ADB command I would use to read a value of the /dev/block/mmcblk0p3
[Android Software Development] IceDragon59:
I'm not entirely sure what the block is, but you can pull an entire block and create a file with it using the command

adb shell dd if=/dev/block/mmcblk0p03 of=/mnt/sdcard/filename.extension

I use the same type command when I pull from the splash block from my phone to backup my splash image, another feature of my program.

I can't seem to find the link to the entire HTC One partition list, including the blocks not listed in "cat /proc/emmc/". I remember seeing it once. The One Max shouldn't be much different.

Anyway, the point is that you should be able to convert it to a readable file with whatever extension it requires and pull the information needed from that file using the command I gave you.
[Android Software Development] DVS_Sokar:
So I am just using AndroidLib.dll at the moment for Pulling prop information.

When running my app to set specific Build.Prop values to Label Strings I get a unhandled error

AndroidLib.dll!RegawMOD.Command.HandleOutput.AnonymousMethod__1(object sender, System.Diagnostic.DataReceivedEventArgs e) Line 86 Command.cs

It's completely random. Sometimes it errors and other times it work fine.

This started occurring after the timeout was implemented.
[Android Software Development] regaw_leinad:
Can you give me the stack trace? and the specific exception that was raised?
[Android Software Development] DVS_Sokar:
I am working on replicating the error again. It's completely random. I will capture the information once I replicate.
[Android Software Development] regaw_leinad:
Sounds good to me! Thanks
[Android Software Development] DVS_Sokar:
FYI I stumbled upon this when looking for Timeout resolutions... Asynchronous Reads works better to avoid Buffer issues in StandardOutput.

http://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why

perhaps this is the answer to the timeout issue.
[Android Software Development] regaw_leinad:
Notice any similarities? ;)

https://github.com/regaw-leinad/AndroidLib/blob/master/AndroidLib/Classes/Util/Command.cs#L71-L112
[Android Software Development] DVS_Sokar:
Oh right haven't looked at the actual code in the new version lol... well at least we know it works in some cases. lol
[Android Software Development] DVS_Sokar:
Here is the stack

+	$exception	{"Safe handle has been closed"}	System.Exception {System.ObjectDisposedException}

+	sender	{System.Diagnostics.Process}	object {System.Diagnostics.Process}

+	e	{System.Diagnostics.DataReceivedEventArgs}	System.Diagnostics.DataReceivedEventArgs

+	output	{[DEVICE_PROVISIONED]: [1]

Then is dumps all the Build.prop info
[Android Software Development] regaw_leinad:
Is that all of the info it gives?