[DEV] AndroidCtrl.dll [7.1.46.0] (ADB/Fastboot/(apk/zip) Signer - Framework) - Android Software/Hacking General [Developers Only]

This (C# .NET 4.6|4.7|4.8) dll is a kind of ADB/Fastboot/(apk/zip) Signer - Framework, it provides a lot of predefined .NET functions to communicate with an Android device. It's designed to work in 1st case with any non-root device but you can also use it with any rooted device (A few functions requires root access).
License
This project is licensed under the Apache License Version 2.0.
The latest build 7.1.46.0 is currently only via FTP, GoogleDrive or Dropbox available, the DevDB has currently some upload issues!
The following (N)amespaces, (C)lasses & (I)nterfaces are currently available:
(N) ADB
(N) Binary (This is the binary/exe implementation of ADB)
(C) ADB (static Management Class for the ADBClient's)
(C) ADBClient (Implementation of IADBClient)
(C) Channel (Implementation of IChannel)
(N) Device
(N) BusyBox
(C) BusyBox
(C) Find
(C) Tar
(N) Dumpsys
(C) Battery
(C) Dumpsys
(I) IBattery
(N) Input
(I) IKeyEvent
(C) Input
(C) InputExtensions
(C) KeyEvent (Implementation of IKeyEvent)
(N) IO
(NS) Compression
(NS) BrotliSharp (Only available in .NET 4.6|4.7|4.8 - In .NET Standard >= 2.1 you have to use the native .NET implementation)
(C) ADirectoryInfo (Similar to .NET Directory/-Info)
(C) AFileInfo (Similar to .NET File/-Info)
(C) AFileStream (Similar to .NET FileStream)
(C) AFileSystemInfo (Similar to .NET FileSystemInfo, it's the abstract base for ADirectoryInfo & AFileInfo)
(C) AMountPointInfo (Similar to ADirectoryInfo & AFileInfo but only for mounts)
(C) FileSystemCache (A cache object for ADirectoryInfo & AFileInfo)
(I) IFileSystemCache (Interface for FileSystemCache)
(C) IO
(I) ITransferMessage
(C) MediaScanner (Manage the Android MediaScanner, useful after some file-transfers via ADB)
(C) Mount (Requires Root and manage the mounts)
(C) Stat (stat class for the ADB-Protocol)
(C) SyncStream (Base implementation of the ADB sync service. Utilized by AFileStream)
(C) TransferMessage
(C) UPath (Similar to .Net Path but for unix paths)
(N) Logcat
(I) ILogEntry
(C) Logcat
(C) LogEntry
(N) Manager
(C) ActivityManager
(I) IInstrumentation
(C) Instrumentation
(I) IPackage
(I) IPermission
(C) Manager
(C) Package
(C) PackageManager
(C) Permission
(N) Provider
(C) Contacts (Contacts provider)
(C) ContactsDataField
(C) ContactsEmail
(C) ContactsEvent
(C) ContactsGroup
(C) ContactsIdentity
(C) ContactsIM
(C) ContactsName
(C) ContactsNickname
(C) ContactsNote
(C) ContactsOrganization
(C) ContactsPhone
(C) ContactsPhoto
(C) ContactsPostalAddress
(C) ContactsRelation
(C) ContactsSipAddress
(C) ContactsWebsite
(I) IContactsDataField
(C) Provider
(C) Telephony (Telephony provider)
(N) Screen
(C) Framebuffer (Implementation of IFramebuffer)
(C) FramebufferInfo
(I) IFramebuffer (Interface of an RAW framebuffer)
(I) IFramebufferInfo
(I) IScreenDimension
(I) IScreenFocus
(C) Screen
(C) ScreenDimension
(C) ScreenFocus
(N) Shell
(I) IShell (Interface of an shell with in-/output abilities)
(C) Shell (Implementation of IShell)
(N) SQLite
(C) Options
(C) QueryTools
(C) SQLite3 (SQLite3 database connector)
(C) BuildProperties
(C) Daemon (Manage the daemon on the device)
(C) Device
(C) Forensics (ALFA-State)
(I) IUptime
(C) OpenRecoveryScript (Manage the OpenRecoveryScript)
(C) Phone (Start a call, dial a number, add a contact or send a sms)
(C) Su
(C) Uptime
(C) Wipe
(N) Shares
(C) Monitor (Implementation of IMonitor)
(N) Socket (This is the IP based implementation of ADB - Here is NO binary/exe required)
(C) ADB (static Management Class for the ADBClient's)
(C) ADBClient (Implementation of IADBClient)
(C) ADBSocket (IP based connector - Mimics the ADB-Server)
(C) Channel (Implementation of IChannel)
(C) ADBridge (Unified access to Binary.ADB and Socket.ADB)
(I) IADBClient (Interface for nearly all ADB commands)
(I) IChannel (Interface of an RAW data channel)
(N) Fastboot
(C) Backdoor (Some backdoor commands)
(C) Fastboot (static Management Class for the FastbootClient's)
(C) FastbootClient (Includes nearly all fastboot.exe commands)
(I) IFastbootClient (Interface for FastbootClient)
(C) Monitor (Implementation of IMonitor)
(C) OEM (Some OEM commands)
(C) Wipe
(N) ProcessModels
(C) General (Includes some predefined process models)
(I) IRealTimeBG (Interface of an background process with in-/output abilities)
(C) RealTimeBGExeV2 (Implementation of IRealTimeBG)
(N) Signer
(C) Signer (signapk.jar Interface)
(N) Tools
(C) CRC
(C) Deploy (Deploy the AAPT/ADB/Fastboot/Signer files needed by this dll)
(C) Hash
(C) Hex
(C) IMEI (Some helper to verify and rebuild a valid IMEI)
(C) ToolBox
(C) Cleanup (Delete the files/folders which were created by this dll)
(C) Config
(C) DeviceInfo (Basic device info, the return from "(Binary/Socket).ADB.Devices()" and "Fastboot.Devices()")
(I) IDeviceInfo (Interface for DeviceInfo)
(I) IMonitor (Interface for the ADB.Binary, ADB.Socket and Fastboot.Fastboot monitor)
Special
Ready-To-Go MVVM's for WPF, XAML via my AndroidCtrlUI.dll
Multi-Device compatible, you can manage unlimited devices at the same time with this dll. Each device gets it's own instance. (Thread-Safe, the dll use lock() for critical sections)
UTF8-File/Folder Transfer you can transfer files/folders with containing special chars (ü, ö, ä, €, @, à, è, etc.)
On-the-fly Device to Device copy (Binary <-> Binary | Binary <-> Socket | Socket <-> Socket)
Device-Monitor, if activated, it will check every 10 sec. ADB & Fastboot for new connected devices and call an defined callback, if something changed. So your program get's an info if an device is connected or removed.
All Android key-events as (int)enum and the ability to send them as single or stack.
Hint
You can use all ADB methods/commands via USB or W-Lan/Lan, if your Rom supports ADB via W-Lan/Lan (Settings/Developer Settings)
If you want to use all sub-classes of IADBClient with BusyBox instead of the Shell, you have to set IADBClient.UseBusyBox to true. This will tell the instance to use the BusyBox commands inside each method, if the device has BusyBox installed.
Referenced .NET assembly's
System
System.Numerics
System.XML
Used Code-analysis rules:
Basic & Advanced Microsoft-Rules for Accuracy
Microsoft-managed minimum & recommended rules
Microsoft Security Rules
About the usage, the namespaces (ADB, Fastboot, Signer) have one basic instance. For example, ADB.Instance(), Fastboot.Instance(), Signer.Instance. As you can see ADB.Instance() and Fastboot.Instance() can have a parameter. This parameter is in both cases an (string) DeviceID, an IDeviceInfo or null, if you use for example null, both classes will return it's Selected client. If you use the DeviceID or the IDeviceInfo the return is a fresh instance of the client or the already created instance. So, in any case, before you call ADB/Fastboot.Instance(). Check with ADB/Fastboot.Devices() if you have a connected device. If so, use the IDeviceInfo object to start your device instance or simply pass the serial to the Instance(). All instances which you have created on this way, will be hold inside an Dictionary<string, ADBClient>, so you can configure each device instance to it's needs and call it when ever you need it. This is also the point where i say it's multi-device and multi-thread safe. Because, if you always use ADB/Fastboot.Instance() you can't reach the wrong device. Also, all classes using lock() for critical sections, because [MethodImpl(MethodImplOptions.Synchronized)] is not longer available under .NET Standard.
If you have any wishes like new features, how-to's or something else, let me know! :cyclops:
Tested OS
Win Vista | 7 | 8 | 8.1 | 10 (32Bit/64Bit in VM-Ware)
Win 7 | 8 | 8.1 | 10 (64Bit Native)
Win XP is not longer supported by ADB! (But, if you have a old ADB binary, the dll will do it's job)
Tested Devices
Android Emulator some Versions (min. 2.x) in AVD
Android x86
HTC Sensation -/ XE (non-/rooted)
HTC One M9 (non-/rooted)
Huawei P9 Lite (VNS-L21,22,23,31,etc.) (non-/rooted)
Huawei P10 Lite (WAS-LX1A,etc.) (non-/rooted)
Samsung Galaxy 2-5 (non-/rooted)
Samsung Galaxy S Plus (non-rooted)
A few Samsung Tabs (non-/rooted)
Google Pixel 4 (Android 11) (non-/rooted)
Requirements
Android: min. 2.x
Platform: x86/x64 (Windows)
Frameworks: min. .NET 4.6 and JRE (only for the Signer)
(Installed ADB/Fastboot device driver)
Download
Mirror: XDA-DevDB (since 29.01.2019 no uploads possible)
Mirror #1: My FTP (Build archiv)
Mirror #2: GoogleDrive
Mirror #3: Dropbox
Each zip-archiv contains the AndroidCtrl.dll, its markup file AndroidCtrl.xml and the program debug database AndroidCtrl.pdb for .NET 4.6|4.7|4.8 and .NET Standard 2.1 (beta)
Examples (Updated to dll version 7.1.46.0) (Updated in the next 24 h)
Mirror: My FTP
Mirror #1: GoogleDrive
Mirror #2: Dropbox
(Contains a simple exe and its source written in C# WPF)
Source
N/A (If you want to have a look at it, send me a PM or simply decompile it.)
DO NOT MIRROR MY FILES! DO NOT COPY MY THREADS!
XDA:DevDB Information
AndroidCtrl.dll, Tool/Utility for the Android General
Contributors
k1ll3r8e, squabbi, Krystanos
Version Information
Status: Stable
Current Stable Version: 7.1.46.0
Stable Release Date: 2020-09-19
Created 2016-07-24
Last Updated 2020-09-19

How - To
0. Complete How-To
1. Getting Started (General)
2. Config & Deploy
3. Individual Call (ADB/Fastboot/Signer)
4. Start/Stop (ADB/Fastboot)
5. Reboot (ADB/Fastboot)
6. DeviceConnectionMonitor
7. Device state check
8. Send KeyEvents (ADB)

Problems & Solutions
1. Windows 8.x | 10.x
NOTE
If u use any callback functions, u have to invoke any UI-/ variable-interaction from an dispatcher like the following example:
Code:
public void Monitor(Added|Changed|Removed)EventHandler(object sender, Monitor(Added|Changed|Removed)EventArgs e)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
// IDeviceInfo[] e.Devices
// Here u can interact with an UI-Element or an variable in ur program code
});
}
if u do it without dispatcher, u'll get an "Thread Exception".
More examples coming soon...
(If u need a specific example, just let me know, i'll try my best to provide one.)

Changelog
DD.MM.YYYY | (A) = Added | (C) = Changed | (D) = Deleted | (F) = Fixed | (R) = Recoded | (U) Updated
----------------------------------------------------------------------------------------------------------------------------------------------------
26.07.2020 [7.0.46.0]
(A) Some new Async overloads to the AFileInfo, AFileSystemInfo, ADirectoryInfo and AMountpointInfo.
(F) A few little bugs
01.02.2020 [6.7.46.0]
(A) ADB.IADBClient{} (The old IADB interface)
(A) ADB.Binary.ADB{} (The old ADB class - only the statics)
(A) ADB.Binary.ADBClient{} (The old ADB class - without any statics)
(A) ADB.Socket.ADB{} (The old ADB class - only the statics)
(A) ADB.Socket.ADBClient{} (The old ADB class - without any statics)
(A) ADB.Device.ADirectoryInfo{}
(A) ADB.Device.AFileInfo{}
(A) ADB.Device.AFileStream{}
(A) ADB.Device.AMountPointInfo{}
(A) ADB.Device.FileSystemCache{}
(A) ADB.Device.IFileSystemCache{}
(D) ADB.Device.Directories{}
(D) ADB.Device.Files{}
(D) ADB.Device.FileSystem{}
(D) ADB.Device.FileSystemItem{}
(D) ADB.Device.IFileSystemItem{}
And everything related to those classes... Directories has been replaced with ADirectoryInfo, Files has been replaced with AFileInfo and FileSystem has been replaced with AMountPointInfo.
31.05.2019 [6.0.46.0]
(C) The Framework Version from 4.0 to 4.6
(C) The versioning:
6 = Major
0 = Minor
46 = Framework Version (4.6)
0 = Hotfix
(A) (int) ADB.Instance().Device.Screen.GetAutoBrightness()
(A) (int) ADB.Instance().Device.Screen.GetBrightness()
(A) (ScreenBrightnessMode) ADB.Instance().Device.Screen.GetBrightnessMode()
(A) (ScreenRotation) ADB.Instance().Device.Screen.GetRotation()
(A) (ScreenRotationMode) ADB.Instance().Device.Screen.GetRotationMode()
(A) (bool) ADB.Instance().Device.Screen.SetBrightness(int brightness)
(A) (bool) ADB.Instance().Device.Screen.SetBrightnessMode(ScreenBrightnessMode mode)
(A) (bool) ADB.Instance().Device.Screen.SetRotation(ScreenRotation rotation)
(A) (bool) ADB.Instance().Device.Screen.SetRotationMode(ScreenRotationMode mode)
(D) ASDK (enum)
(C From) (ASDK) ADB.Instance().Device.GetSDK()
(C To) (int) ADB.Instance().Device. GetSDK()
10.04.2019 [0.0.5.2]
(A) A workaround for older SU binaries
Code:
// (Source ADB.Device.Su {})
///<summary>
/// Enables an (W)ork(A)round for older SU binaries, which needs the command as an single argument.
///<para/>For example, the latest SU binaries support a syntax like [su -c id -u] where older binaries need [su -c "id -u"]
///<para/>If u deactivate this workaround by enabled <see cref="IADB.UseSu"/>, <see cref="IADB.UseSu"/> gets also disabled!
///<para/>This workaround is by default disabled
///<para/>Affected Methods:
///<para/><see cref="ShellCmd(string, int)"/>, <see cref="ShellCmd(string, CancellationToken, int)"/>, <see cref="ShellCmd(string, ShellDataEventHandler, int)"/>, <see cref="ShellCmd(string, ShellDataEventHandler, CancellationToken, int)"/>
///<para/><see cref="ShellCmdHRes(string, int)"/>, <see cref="ShellCmdHRes(string, CancellationToken, int)"/>, <see cref="ShellCmdHRes(string, ShellDataEventHandler, int)"/>, <see cref="ShellCmdHRes(string, ShellDataEventHandler, CancellationToken, int)"/>
///</summary>
public bool WA_SingleArgument
(A) A fix for unresponsive interactive shells. This happened to me on Lineage on my HTC Sensation, where the device sends an "resize" request... Sending a command in this state caused the command getting cut at the 1st byte, for example, u send "id -u" the delivered command was "d -u".
(A) Added "feature" detection for Binary.ADB, now u can get the "features" of the device like: cmd, stat, stat_v2, shell, shell_v2, etc. in the "IChannel.Features".
(R) Removed the last bit of code duplication and optimized some internal logic's. For example, the "Socket.IChannel" got a speed boost from ~1.920.000 bytes during an transfer of 14.400.000 bytes.
06.03.2019 [0.0.5.1]
(C) ADB.Device structure (see 1st post)
(R) ADB.Device.Provider (Decreased the loading time of the contacts and their data)
(D) AAPT completely
Older Changes:
16.02.2019 [0.0.4.2]
(A) DNS lookup for ADB.Socket
(R) Reduced code duplication
07.02.2019 [0.0.4.1]
(F) An issue inside the ADB.Binary, the problem was that "ADB.Devices()" returned nothing, if more than one device was connected. Reason for the issue was the "(int)IChannel.ReadHexLength()" function, there i read an Int16 but it was an UInt16 which caused an overflow.
29.01.2019 [0.0.4.0]
(U) AAPT, ADB, Fastboot binaries and the required dlls to the latest version (1.0.40)
(A) ADB.ADBridge - Unified access to ADB.Binary and ADB.Socket
(A) ADB.IADB - Interface for ADB-/Socket with nearly all ADB commands
(A) ADB.IChannel - Interface of an ADB-/Socket RAW-data channel
(A) ADB.IFramebuffer - Interface for the ADB-/Socket framebuffer
(A) ADB.IShell - Interface for the ADB-/Socket Shell v1 & v2
(A) IMonitor - Interface for the ADB-/Socket and Fastboot device-monitor
(A) On-the-fly device to device copy (ADB.Binary <-> ADB.Binary | ADB.Binary <-> ADB.Socket | ADB.Socket <-> ADB.Socket)
Reordered the ADB namespace... The old layout was:
ADB - Binary based ADB
ADB.Device - Device helper
ADBSocket - Socket based ADB
The new layout is:
ADB - Main ADB
ADB.Binary - Binary based ADB
ADB.Device - Device helper
ADB.Shared - Shared helper, extensions for ADB.Binary and ADB.Socket
ADB.Socket - Socket based ADB
Implemented the framebuffer for ADB.Binary and ADB.Socket (A ready-to-go Remote-Desktop is available via my AndroidCtrlUI.dll)
09.04.2018 [0.0.3.1]
This is a complete new version!
-
I added a lot of new stuff like the "CancellationToken" overload, the "MediaScanner" class and also some fine tunes to the "Screen" class, there u can now also get the Screen dimensions. Also a lot models like the old MemDumpxxx_4xx have been removed (we are now 4 versions higher and the outputs are not longer available or have changed to much).
15.02.2018 [0.0.2.5]
(F) A problem where a NULL exception was raised during directory parsing
(F) A few UI freezes and applied a few tweaks to some logic's.
(D) Tools.Icons {}
(D) Tools.TrayNotify {}
Reason for this is the upcoming compatibility to .NET Core. BUT, the functions are not lost, i added those not .NET Core compatible calls to the AndroidCtrlUI.dll... Because the UI dll will be never migrated to .NET Core.
03.11.2017 [0.0.2.4]
Nearly full new build
-
Sadly my notes are lost, based on a data loss on my Dev Environment...

Showcase
ADB-Overlay made by me
The XDA-Thread and Download can be found here
P10 Lite Toolkit made by me
The XDA-Thread and Download can be found here
P9 Lite Toolkit made by me
The XDA-Thread and Download can be found here
HTC One Toolkit from our Member @squabbi
The XDA-Thread and Download can be found here
--
U use this dll in ur project?
Send me a PM with:
Project Name
Small image
Short description
Download link
then i'll link it here.

An interesting library, time to change Droid Manager code base to use this one ^__^
Thanks for your hard work :highfive:

Could you put an example of how to use the adb and fastboot commands?
such as adb reboot
and fastboot reboot

squabbi said:
Could you put an example of how to use the adb and fastboot commands?
such as adb reboot
and fastboot reboot
Click to expand...
Click to collapse
Yup i'll do it right now
#EDIT:
Added:
Start/Stop ADB/Fastboot
Check if ADB/Fastboot is running
Device Reboot ADB/Fastboot
Sending KeyEvents ADB

Hey another question. How would I use for example:
Code:
Fastboot.Instance().OEM.ReadCid();
I would presume there would need to be a 'string' for it to save to.
Code:
private string _cid
??
EDIT: So i deciced to try this:
Code:
MessageBox.Show("cid: " + Fastboot.Instance().OEM.ReadCid());
When I press the button it shows:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Thanks!

squabbi said:
Hey another question. How would I use for example:
Code:
Fastboot.Instance().OEM.ReadCid();
I would presume there would need to be a 'string' for it to save to.
Code:
private string _cid
??
EDIT: So i deciced to try this:
Code:
MessageBox.Show("cid: " + Fastboot.Instance().OEM.ReadCid());
When I press the button it shows:
Thanks!
Click to expand...
Click to collapse
Hey there
Methods/functions like "ReadCid()" returns a "List<string>" so u can do like:
Code:
string cid = string.Join(" ", Fastboot.Instance().OEM.ReadCid().ToArray());
// or
// The return are 3 lines, so we need to get the 2cnd
string cid = Fastboot.Instance().OEM.ReadCid()[1];
NOTE
I return there a "List<string> (the raw output)" coz i dun know if the output will be the same on each device.
In this case u have filter the right line ur self
Hope this helps

k1ll3r8e said:
Hey there
Methods/functions like "ReadCid()" returns a "List<string>" so u can do like:
Code:
string cid = string.Join(" ", Fastboot.Instance().OEM.ReadCid().ToArray());
// or
// The return are 3 lines, so we need to get the 2cnd
string cid = Fastboot.Instance().OEM.ReadCid()[1];
NOTE
I return there a "List<string> (the raw output)" coz i dun know if the output will be the same on each device.
In this case u have filter the right line ur self
Hope this helps
Click to expand...
Click to collapse
Thanks again!
It worked perfectly! Another question. I'm now using a textbox to show the output like this:
Code:
MainWindow mainWin = (MainWindow)App.Current.MainWindow;
mainWin.tBOutput.AppendText(String.Join("", "\n", Fastboot.Instance().OEM.ReadCid()[1]));
mainWin.tBOutput.ScrollToEnd();
How can I do this but in a seperate window? Like one that is seperate from the MainWindow.
Thanks! :good:

squabbi said:
Thanks again!
It worked perfectly! Another question. I'm now using a textbox to show the output like this:
Code:
MainWindow mainWin = (MainWindow)App.Current.MainWindow;
mainWin.tBOutput.AppendText(String.Join("", "\n", Fastboot.Instance().OEM.ReadCid()[1]));
mainWin.tBOutput.ScrollToEnd();
How can I do this but in a seperate window? Like one that is seperate from the MainWindow.
Thanks! :good:
Click to expand...
Click to collapse
Hey there
There are 3 and more options how u can handle this...
1. Simple "MessageBox"
Code:
MessageBox.Show(string.Join("\n", Fastboot.Instance().OEM.ReadCid().ToArray()));
2. Extra Window
XAML
Code:
<Window x:Class="Multi_Explorer.viewmodel.android.fastboottools.htc.CidDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Show CID" Height="410" Width="300" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid>
<RichTextBox x:Name="TokenOutput" IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Auto">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0,0,0,0"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
</FlowDocument>
</RichTextBox>
</Grid>
</Window>
CS
Code:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
namespace Multi_Explorer.viewmodel.android.fastboottools.htc
{
/// <summary>
/// Interaktionslogik für CidDialog.xaml
/// </summary>
public partial class CidDialog : Window
{
#region Instance
private static CidDialog _instance = null;
public static CidDialog Instance
{
get
{
if (_instance != null)
{
return _instance;
}
else
{
_instance = new CidDialog();
return _instance;
}
}
}
#endregion
public CidDialog()
{
InitializeComponent();
this.Closing += WindowClosing;
App.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
#region WindowClosing
///<summary>
/// Clean exit
///</summary>
private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
_instance = null;
}
#endregion
#region Add
public void Add(List<string> msg)
{
foreach (string tmp in msg)
{
TokenOutput.Document.Blocks.Add(new Paragraph(new Run(tmp)));
}
TokenOutput.ScrollToEnd();
}
#endregion
#region Clear
public void Clear()
{
TokenOutput.Document.Blocks.Clear();
}
#endregion
}
}
Usage
Code:
CidDialog ciddiag = CidDialog.Instance;
ciddiag.Add(Fastboot.Instance().OEM.ReadCid());
// As window
ciddiag.Show();
// As dialog window (this will freeze the complete application until it's closed)
ciddiag.ShowDialog();
3. Extra Window with ADB/Fastboot instance
XAML
Code:
<Window x:Class="Multi_Explorer.viewmodel.android.fastboottools.htc.CidDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Show CID" Height="410" Width="300" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid>
<RichTextBox x:Name="TokenOutput" IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Auto">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0,0,0,0"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
</FlowDocument>
</RichTextBox>
</Grid>
</Window>
CS
Code:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using AndroidCtrl;
using AndroidCtrl.ADB;
using AndroidCtrl.Tools;
using AndroidCtrl.Fastboot;
namespace Multi_Explorer.viewmodel.android.fastboottools.htc
{
/// <summary>
/// Interaktionslogik für CidDialog.xaml
/// </summary>
public partial class CidDialog : Window
{
public CidDialog()
{
InitializeComponent();
this.Closing += WindowClosing;
App.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
// If u have a selected device this will work in all sub-windows
Add(Fastboot.Instance().OEM.ReadCid());
}
#region WindowClosing
///<summary>
/// Clean exit
///</summary>
private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
_instance = null;
}
#endregion
#region Add
public void Add(List<string> msg)
{
foreach (string tmp in msg)
{
TokenOutput.Document.Blocks.Add(new Paragraph(new Run(tmp)));
}
TokenOutput.ScrollToEnd();
}
#endregion
#region Clear
public void Clear()
{
TokenOutput.Document.Blocks.Clear();
}
#endregion
}
}
Usage
Code:
CidDialog ciddiag = CidDialog.Instance;
// Optional
// ciddiag.Add(Fastboot.Instance().OEM.ReadCid());
// As window
ciddiag.Show();
// As dialog window (this will freeze the complete application until it's closed)
ciddiag.ShowDialog();

k1ll3r8e said:
Hey there
There are 3 and more options how u can handle this...
Click to expand...
Click to collapse
Thanks for clarifying! What if i want to get the identifier code? it has multiple strings? how can i choose to show all of them?
EDIT: (More questions! )
Is it possible to use:
Code:
foreach (DataModelDevicesItem device in adbDevices)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
// here goes the add command ;)
deviceselector.Items.Add(device);
});
}
foreach (DataModelDevicesItem device in fastbootDevices)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
deviceselector.Items.Add(device);
});
}
to check if the device is in fastboot or adb? e.g
I press a button to flash recovery. i can have my phone in adb or fastboot and it will check to see which it is in. Then it wil lcarry out a specific command?

Hey there
squabbi said:
Thanks for clarifying! What if i want to get the identifier code? it has multiple strings? how can i choose to show all of them?
Click to expand...
Click to collapse
If u mean the HTC-Bootloader unlock code, u can use the described 2 or 3.
(Both window examples have an "foreach loop" to print out each line from the List<string> into the RichTextBox)
If u want also replace the "(bootloader) " tag u can use this line:
Code:
TokenOutput.Document.Blocks.Add(new Paragraph(new Run(tmp.Replace("(bootloader) ", ""))));
just replace it in the CS code with the one in the "foreach loop".
squabbi said:
EDIT: (More questions! )
Is it possible to use:
Code:
foreach (DataModelDevicesItem device in adbDevices)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
// here goes the add command ;)
deviceselector.Items.Add(device);
});
}
foreach (DataModelDevicesItem device in fastbootDevices)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
deviceselector.Items.Add(device);
});
}
to check if the device is in fastboot or adb? e.g
Click to expand...
Click to collapse
Yes, so i do it in my projects also.
squabbi said:
I press a button to flash recovery. i can have my phone in adb or fastboot and it will check to see which it is in. Then it wil lcarry out a specific command?
Click to expand...
Click to collapse
For this scenario, u need a function which checks which state have the current device serial. After u have the state ADB or Fastboot, u can call 2 different methods from my dll:
ADB
Code:
// This requires Root in any case!
ADB.Instance().Device.FlashImage(IDDevicePartition partition, string localPath, bool tmpToSD = true, int timeOut = -1);
Fastboot
Code:
Fastboot.Instance().Flash(IDDevicePartition partition, string file, int timeOut = -1);
NOTE
I will build a function which will do the work in the future, next release will include it.
#EDIT:
Release it out
Code:
AndroidCtrl.Tools.General.CheckDeviceState(string deviceID);
// return is a IDDeviceState
Hope this helps

k1ll3r8e said:
Hey there
If u mean the HTC-Bootloader unlock code, u can use the described 2 or 3.
(Both window examples have an "foreach loop" to print out each line from the List<string> into the RichTextBox)
If u want also replace the "(bootloader) " tag u can use this line:
Code:
TokenOutput.Document.Blocks.Add(new Paragraph(new Run(tmp.Replace("(bootloader) ", ""))));
just replace it in the CS code with the one in the "foreach loop".
Yes, so i do it in my projects also.
For this scenario, u need a function which checks which state have the current device serial. After u have the state ADB or Fastboot, u can call 2 different methods from my dll:
ADB
Code:
// This requires Root in any case!
ADB.Instance().Device.FlashImage(IDDevicePartition partition, string localPath, bool tmpToSD = true, int timeOut = -1);
Fastboot
Code:
Fastboot.Instance().Flash(IDDevicePartition partition, string file, int timeOut = -1);
NOTE
I will build a function which will do the work in the future, next release will include it.
#EDIT:
Release it out
Code:
AndroidCtrl.Tools.General.CheckDeviceState(string deviceID);
// return is a IDDeviceState
Hope this helps
Click to expand...
Click to collapse
Hey there!
Im using this for the output:
Code:
IDDeviceState state = General.CheckDeviceState(ADB.Instance().DeviceID);
if (state == IDDeviceState.DEVICE)
{
ADB.Instance().Reboot(IDBoot.BOOTLOADER);
CidDialog ciddiag = CidDialog.Instance;
ciddiag.Add(Fastboot.Instance().OEM.GetIdentifierToken());
ciddiag.Show();
}
else if (state == IDDeviceState.FASTBOOT)
{
CidDialog ciddiag = CidDialog.Instance;
ciddiag.Add(Fastboot.Instance().OEM.GetIdentifierToken());
ciddiag.Show();
}
When I first press the button the output window shows. When I close it and press the button again it gives me this error - even if I wait a couple of seconds.
Thanks for your help! :fingers-crossed::good:

squabbi said:
Hey there!
Im using this for the output:
Code:
IDDeviceState state = General.CheckDeviceState(ADB.Instance().DeviceID);
if (state == IDDeviceState.DEVICE)
{
ADB.Instance().Reboot(IDBoot.BOOTLOADER);
CidDialog ciddiag = CidDialog.Instance;
ciddiag.Add(Fastboot.Instance().OEM.GetIdentifierToken());
ciddiag.Show();
}
else if (state == IDDeviceState.FASTBOOT)
{
CidDialog ciddiag = CidDialog.Instance;
ciddiag.Add(Fastboot.Instance().OEM.GetIdentifierToken());
ciddiag.Show();
}
When I first press the button the output window shows. When I close it and press the button again it gives me this error - even if I wait a couple of seconds.
Thanks for your help! :fingers-crossed::good:
Click to expand...
Click to collapse
Hey there
oh yes, that is my fault
U have to add this to ur Window constructor "CidDialog(){}"
Code:
this.Closing += WindowClosing;
And this is the "WindowClosing method"
Code:
#region WindowClosing
///<summary>
/// Clean exit
///</summary>
private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
_instance = null;
}
#endregion
Explain
"CidDialog.Instance" create a new instance of the window. But on close the instance will not be set to null. So u can't open it again, coz the system think it's still open.
Hope this helps
#EDIT:
I updated the examples 2 and 3 also.

k1ll3r8e said:
Hey there
oh yes, that is my fault
U have to add this to ur Window constructor "CidDialog(){}"
Code:
this.Closing += WindowClosing;
And this is the "WindowClosing method"
Code:
#region WindowClosing
///<summary>
/// Clean exit
///</summary>
private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
_instance = null;
}
#endregion
Explain
"CidDialog.Instance" create a new instance of the window. But on close the instance will not be set to null. So u can't open it again, coz the system think it's still open.
Hope this helps
#EDIT:
I updated the examples 2 and 3 also.
Click to expand...
Click to collapse
Thanks a lot man! Time to put everything in full motion! ?
Sent from my HTC One_M8 using Tapatalk

squabbi said:
Thanks a lot man! Time to put everything in full motion! ?
Sent from my HTC One_M8 using Tapatalk
Click to expand...
Click to collapse
Np dude
Good Luck!

Hey there! I may be over looking, but where can I use the 'fastboot boot image.img' command?
Thanks!

squabbi said:
Hey there! I may be over looking, but where can I use the 'fastboot boot image.img' command?
Thanks!
Click to expand...
Click to collapse
Hey bro,
I dun implemented it sry... Next build will include it.
Upload starts tonight
Sent from my HTC Sensation using XDA Free mobile app

Related

[Q] Load SQLite DB

I have SQLite DB file. I copy him to StorageFile and open it by SQLite
Code:
...............................
using SQLiteClient;
using Community.CsharpSqlite;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Конструктор
private string fileName = "DB";
public MainPage()
{
InitializeComponent();
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
System.IO.Stream src = Application.GetResourceStream(new Uri(fileName, UriKind.Relative)).Stream;
IsolatedStorageFileStream dest = new IsolatedStorageFileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, store);
src.Position = 0;
CopyStream(src, dest);
dest.Flush();
dest.Close();
src.Close();
dest.Dispose();
IsolatedStorageFile tmp= IsolatedStorageFile.GetUserStoreForApplication();
if (!tmp.FileExists(fileName))
{
return;
}
SQLiteConnection db = new SQLiteConnection(fileName);
try
{
db.Open();
SQLiteCommand cmd = db.CreateCommand("SELECT * FROM table");
var lst = cmd.ExecuteQuery<Test>();
ApplicationTitle.Text = "Selected " + lst.ToList().Count + " items\r\nTime ";
}
catch (SQLiteException ex)
{
ApplicationTitle.Text = "Error: " + ex.Message;
}
}
private static void CopyStream(System.IO.Stream input, IsolatedStorageFileStream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
int readCount;
do
{
readCount = input.Read(buffer, 0, buffer.Length);
if (readCount > 0)
{
output.Write(buffer, 0, readCount);
}
} while (readCount > 0);
input.Position = TempPos;
}
}
public class Test
{
public Test()
{
}
int _id;
public int id
{
get { return _id; }
set { _id = value; }
}
}
}
Result : ApplicationTitle = unable to opendatabase file.
Why? Plz help.
Probably because you doing something wrong, for example, opening SQLiteConnection
Seems like correct syntax should be
Code:
new SqliteConnection("Version=3,uri=file:db")
Download and try source code from http://wp7sqlite.codeplex.com/SourceControl/list/changesets#
error "Couldn't open database file version=3,urlB"
file DB i created from command "backup DB File". It's right?
I have no idea what kind of file do you have. I just downloaded and ran example from sources mentioned above and it works fine (but with few assertions). BTW you should have a complete source code of SQLite, just debug into SQLite procedures and check what's wrong.
Example work fine. I want read database from project file (Content).He isn't located in StorageFile. I use him after i'm saving myfile to StorageFile .
evgen_wp said:
Example work fine. I want read database from project file (Content).He isn't located in StorageFile. I use him after i'm saving myfile to StorageFile .
Click to expand...
Click to collapse
I already understood you. Add your code (to save database file from resource stream to isf) to example, and test conn.Open() call using F11 (Step Into). You'll see what's wrong. I don't have your database file and have no idea what did you put inside
File did not have time to create. It is ... work now.he can open empty file but can't open file with data
P.S. I use Sqlite Client for Windows Phone from http://sqlitewindowsphone.codeplex.com/
Why don't you use another codeplex project I've posted above? It works fine for me (tested because of your question).
P.S. Don't forget to push "Thanks" button. It's not a paid Microsoft customer service and I'm not your support guy.

[Automation Tool] [Java] [WIP] [Tutorials] Selenium [RHBROMS]

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
SELENIUM by Ravi H Basawa​
This will be a Full Tutorial on Selenium Automation Tool
I will be updating this thread as I get time. SO NO ETA's.
Click to expand...
Click to collapse
If anybody wants to use / copy this tutorial to their Website or Blog please feel free to contact me at my personal email id: [email protected]
or at our official Website: www.rhbroms.com
Click to expand...
Click to collapse
Please Click on Thanks button if this tutorial by me had helped you for some extent !!!
Click to expand...
Click to collapse
Contents:
1. What is Selenium?
2. What all we need before we get it started?
3. How to setup Selenium for Eclipse?
4. Simple Selenium Test Script for google.co.in
5. Execution using Junit
5a. Execution using TestNG
6. DataDriven Testing using POI jar files
7. Issues or challenges with Selenium
Credits:
@Swaroop Bandagadde
My Other Works:
1. ROBOTIUM AUTOMATION TOOL
2. MONKEYRUNNER AUTOMATION TOOL
Selenium
1. What is Selenium?​
Selenium is an open source ( It's free !!!!) automation testing tool used for automating websites under any browser(not all).
Selenium supports the following browsers: IE, FireFox(Default), Chrome, Safari, Opera.
We write Selenium WebDriver Scripts in Eclipse. These scripts are written in Java language.
Things that you should be good at Java are: Constructors, Overriding, Overloading, Constructor Chaining, Interface, Inheritance, Abstract Class and UpCasting - DownCasting concepts are enough to write Selenium WebDriver Script.
What all we need before we get it started?
2. What all we need before we get it started?​
1. Windows 7 / 8
2. Java
3. Eclipse ((Juno or ADT) what I have worked on !! )
4. selenium-server-standalone-2.38.0
5. TestNG plugin for Eclipse
6. POI jar files
Downloads:
POI jar files: POI.zip
Selenium Jar file
How to setup Selenium for Eclipse?
3. How to setup Selenium for Eclipse?​
1. Open Eclipse goto Help -> Install new software.. -> give work with edittext field value as " TestNG - http://beust.com/eclipse " -> select all -> Next -> Finish
2. when you create a new test project inside its build path add selenium webdriver jar files. I will show it in next chapter.
4. Simple Selenium Test Script for Google website
4. Simple Selenium Test Script for Google website ​
1. Create new java project with name Selenium Test as shown below:
2. Now we have to add the selenium Jar file to the build path ( Goto project -> Properties -> Java Build path ) as shown in below screen shot and add the downloaded selenium-server-standalone-2.38.0.jar file. by clicking on the add external Jar's button. After this goto "Order and Export" tab click on "Select All" button and click "ok" button.
3.After completion of the above step now create a new java class ( Goto Project -> New -> Class) as shown in below ss and give name as TestWebDriver
4. After this now we will write a code to open Mozilla FireFox Browser and also open Google website inside it. The code for this is as below:
package com.rhb.selenium; // package name what I have given. It can differ with yours
import org.openqa.selenium.WebDriver; // Automatically imported by eclipse [This is for invoking the WebDriver class from selenium API]
import org.openqa.selenium.firefox.FirefoxDriver; // Automatically imported by eclipse [This is for invoking the FireFoxDriver class from selenium API]
public class TestWebDriver {
static WebDriver driver = null; // initialization
//the below method is made static to call this method inside our package without creating any instance for it.
public static void setup(){
driver = new FirefoxDriver(); // inbuilt method called from selenium class
driver.get("http://www.google.co.in"); // opens the website which is written inside the braces.
}
}
Click to expand...
Click to collapse
5. Now Lets create another java class called FunLib and inside this what we do is we will try to enter some text into the edit text box of the Google website and also we will click on the search button. the code for this is as below:
import org.openqa.selenium.By;
public class FunLib extends TestWebDriver {
public static void Search() throws InterruptedException {
driver.findElement(By.xpath("//div[@id='hplogo']")).click(); // clicks on the Google Logo
Thread.sleep(3000); // sleeps for 3000 milliseconds
driver.findElement(By.xpath("//input[@name='q']")).sendKeys("RHBROMS"); // type as RHBROMS in the edit text field
driver.findElement(By.xpath("//button[@id='gbqfb']")).click(); // Click on the Search button
Thread.sleep(3000); // again sleeps for 3000 milliseconds
driver.findElement(By.xpath("//li[1]/div/div/h3/a")).click(); // Click on the first link that is rhbroms.com
System.out.println("button got clicked"); // displays the msg on console.
}
}
Click to expand...
Click to collapse
6. Okay now you might be thinking as how to identify the edit text field as well as other elements.!! Its easy for that we need some Extensions for FireFox they are as below:
7. After installing these Extensions we now see how to use them to Identify the objects. Thing is we don't use all these but some, It again depends on which tool u want to use!!. which one is best for you.
8. First I will show you how to Identify the Google Logo by using Xpath. To do this open FireFox and open Google website and right click on Google Logo and select View XPath. After this you will see something like as shown below:
9. As you can see from the image as XPath is given as : id('hplogo') but thing is how to use this in our code.. Simple just add the tag type in this case it is <div> (The <div> tag defines a division or a section in an HTML document.) the changes what u have to do is as shown in below Screen Shot.
10. Now the same goes for other objects too..!! If you find any doubts on this feel free to ask me by either commenting here or by emailing me.
11. Now we will see how to execute our first Automation Script in the next chapter.
5. Execution using Junit and TestNG
5. Execution using Junit ​
1. First we will see how to execute our script via JUnit Suit.
2. Let us create a new JUnit test case (project -> New -> Junit test case) as shown in below screen shot:
3. Now let us give the Junit test case name as "Junit" as shown below in the screen shot. NOTE: Uncheck setup and teardown options.
4. Okay as we are done with creating new Junit test case just do the below editing:
package com.rhb.selenium; // package name
import junit.framework.TestCase; // auto import
import org.testng.annotations.Test; // auto import to give annotations that are necessary
public class Junit extends TestCase {
@Test
public void test1() throws Exception{
Main m = new Main(); // creating instance for Main class as "m"
m.setup(); // as setup is a method which is declared under Main class we can access it using access specifier "m"
m.Search(); // as Search is a method which is declared under Main class we can access it using access specifier "m"
}
}
Click to expand...
Click to collapse
5. To run the above JUnit Test right click on Junit.java file -> RunAs -> Junit Test
6. When you run the Junit test FireFox runs automatically in WebDriver mode as shown below and all the operations that we have specified in the Main class will be performed. Screen Shot of this is as shown below:
7. The below snap shows the test case is pass and the color is changed to Green. And also we got a msg at console as "button got clicked" what we have written in FunLib.java !!
8. The Result at FireFox WebDriver should be as shown below:
9. Okay now we will see how to execute using TestNG ( Easy one )
5a. Execution using TestNG
5a. Execution using TestNG​
1. Don't worry it is very easy compared to JUnit.
2. I hope you have installed the plugin of TestNG to your Eclipse.
3. Lets Create a new java class with name TestNGSuite1. Copy paste the below code after creation:
package com.rhb.selenium;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.testng.annotations.Test;
public class TestNGSuite1 {
@Test
public void testngtest() throws FileNotFoundException, InvalidFormatException, IOException, Exception {
Main m = new Main(); // instance of Main class
m.setup(); // call for setup method
m.Search(); // call for Search method
}
}
Click to expand...
Click to collapse
3. Right click on TestNGSuite1.java file -> TestNG -> Convert to TestNG as shown in below screen shot:
4. Now you will see as below Screen Shot, here TestNG is converting our java file to executable xml format.
5. Now click on Finish button and you will see a Testing.xml file as shown below:
6. Now Just right click on the xml file -> RunAs -> TestNG Suite as shown below:
7. Finally you will see the final result as below:
6. DataDriven Testing using POI jar files and TestNG XSLT + ANT
6. DataDriven Testing using POI jar files​
1.We go for data driven testing when we have some modules that need to be tested for multiple values. For example in a application which has a login page with username and password field we have to test these edit text boxes for multiple inputs, It can be a number or it also can be a string or both together.
2. Here I will take Google.com as example and show you how to extract data from a excel file and push the same to Google website.
3. First we will create an excel file with some data present in it to test our application. (An Excel file for testing our app is attached here)
4. To extract data from Excel we use “FileInputStream” Class by which we can create/delete and modify a file.
5. Now add POI.jar files to Java Build Path same as how we added Selenium Jar file.
6. After adding of POI jar files to Java Build Path you will see them added as shown below:
7. After this is done we will create a new java class and will give the name as "DataDriveTest" and extend it from "TestWebDriver" Class.
8. Now what we will do is we will open google.com enter "search" value as "RHBROMS" ( 1st value from the excel sheet ) click on the first link and then we will click on back button of the browser and then we will clear the search box and enter "xda developers" ( 2nd value from the excel sheet ) and click on first link that will be xda developers website.
9. The code for this is as written below with explanation.
package com.rhb.selenium;
// below package imports are for File I/O operations
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
// below packages are for excel sheet operations
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
public class DataDriveTest extends TestWebDriver {
public static void test() throws Exception, IOException,
FileNotFoundException,InvalidFormatException {
String cellval1 = null; // set the current value of cellval1 as NULL
String cellval2 = null; // set the current value of cellval2 as NULL
FileInputStream fis= new FileInputStream("E:\\Test.xls");
Workbook wb = WorkbookFactory.create(fis); // creates object for workbook Test.xls
Sheet ws = wb.getSheet("Sheet1"); // opens Sheet1 from workbook Test.xls
int rc = ws.getLastRowNum(); // counts the number of rows which are used
for(int i=1; i<=rc; i++)
{
Row r = ws.getRow(i); // ponts to the i'th ROW
for (int j=0;j==0;j++){
{
Cell c = r.getCell(j); // points to the j'th Column
cellval1=c.getStringCellValue(); // gets the data from J'th cell
Cell c1 = r.getCell(j+1); // ponts to the J+1'th column
cellval2=c1.getStringCellValue(); // gets the data from J+1'th cell
driver.findElement(By.xpath("//div[@id='hplogo']")).click(); // Clicks on the google logo
driver.findElement(By.xpath("//input[@name='q']")).sendKeys(cellval1); // take the first value from first column and paste it at the search box
driver.findElement(By.xpath("//button[@id='gbqfb']")).click(); // clicks on the search button
Thread.sleep(3000); // sleeps for 3000milisecs
driver.findElement(By.xpath("//li[1]/div/div/h3/a")).click(); // clicks on first link
driver.navigate().back(); // clicks on the back button of the browser
driver.findElement(By.xpath("//input[@name='q']")).clear(); // clears the search box
driver.findElement(By.xpath("//input[@name='q']")).sendKeys(cellval2); // enters the second value from the excel sheet
driver.findElement(By.xpath("//button[@id='gbqfb']")).click(); // clicks on the search button again
Thread.sleep(3000);
driver.findElement(By.xpath("//li[1]/div/div/h3/a")).click(); // clicks on the first link
}
}
}
}
}
Click to expand...
Click to collapse
10. Now to execute this we have to do some editing at Main.java file as:
Code:
public class Main extends DataDriveTest {
public static void main(String args[]) throws FileNotFoundException, InvalidFormatException, IOException, Exception{
setup();
test();
}
11. And also in TestNGSuit1.java file as:
Code:
@Test
public void testngtest() throws FileNotFoundException, InvalidFormatException, IOException, Exception {
Main m = new Main();
m.setup();
m.test();
}
12. Now as usual convert the TestNGSuit1 file to TestNG and execute. :victory:
13. To see your TestNG results go to your eclipse workspace and open selenium project inside that you will find test-output folder. As shown in below Screen Shot:
14. For Generation of Graphical and more clean Results we use TestNG xslt with ANT. lets see how to do it in Next Chapter :laugh::laugh:
6. TestNG xslt with ANT ​
1. Download Ant from here: http://ant.apache.org/
2. Unzip it and rename the folder as ant.
3. Set ANT_HOME to environmental variables.( In windows 7 Right click on Computer -> properties -> “Advance system setting”
-> Choose Advanced Tab
-> Press Environment Variables Button
-> In the System Variables, click New Button
Give the Variable Name:ANT_HOME
Give the Value: E:\ant
Click OK )
as shown in Below Screen Shot.
4. Set ANT_HOME path,
go to path
Give the Value C:\ANT\bin
Click OK
5. To check ANT works properly or not
In the command prompt, type:
Code:
ant -version
you will see as below Screen Shot:
6. Now download testng-xslt from HERE
7. After this extract the downloaded zip file and go to testNG-xslt -> src -> main -> resources and copy the file testng-results.xsl and also copy this file from testNG-xslt -> lib that is saxon-8.7.jar and keep them at any folder for time being.
8. Now go to your project workspace and goto SeleniumTest -> test-output and paste testing-results.xsl that you copied.
9. and now goto eclipse and add saxon-8.7.jar to buildpath.
NOTE: the thing is you have to keep all your jar files in a same folder as I have kept at jar folder as shown below in my setup:
10. Now after doing all this create new xml file and call it as Build.xml
11. After creating this just copy paste the below code:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<project name="SeleniumTest" default="compile" basedir=".">
<path id="cp">
<pathelement path="bin" />
<fileset dir="jars"/>
</path>
<!-- for compiling -->
<target name="compile">
<javac classpathref="cp" srcdir="src" destdir="bin"/>
</target>
<!-- for running -->
<target name="run" depends="compile">
<java classpathref="cp" classname="org.testng.TestNG" args="testng.xml"/>
</target>
<!-- for report generation -->
<target name="report" depends="run">
<xslt in="./test-output/testng-results.xml" style="./test-output/testng-results.xsl" out="./test-output/testng-xslt.html">
<param expression="${basedir}/test-output/" name="testNgXslt.outputDir" />
<classpath refid="cp"/>
</xslt>
</target>
</project>
12. After this save the file.
13. Now right click on the project and do as below and select TestNG:
14. Now Run the Build.xml file. and your results will be stored at Index.html at test-output folder.
To be continued .. NEXT will be Maven with TestNG!!
Excellent..
This tutorial helps in starting up with Selenium with all the configuration.
Thanks
Swaroop Bandagadde said:
This tutorial helps in starting up with Selenium with all the configuration.
Click to expand...
Click to collapse
Thank you @Swaroop Bandagadde for helping me to write this Tutorial !!..:victory:

[HOWTO] Write to media card (secondary storage) from an app under Android 4.4 KitKat

In Android 4.4 KitKat, Google/AOSP made the following change to the API specification, much to the detriment of app developers and users:
"The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."
Click to expand...
Click to collapse
Source: http://source.android.com/devices/tech/storage/index.html
You can read my rather unhappy write-up about it here: https://plus.google.com/108338299717386673901/posts/gjnmuaDM8sn
This only applies to dual-storage devices, i.e., devices with a user-writable internal flash storage AND a removable SD card. But if your device has both, as of Android 4.4, apps will no longer be able to write arbitrarily to the "secondary" storage (the SD card).
There is however still an API exposed that will allow you to write to secondary storage, notably the media content provider. This is far from an ideal solution, and I imagine that someday it will not be possible.
I've written a tiny bit of code to let your applications continue to work with files on the SD card using the media content provider. This code should only be used to write to the secondary storage on Android 4.4+ devices if all else fails. I would strongly recommend that you NEVER rely on this code. This code DOES NOT use root access.
The class:
Code:
/*
* Copyright (C) 2014 NextApp, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package nextapp.mediafile;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.MediaStore;
/**
* Wrapper for manipulating files via the Android Media Content Provider. As of Android 4.4 KitKat, applications can no longer write
* to the "secondary storage" of a device. Write operations using the java.io.File API will thus fail. This class restores access to
* those write operations by way of the Media Content Provider.
*
* Note that this class relies on the internal operational characteristics of the media content provider API, and as such is not
* guaranteed to be future-proof. Then again, we did all think the java.io.File API was going to be future-proof for media card
* access, so all bets are off.
*
* If you're forced to use this class, it's because Google/AOSP made a very poor API decision in Android 4.4 KitKat.
* Read more at https://plus.google.com/+TodLiebeck/posts/gjnmuaDM8sn
*
* Your application must declare the permission "android.permission.WRITE_EXTERNAL_STORAGE".
*/
public class MediaFile {
private final File file;
private final ContentResolver contentResolver;
private final Uri filesUri;
private final Uri imagesUri;
public MediaFile(ContentResolver contentResolver, File file) {
this.file = file;
this.contentResolver = contentResolver;
filesUri = MediaStore.Files.getContentUri("external");
imagesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
/**
* Deletes the file. Returns true if the file has been successfully deleted or otherwise does not exist. This operation is not
* recursive.
*/
public boolean delete()
throws IOException {
if (!file.exists()) {
return true;
}
boolean directory = file.isDirectory();
if (directory) {
// Verify directory does not contain any files/directories within it.
String[] files = file.list();
if (files != null && files.length > 0) {
return false;
}
}
String where = MediaStore.MediaColumns.DATA + "=?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };
// Delete the entry from the media database. This will actually delete media files (images, audio, and video).
contentResolver.delete(filesUri, where, selectionArgs);
if (file.exists()) {
// If the file is not a media file, create a new entry suggesting that this location is an image, even
// though it is not.
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.DATA, file.getAbsolutePath());
contentResolver.insert(imagesUri, values);
// Delete the created entry, such that content provider will delete the file.
contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}
public File getFile() {
return file;
}
/**
* Creates a new directory. Returns true if the directory was successfully created or exists.
*/
public boolean mkdir()
throws IOException {
if (file.exists()) {
return file.isDirectory();
}
ContentValues values;
Uri uri;
// Create a media database entry for the directory. This step will not actually cause the directory to be created.
values = new ContentValues();
values.put(MediaStore.Files.FileColumns.DATA, file.getAbsolutePath());
contentResolver.insert(filesUri, values);
// Create an entry for a temporary image file within the created directory.
// This step actually causes the creation of the directory.
values = new ContentValues();
values.put(MediaStore.Files.FileColumns.DATA, file.getAbsolutePath() + "/temp.jpg");
uri = contentResolver.insert(imagesUri, values);
// Delete the temporary entry.
contentResolver.delete(uri, null, null);
return file.exists();
}
/**
* Returns an OutputStream to write to the file. The file will be truncated immediately.
*/
public OutputStream write()
throws IOException {
if (file.exists() && file.isDirectory()) {
throw new IOException("File exists and is a directory.");
}
// Delete any existing entry from the media database.
// This may also delete the file (for media types), but that is irrelevant as it will be truncated momentarily in any case.
String where = MediaStore.MediaColumns.DATA + "=?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };
contentResolver.delete(filesUri, where, selectionArgs);
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.DATA, file.getAbsolutePath());
Uri uri = contentResolver.insert(filesUri, values);
if (uri == null) {
// Should not occur.
throw new IOException("Internal error.");
}
return contentResolver.openOutputStream(uri);
}
}
Source download (or cut/paste the above): http://android.nextapp.com/content/mediawrite/v1/MediaFile.java
Eclipse project with test app: http://android.nextapp.com/content/mediawrite/v1/MediaWrite.zip
APK of test app: http://android.nextapp.com/content/mediawrite/v1/MediaWrite.apk
The test project is currently configured to target the path /storage/extSdCard/MediaWriteTest (this is correct for a Note3, at least on 4.3...make sure you don't have anything there). Edit MainActivity.java in the Eclipse project to change it.
And again, let me stress that the above code might not work in the future should Google dislike it. I wouldn't recommend that the average app developer make use of this code, but if you're writing a file manager (or something else that competes with any of my other apps) , it might be useful to you. And actually at the time of writing, this functionality is NOT in FX File Explorer or WebSharing.
Follow up:
My understanding is that creating and deleting files with this method does work on Android 4.4, but making new directories does not.
Creating directories does work on Android 4.3 (e.g. Google Play Edition) devices that have crippled secondary storage, so that mkdir() method will be useful for all five people who own GPE devices who are still using 4.3.
Too good to be true!
Wow! This is perfect..
This issue has been resolved in another thread using a much simpler method...
Sent from my GT-I9505 using Tapatalk
AMoosa said:
This issue has been resolved in another thread using a much simpler method...
Sent from my GT-I9505 using Tapatalk
Click to expand...
Click to collapse
If that solution is for non-root app developers, can you provide a link?
Bear in mind this solution is for app developers writing apps for users who may be on stock firmware without root access. I'm familiar with the proper solution for rooted users, where media_rw is added for the WRITE_EXTERNAL_STORAGE permission in /etc/permissions/platform.xml.
tliebeck said:
If that solution is for non-root app developers, can you provide a link?
Bear in mind this solution is for app developers writing apps for users who may be on stock firmware without root access. I'm familiar with the proper solution for rooted users, where media_rw is added for the WRITE_EXTERNAL_STORAGE permission in /etc/permissions/platform.xml.
Click to expand...
Click to collapse
Root solution... Possible to grant WRITE_MEDIA_STORAGE via pm grant in shell (non root via adb shell?)? Samsung File Manager uses it and it can access to extsdcard. Better than modifying system file.
But I agree that we need Fixer app for that (to fix things in etc/permissions/platform.xml)
I did this method when we first got kitkat a while back http://forum.xda-developers.com/showthread.php?t=2524277
But rooted devices. Good job bro
tliebeck said:
If that solution is for non-root app developers, can you provide a link?
Bear in mind this solution is for app developers writing apps for users who may be on stock firmware without root access. I'm familiar with the proper solution for rooted users, where media_rw is added for the WRITE_EXTERNAL_STORAGE permission in /etc/permissions/platform.xml.
Click to expand...
Click to collapse
Hi. Yes it's the one you have cited. Isn't everyone on xda rooted these days? Lol.
Sent from my GT-I9505 using Tapatalk
pyler said:
Root solution... Possible to grant WRITE_MEDIA_STORAGE via pm grant in shell (non root via adb shell?)? Samsung File Manager uses it and it can access to extsdcard. Better than modifying system file.
But I agree that we need Fixer app for that (to fix things in etc/permissions/platform.xml)
Click to expand...
Click to collapse
The Samsung file manager declares it in its manifest, and I believe it's available to any system app that does so. I'm not sure on the method by which these permissions are granted (i.e., if it's based on having a certain signature, or if just being in /system is enough). I didn't think there was a means to grant it to any non-system app without using root though.
I did try just try declaring that in the manifest, and it pm grant returns the following (for shell and root):
Operation not allowed: java.lang.SecurityException: Permission android.permission.WRITE_MEDIA_STORAGE is not a changeable permission type
Click to expand...
Click to collapse
Thanks for the suggestion though, was worth a try.
AMoosa said:
Hi. Yes it's the one you have cited. Isn't everyone on xda rooted these days? Lol.
Sent from my GT-I9505 using Tapatalk
Click to expand...
Click to collapse
Yeah, this certainly isn't going to be *personally* useful to anyone here...just posted it for app devs catering to users on non-rooted stock stuff.
tliebeck said:
Yeah, this certainly isn't going to be *personally* useful to anyone here...just posted it for app devs catering to users on non-rooted stock stuff.
Click to expand...
Click to collapse
I have a question, if I install the kitkat 4.4.2 update for sprint can I then install apk or is there a diffrent way also im not rooted. Cause this is the only thing stopping me from installing the update.
dadda said:
I have a question, if I install the kitkat 4.4.2 update for sprint can I then install apk or is there a diffrent way also im not rooted. Cause this is the only thing stopping me from installing the update.
Click to expand...
Click to collapse
Would not recommend it, this is still not confirmed to work, and only affects applications that implement it. Only real solution is still rooting.
Thanks, I'm still debating on rooting my phone cause of my evo 3D camera stop working.
Apparently the latest update of ES File Explorer should give write access to the external SD card without root, here's the changelog:
Code:
V3.1.1
-Samsung external card write issue on Android 4.4 Kitkat
-Multi-thread download & copy setting
-Video/audio thumbnails
-Download Facebook video when playing(use FB link in homepage)
It would be interesting to know the hack the app used to write and delete files there!
virtualdj said:
Apparently the latest update of ES File Explorer should give write access to the external SD card without root, here's the changelog:
Code:
V3.1.1
-Samsung external card write issue on Android 4.4 Kitkat
-Multi-thread download & copy setting
-Video/audio thumbnails
-Download Facebook video when playing(use FB link in homepage)
It would be interesting to know the hack the app used to write and delete files there!
Click to expand...
Click to collapse
The above code should work for creating and deleting files.
My question would be whether or not they are able to create new folders? If they can, they've found a new workaround.
Base directory in this app is storage/extSdCard/WriteMediaTest
My base directory is storage/sdcard1/WriteMediaTest
Can you change this?
Wysłane z mojego GT-P3100 przy użyciu Tapatalka
tliebeck said:
The above code should work for creating and deleting files.
My question would be whether or not they are able to create new folders? If they can, they've found a new workaround.
Click to expand...
Click to collapse
ES Explorer can create directory on ext sdcard without root.
Anyone get updated with how to do that?
jimmod said:
ES Explorer can create directory on ext sdcard without root.
Anyone get updated with how to do that?
Click to expand...
Click to collapse
I just got 4.4.2 on m G Tab 8.3. I can't do a File.mkdir(), but I could do it from the command line. I could also do a cp. Maybe they are doing a Runtime.exec()?
Update. Just tried that. Did not work, permission denied. Weird that that shell user can, but an app user can't.
dburckh said:
I just got 4.4.2 on m G Tab 8.3. I can't do a File.mkdir(), but I could do it from the command line. I could also do a cp. Maybe they are doing a Runtime.exec()?
Update. Just tried that. Did not work, permission denied. Weird that that shell user can, but an app user can't.
Click to expand...
Click to collapse
Yes, adb shell (shell user) is able to create folder.
But if using terminal emulator app it permission denied.
Most likely shell user have write permission. But to switch to shell user from app will need root access.
Sorry for not updating this thread promptly with this information, but there is now a 4.4 folder creation workaround, courtesy of the developer of X-plore File Manager. Works on Samsung devices, but apparently doesn't on Sony or HTC stuff. Not sure why this is the case.
I haven't had time to update the original standalone sample app/project, but here's the complete workaround class straight out of FX beta. This code is designed to be built against Android 2.1 (API level 7), hence the use of reflection. It's using the media API to generate album art for an MP3 track and place it in the folder you want created. Tiny MP3 file is attached, place that in /res/raw.
Code:
package nextapp.maui.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import nextapp.maui.AndroidEnvironment;
import nextapp.maui.Maui;
import nextapp.maui.R;
import nextapp.maui.storage.ContentUriUtil;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
/**
* Wrapper for manipulating files via the Android Media Content Provider. As of Android 4.4 KitKat, applications can no longer write
* to the "secondary storage" of a device. Write operations using the java.io.File API will thus fail. This class restores access to
* those write operations by way of the Media Content Provider.
*
* Note that this class relies on the internal operational characteristics of the media content provider API, and as such is not
* guaranteed to be future-proof. Then again, we did all think the java.io.File API was going to be future-proof for media card
* access, so all bets are off.
*
* If you're forced to use this class, it's because Google/AOSP made a very poor API decision in Android 4.4 KitKat.
* Read more at https://plus.google.com/+TodLiebeck/posts/gjnmuaDM8sn
*
* Your application must declare the permission "android.permission.WRITE_EXTERNAL_STORAGE".
*/
public class MediaFile {
private static final String NO_MEDIA = ".nomedia";
private static final String ALBUM_ART_URI = "content://media/external/audio/albumart";
private static final String[] ALBUM_PROJECTION = { BaseColumns._ID, MediaStore.Audio.AlbumColumns.ALBUM_ID, "media_type" };
private static File getExternalFilesDir(Context context) {
if (AndroidEnvironment.SDK < AndroidEnvironment.FROYO) {
return null;
}
try {
Method method = Context.class.getMethod("getExternalFilesDir", String.class);
return (File) method.invoke(context, (String) null);
} catch (SecurityException ex) {
Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
return null;
} catch (NoSuchMethodException ex) {
Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
return null;
} catch (IllegalArgumentException ex) {
Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
return null;
} catch (IllegalAccessException ex) {
Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
return null;
} catch (InvocationTargetException ex) {
Log.d(Maui.LOG_TAG, "Unexpected reflection error.", ex);
return null;
}
}
public static boolean SUPPORTED = ContentUriUtil.FILES_URI != null;
private final File file;
private final Context context;
private final ContentResolver contentResolver;
public MediaFile(Context context, File file) {
this.file = file;
this.context = context;
contentResolver = context.getContentResolver();
}
/**
* Deletes the file. Returns true if the file has been successfully deleted or otherwise does not exist. This operation is not
* recursive.
*/
public boolean delete()
throws IOException {
if (!SUPPORTED) {
throw new IOException("MediaFile API not supported by device.");
}
if (!file.exists()) {
return true;
}
boolean directory = file.isDirectory();
if (directory) {
// Verify directory does not contain any files/directories within it.
String[] files = file.list();
if (files != null && files.length > 0) {
return false;
}
}
String where = MediaStore.MediaColumns.DATA + "=?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };
// Delete the entry from the media database. This will actually delete media files (images, audio, and video).
contentResolver.delete(ContentUriUtil.FILES_URI, where, selectionArgs);
if (file.exists()) {
// If the file is not a media file, create a new entry suggesting that this location is an image, even
// though it is not.
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// Delete the created entry, such that content provider will delete the file.
contentResolver.delete(ContentUriUtil.FILES_URI, where, selectionArgs);
}
return !file.exists();
}
public File getFile() {
return file;
}
private int getTemporaryAlbumId() {
final File temporaryTrack;
try {
temporaryTrack = installTemporaryTrack();
} catch (IOException ex) {
return 0;
}
final String[] selectionArgs = { temporaryTrack.getAbsolutePath() };
Cursor cursor = contentResolver.query(ContentUriUtil.FILES_URI, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
selectionArgs, null);
if (cursor == null || !cursor.moveToFirst()) {
if (cursor != null) {
cursor.close();
cursor = null;
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, temporaryTrack.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "{MediaWrite Workaround}");
values.put(MediaStore.MediaColumns.SIZE, temporaryTrack.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.AudioColumns.IS_MUSIC, true);
contentResolver.insert(ContentUriUtil.FILES_URI, values);
}
cursor = contentResolver.query(ContentUriUtil.FILES_URI, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
selectionArgs, null);
if (cursor == null) {
return 0;
}
if (!cursor.moveToFirst()) {
cursor.close();
return 0;
}
int id = cursor.getInt(0);
int albumId = cursor.getInt(1);
int mediaType = cursor.getInt(2);
cursor.close();
ContentValues values = new ContentValues();
boolean updateRequired = false;
if (albumId == 0) {
values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, 13371337);
updateRequired = true;
}
if (mediaType != 2) {
values.put("media_type", 2);
updateRequired = true;
}
if (updateRequired) {
contentResolver.update(ContentUriUtil.FILES_URI, values, BaseColumns._ID + "=" + id, null);
}
cursor = contentResolver.query(ContentUriUtil.FILES_URI, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?",
selectionArgs, null);
if (cursor == null) {
return 0;
}
try {
if (!cursor.moveToFirst()) {
return 0;
}
return cursor.getInt(1);
} finally {
cursor.close();
}
}
private File installTemporaryTrack()
throws IOException {
File externalFilesDir = getExternalFilesDir(context);
if (externalFilesDir == null) {
return null;
}
File temporaryTrack = new File(externalFilesDir, "temptrack.mp3");
if (!temporaryTrack.exists()) {
InputStream in = null;
OutputStream out = null;
try {
in = context.getResources().openRawResource(R.raw.temptrack);
out = new FileOutputStream(temporaryTrack);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
return null;
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
return null;
}
}
}
}
return temporaryTrack;
}
/**
* Creates a new directory. Returns true if the directory was successfully created or exists.
*/
public boolean mkdir()
throws IOException {
if (file.exists()) {
return file.isDirectory();
}
File tmpFile = new File(file, ".MediaWriteTemp");
int albumId = getTemporaryAlbumId();
if (albumId == 0) {
throw new IOException("Fail");
}
Uri albumUri = Uri.parse(ALBUM_ART_URI + '/' + albumId);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath());
if (contentResolver.update(albumUri, values, null, null) == 0) {
values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);
contentResolver.insert(Uri.parse(ALBUM_ART_URI), values);
}
try {
ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r");
fd.close();
} finally {
MediaFile tmpMediaFile = new MediaFile(context, tmpFile);
tmpMediaFile.delete();
}
return file.exists();
}
/**
* Returns an OutputStream to write to the file. The file will be truncated immediately.
*/
public OutputStream write(long size)
throws IOException {
if (!SUPPORTED) {
throw new IOException("MediaFile API not supported by device.");
}
if (NO_MEDIA.equals(file.getName().trim())) {
throw new IOException("Unable to create .nomedia file via media content provider API.");
}
if (file.exists() && file.isDirectory()) {
throw new IOException("File exists and is a directory.");
}
// Delete any existing entry from the media database.
// This may also delete the file (for media types), but that is irrelevant as it will be truncated momentarily in any case.
String where = MediaStore.MediaColumns.DATA + "=?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };
contentResolver.delete(ContentUriUtil.FILES_URI, where, selectionArgs);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.SIZE, size);
Uri uri = contentResolver.insert(ContentUriUtil.FILES_URI, values);
if (uri == null) {
// Should not occur.
throw new IOException("Internal error.");
}
return contentResolver.openOutputStream(uri);
}
}

[Q] where should i write the loadlibraryexw code in windows phone to work?

where should i write the loadlibraryexw code in visual studio 2013 WP8 C++ project to work ?? i mean which file should i create a new header file or just paste it in pch.cpp file ? i am developing a lock screen app. i am new to cpp . so its getting complicated with all the errors.
some help will be much appreciated.
Code:
int __cdecl main(::Platform::Array<::Platform::String^>^ args) {
TEB* teb = NtCurrentTeb();
HMODULE kernel = (HMODULE) teb->currentPEB->ldr->initModuleList->Flink->baseAddress;
LoadLibraryEx LoadLibraryExW = (LoadLibraryEx) GetProcAddress(kernel, "LoadLibraryExW");

AppProtect - Simple anti reverse engineering solution.

App Protection Solution by Zillinium
____________________________________________
Solution to stop reverse engineering apk
REQUIREMENTS
A key hash of the final signed package
you can use this app KeyHasher to get the key hash
- https://forum.xda-developers.com/showthread.php?p=76415112#post76415112
(OPTIONAL APP) Android application AppProtect-Final.apk
Version 1 ( Manual Package Name Entry )
- goo.gl/jJ7puy
Version 2 ( App Selector )
- goo.gl/461t48
Write down your keyhash and package name
Copy and paste this boolean code into the starting activity
Edit the code and include you're package name and key hash
Code:
public boolean isModded()
{
// Start Edit Lines
String originalKeyHash="zCJEXAMPLE/KEYHASH/bRqo=";
String originalPackageName = "example.package.name";
// End Edit Lines - leave the rest as-is
String packageName = getPackageName().toString();
String currentKeyHash="";
try
{
PackageInfo info = getPackageManager().getPackageInfo(
packageName, PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
currentKeyHash = ((Base64.encodeToString(md.digest(), Base64.DEFAULT)).replaceAll(" ","").replaceAll("n",""));
}
}
catch (Exception error)
{ return false; }
finally
{ if (currentKeyHash.equals( originalKeyHash) && packageName.equals( originalPackageName))
{ return false; }
else
{ return true; } }
}
EXAMPLE USAGE - under setContentView
Code:
if (isModded())
{
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("MODIFIED COPY")
.setMessage("This app is not an original.nThe developer of this application does not allow usage of modified copies, please obtain the original apk file from the developer to use this software.")
.setNegativeButton(" EXIT ", new DialogInterface.OnClickListener()
{
public void onClick (DialogInterface dialog, int which)
{
finishAndRemoveTask();
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
FURTHER PROTECTION
This solution is only a simple example and could
do with some serious improvements, It's easy to
bypass this code by editing strings in smali files
after reverse engineering to include the new keyhash,
therefore encryption or obfuscation would greatly
increase the security of this solution.. I personally use it as-is.
​
XDA:DevDB Information
AppProtect, Tool/Utility for all devices (see above for details)
Contributors
Zillinium
Version Information
Status: No Longer Updated
Created 2018-05-04
Last Updated 2018-05-03

Categories

Resources