public static bool IsAppRunning(string appName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query          = string.Format(API_ProcessQuery, connectInfo.IP);
                string downloadString = client.DownloadString(query);

                var processList = JsonUtility.FromJson <ProcessList>(downloadString);
                for (int i = 0; i < processList.Processes.Length; ++i)
                {
                    string processName = processList.Processes[i].ImageName;

                    if (processName.Contains(appName))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        public static bool DeviceLogFile_View(string packageFamilyName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                try
                {
                    // Setup
                    string logFile = Application.temporaryCachePath + @"/deviceLog.txt";

                    // Get the app details...
                    AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
                    if (appDetails == null)
                    {
                        Debug.LogError("Application not found on target device (" + packageFamilyName + ")");
                        return(false);
                    }

                    // Download the file
                    string query = string.Format(kAPI_FileQuery, connectInfo.IP);
                    query += "?knownfolderid=LocalAppData";
                    query += "&filename=UnityPlayer.log";
                    query += "&packagefullname=" + appDetails.PackageFullName;
                    query += "&path=%5C%5CTempState";
                    client.DownloadFile(query, logFile);

                    // Open it up in default text editor
                    System.Diagnostics.Process.Start(logFile);
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.ToString());
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Downloads and launches the Log file for the target application on the target device.
        /// </summary>
        /// <param name="packageFamilyName"></param>
        /// <param name="targetDevice"></param>
        /// <returns>True, if download success.</returns>
        public static bool DeviceLogFile_View(string packageFamilyName, ConnectInfo targetDevice)
        {
            EditorUtility.DisplayProgressBar("Download Log", "Downloading Log File for " + packageFamilyName, 0.25f);

            AppDetails appDetails = QueryAppDetails(packageFamilyName, targetDevice);

            if (appDetails == null)
            {
                Debug.LogWarningFormat("{0} not installed on target device", packageFamilyName);
                EditorUtility.ClearProgressBar();
                return(false);
            }

            string logFile = string.Format("{0}/{1}_{2}{3}{4}{5}{6}{7}_deviceLog.txt",
                                           Application.temporaryCachePath,
                                           targetDevice.MachineName,
                                           DateTime.Now.Year,
                                           DateTime.Now.Month,
                                           DateTime.Now.Day,
                                           DateTime.Now.Hour,
                                           DateTime.Now.Minute,
                                           DateTime.Now.Second);

            string response = WebRequestGet(string.Format(API_FileQuery, FinalizeUrl(targetDevice.IP), appDetails.PackageFullName), GetBasicAuthHeader(targetDevice, true));
            bool   success  = !string.IsNullOrEmpty(response);

            if (success)
            {
                File.WriteAllText(logFile, response);
                Process.Start(logFile);
            }

            EditorUtility.ClearProgressBar();

            return(success);
        }
        /// <summary>
        /// Kills the target application on the target device.
        /// </summary>
        /// <param name="packageFamilyName"></param>
        /// <param name="targetDevice"></param>
        /// <param name="showDialog"></param>
        /// <returns>true, if application was successfully stopped.</returns>
        public static bool KillApp(string packageFamilyName, ConnectInfo targetDevice, bool showDialog = true)
        {
            AppDetails appDetails = QueryAppDetails(packageFamilyName, targetDevice);

            if (appDetails == null)
            {
                Debug.LogError("Application not found");
                return(false);
            }

            string query = string.Format("{0}?package={1}",
                                         string.Format(API_AppQuery, FinalizeUrl(targetDevice.IP)),
                                         WWW.EscapeURL(EncodeTo64(appDetails.PackageFullName)));

            bool        success       = WebRequestDelete(query, GetBasicAuthHeader(targetDevice), showDialog);
            MachineName targetMachine = GetMachineName(targetDevice);

            if (success)
            {
                Debug.LogFormat("Successfully stopped {0} on {1}.", packageFamilyName, targetMachine.ComputerName);
            }

            return(success);
        }
        public static bool InstallApp(string appFullPath, ConnectInfo connectInfo, bool waitForDone = true)
        {
            try
            {
                // Calc the cert and dep paths
                string fileName     = Path.GetFileName(appFullPath);
                string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
                string certName     = Path.GetFileName(certFullPath);
                string depPath      = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\";

                // Post it using the REST API
                WWWForm form = new WWWForm();

                // APPX file
                FileStream   stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader reader = new BinaryReader(stream);
                form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
                stream.Close();

                // CERT file
                stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                reader = new BinaryReader(stream);
                form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
                stream.Close();

                // Dependencies
                FileInfo[] depFiles = (new DirectoryInfo(depPath)).GetFiles();
                foreach (FileInfo dep in depFiles)
                {
                    stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    reader = new BinaryReader(stream);
                    string depFilename = Path.GetFileName(dep.FullName);
                    form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
                    stream.Close();
                }

                // Credentials
                Dictionary <string, string> headers = form.headers;
                headers["Authorization"] = "Basic " + EncodeTo64(connectInfo.User + ":" + connectInfo.Password);

                // Unity places an extra quote in the content-type boundary parameter that the device portal doesn't care for, remove it
                if (headers.ContainsKey("Content-Type"))
                {
                    headers["Content-Type"] = headers["Content-Type"].Replace("\"", "");
                }

                // Query
                string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
                query += "?package=" + WWW.EscapeURL(fileName);
                WWW      www            = new WWW(query, form.data, headers);
                DateTime queryStartTime = DateTime.Now;
                while (!www.isDone &&
                       ((DateTime.Now - queryStartTime).TotalSeconds < TimeOut))
                {
                    System.Threading.Thread.Sleep(10);
                }

                // Give it a short time before checking
                System.Threading.Thread.Sleep(250);

                // Report
                if (www.isDone)
                {
                    Debug.Log(JsonUtility.FromJson <Response>(www.text).Reason);
                }

                // Wait for done (if requested)
                DateTime waitStartTime = DateTime.Now;
                while (waitForDone &&
                       ((DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime))
                {
                    AppInstallStatus status = GetInstallStatus(connectInfo);
                    if (status == AppInstallStatus.InstallSuccess)
                    {
                        Debug.Log("Install Successful!");
                        break;
                    }
                    else if (status == AppInstallStatus.InstallFail)
                    {
                        Debug.LogError("Install Failed!");
                        break;
                    }

                    // Wait a bit and we'll ask again
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.ToString());
                return(false);
            }

            return(true);
        }
 // Functions
 public static bool IsAppInstalled(string baseAppName, ConnectInfo connectInfo)
 {
     // Look at the device for a matching app name (if not there, then not installed)
     return(QueryAppDetails(baseAppName, connectInfo) != null);
 }
        /// <summary>
        /// Installs the target application on the target device.
        /// </summary>
        /// <param name="appFullPath"></param>
        /// <param name="targetDevice"></param>
        /// <param name="waitForDone">Should the thread wait until installation is complete?</param>
        /// <returns>True, if Installation was a success.</returns>
        public static bool InstallApp(string appFullPath, ConnectInfo targetDevice, bool waitForDone = true)
        {
            bool success = false;

            try
            {
                // Calculate the cert and dependency paths
                string fileName     = Path.GetFileName(appFullPath);
                string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
                string certName     = Path.GetFileName(certFullPath);
                string depPath      = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\";

                // Post it using the REST API
                var form = new WWWForm();

                // APPX file
                Debug.Assert(appFullPath != null);
                using (var stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
                    }
                }

                // CERT file
                Debug.Assert(certFullPath != null);
                using (var stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
                    }
                }

                // Dependencies
                FileInfo[] depFiles = new DirectoryInfo(depPath).GetFiles();
                foreach (FileInfo dep in depFiles)
                {
                    using (var stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var reader = new BinaryReader(stream))
                        {
                            string depFilename = Path.GetFileName(dep.FullName);
                            form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
                        }
                    }
                }

                // Query
                string query = string.Format(API_InstallQuery, FinalizeUrl(targetDevice.IP));
                query += "?package=" + WWW.EscapeURL(fileName);

                var response = WebRequestPost(query, form, GetBasicAuthHeader(targetDevice));

                if (string.IsNullOrEmpty(response))
                {
                    Debug.LogErrorFormat("Failed to install {0} on {1}.\n", fileName, targetDevice.MachineName);
                    return(false);
                }

                // Wait for done (if requested)
                DateTime waitStartTime = DateTime.Now;
                while (waitForDone && (DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime)
                {
                    EditorUtility.DisplayProgressBar("Connecting to Device Portal", "Installing...", (float)((DateTime.Now - waitStartTime).TotalSeconds / MaxWaitTime));
                    AppInstallStatus status = GetInstallStatus(targetDevice);

                    if (status == AppInstallStatus.InstallSuccess)
                    {
                        Debug.LogFormat("Successfully installed {0} on {1}.", fileName, targetDevice.MachineName);
                        success = true;
                        break;
                    }

                    if (status == AppInstallStatus.InstallFail)
                    {
                        Debug.LogErrorFormat("Failed to install {0} on {1}.\n", fileName, targetDevice.MachineName);
                        break;
                    }

                    // Wait a bit and we'll ask again
                    Thread.Sleep(1000);
                }

                EditorUtility.ClearProgressBar();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                success = false;
            }

            return(success);
        }
 /// <summary>
 /// Determines if the target application is currently running on the target device.
 /// </summary>
 /// <param name="packageFamilyName"></param>
 /// <param name="targetDevice"></param>
 /// <returns>True, if application is currently installed on device.</returns>
 public static bool IsAppInstalled(string packageFamilyName, ConnectInfo targetDevice)
 {
     return(QueryAppDetails(packageFamilyName, targetDevice) != null);
 }
 /// <summary>
 /// Opens the Device Portal for the target device.
 /// </summary>
 /// <param name="targetDevice"></param>
 public static void OpenWebPortal(ConnectInfo targetDevice)
 {
     //TODO: Figure out how to pass username and password to browser?
     Process.Start(FinalizeUrl(targetDevice.IP));
 }
 public DevicePortalConnections(ConnectInfo connectInfo)
 {
     Connections.Add(connectInfo);
 }