Exemple #1
0
        public void Download(OnDownloadProgressHandler ProgressEvent, OnDownloadFinishHandler FinishEvent)
        {
            OnDownloadProgress = ProgressEvent;
            OnDownloadFinish   = FinishEvent;

            // just Delete a File
            if (this.PatchAction == EPatchAction.DataDelete || this.PatchAction == EPatchAction.GrfDelete)
            {
                if (OnDownloadFinish != null)
                {
                    OnDownloadFinish(this, false);
                }
                return;
            }

            FilePath = Path.GetTempFileName();
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }


            TimeoutWebClient client = new TimeoutWebClient();

            client.BaseAddress = DownloadUrl;

            client.DownloadFileCompleted   += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileAsync(new Uri(DownloadUrl), FilePath, client);
        }
Exemple #2
0
    public bool Download(string url, string filename)
    {
        bool flag = false;

        try
        {
            if (!Directory.Exists(Path.GetDirectoryName(filename)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
            }

            using (var client = new TimeoutWebClient())
            {
                ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;

                //authorization needed to acces github
                if (Path.GetExtension(filename).Contains("png"))
                {
                    //client.Headers.Add(HttpRequestHeader.Authorization, string.Concat("token ", RepoData.GetToken()));
                }
                client.DownloadFile(new Uri(url), filename + ".tmp");
            }
            flag = true;
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
            File.Move(filename + ".tmp", filename);
        }
        catch (Exception)
        {
            flag = false;
        }
        return(flag);
    }
Exemple #3
0
        internal async Task DownloadFileAsync(DownloadFile file)
        {
            string?directoryName = Path.GetDirectoryName(file.Path);

            if (!string.IsNullOrEmpty(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            using (var wc = new TimeoutWebClient())
            {
                long lastBytes = 0;

                wc.DownloadProgressChanged += (s, e) =>
                {
                    lock (locker)
                    {
                        var progressedBytes = e.BytesReceived - lastBytes;
                        if (progressedBytes < 0)
                        {
                            return;
                        }

                        lastBytes = e.BytesReceived;

                        var progress = new FileDownloadProgress(
                            file, e.TotalBytesToReceive, progressedBytes, e.BytesReceived, e.ProgressPercentage);
                        FileDownloadProgressChanged?.Invoke(this, progress);
                    }
                };
                await wc.DownloadFileTaskAsync(file.Url, file.Path)
                .ConfigureAwait(false);
            }
        }
Exemple #4
0
        /// <summary>
        /// Create a WebClient with some CKAN-sepcific adjustments, like a user agent string.
        /// </summary>
        /// <param name="timeout">Timeout for the request in milliseconds, defaulting to 100 000 (=100 seconds)</param>
        /// <returns>A custom WebClient</returns>
        private static WebClient MakeDefaultHttpClient(int timeout = 100000)
        {
            var client = new TimeoutWebClient(timeout);

            client.Headers.Add("User-Agent", UserAgentString);
            return(client);
        }
Exemple #5
0
        public void DownloadStatus()
        {
            // Load info from CP xml export
            TimeoutWebClient web = new TimeoutWebClient();

            web.TimeOut = 5000;

            try {
                string statusData = web.DownloadString(StatusUrl);
                // Load xml data into our class
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(statusData);
                // doc -> xml -> ServerStatus -> Group -> Server
                XmlNode node = doc.FirstChild.NextSibling.FirstChild.FirstChild;

                string loginServer   = node.Attributes["loginServer"].Value.Trim();
                string charServer    = node.Attributes["charServer"].Value.Trim();
                string mapServer     = node.Attributes["mapServer"].Value.Trim();
                string woeActive     = node.Attributes["woeActive"].Value.Trim();
                string playersOnline = node.Attributes["playersOnline"].Value.Trim();

                LoginServer = (loginServer == "1");
                CharServer  = (charServer == "1");
                MapServer   = (mapServer == "1");
                WoeActive   = (woeActive == "1");
                PlayerCount = int.Parse(playersOnline);
            } catch {
                // Failed, assume servers are donw
                Reset();
            }
        }
Exemple #6
0
        public ActionResult EvalJsonAPI(string userToken, string windowType = DefaultEvalWindow, int maxNumPolicies = 5)
        {
            if (userToken != ConfigurationManager.AppSettings[ApplicationMetadataStore.AKWebServiceToken])
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "A valid token must be specified."));
            }

            string trainerStatus = string.Empty;

            try
            {
                using (var wc = new TimeoutWebClient())
                {
                    var    trainerStatusJson  = wc.DownloadString(ConfigurationManager.AppSettings[ApplicationMetadataStore.AKTrainerURL] + "/status");
                    JToken jtoken             = JObject.Parse(trainerStatusJson);
                    int    numLearnedExamples = (int)jtoken.SelectToken("Stage2_Learn_Total");
                    trainerStatus = $"Trainer OK. Total learned examples: {numLearnedExamples}";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Unable to connect to the remote server"))
                {
                    trainerStatus = "Please wait as trainer has not started yet";
                }
                else
                {
                    new TelemetryClient().TrackException(ex);
                    trainerStatus = "Error getting trainer status, check Application Insights for more details.";
                }
            }

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

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

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

            return true;
        }
Exemple #8
0
        public static AppInstallStatus GetInstallStatus(ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query      = string.Format(API_InstallStatusQuery, connectInfo.IP);
                string statusJSON = client.DownloadString(query);
                var    status     = JsonUtility.FromJson <InstallStatus>(statusJSON);

                if (status == null)
                {
                    return(AppInstallStatus.Installing);
                }

                Debug.LogFormat("Install Status: {0}|{1}|{2}|{3}", status.Code, status.CodeText, status.Reason, status.Success);

                if (status.Success == false)
                {
                    Debug.LogError(status.Reason + "(" + status.CodeText + ")");
                    return(AppInstallStatus.InstallFail);
                }

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

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

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

            return(true);
        }
Exemple #10
0
        /// <summary>
        /// 通过ticket换取二维码
        /// </summary>
        /// <param name="ticket"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static MediaGetRes Showqrcode(string ticket, string filepath)
        {
            string filename = null;
            string url      = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";

            url += ticket;

            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.DownloadFile(url, filepath);

            string disposition = wc.ResponseHeaders["Content-disposition"];

            if (string.IsNullOrEmpty(disposition))
            {
                string json = System.IO.File.ReadAllText(filepath);
                return(JsonConvert.DeserializeObject <MediaGetRes>(json));
            }
            else
            {
                filename = StringHelper.SubString(disposition, "filename=\"", "\"");
            }

            return(new MediaGetRes()
            {
                errcode = "0", filename = filename
            });
        }
Exemple #11
0
        private void DownloadOneTitle(string titleId, string version, int curr, int total)
        {
            titleId = titleId.ToUpper();

            mLastDownSize = 0;
            string outputDir = Path.Combine(Environment.CurrentDirectory, "NusData");

            WebClient nusWC = new TimeoutWebClient(60 * 1000);

            // Create\Configure NusClient
            mNusClient = new libWiiSharp.WiiuNusClient(titleId, version, outputDir);
            mNusClient.ConfigureNusClient(nusWC);
            mNusClient.UseLocalFiles = true;

            mNusClient.SetToWiiServer();

            // Events
            mNusClient.Debug         += nusClient_Debug;
            mNusClient.CurrProgress  += NusClient_CurrProgress;
            mNusClient.TotalProgress += NusClient_TotalProgress;

            mNusClient.cancelDownload = false;

            ShowLog("");
            ShowLog(string.Format("  Download [{0}/{1}] - TitleId:{2} Start...", curr + 1, total, titleId));
            mNusClient.downloadTitle();
            ShowLog(string.Format("  Download [{0}/{1}] - TitleId:{2} Finish...", curr + 1, total, titleId));
        }
        public bool RetrieveCustomLeaderboardList()
        {
            try
            {
                // The spawnset list must be retrieved first.
                if (Spawnsets.Count == 0)
                {
                    App.Instance.ShowError("Could not retrieve custom leaderboard list", "The internal spawnset list is empty. This must be initialized before retrieving the custom leaderboard list.");
                    return(false);
                }

                string downloadString = string.Empty;
                using (TimeoutWebClient client = new TimeoutWebClient(Timeout))
                    downloadString = client.DownloadString(UrlUtils.ApiGetCustomLeaderboards);
                CustomLeaderboards = JsonConvert.DeserializeObject <List <CustomLeaderboardBase> >(downloadString);

                foreach (SpawnsetListEntry entry in Spawnsets)
                {
                    entry.HasLeaderboard = CustomLeaderboards.Any(l => l.SpawnsetFileName == entry.SpawnsetFile.FileName);
                }

                return(true);
            }
            catch (WebException ex)
            {
                App.Instance.ShowError("Error retrieving custom leaderboard list", $"Could not connect to '{UrlUtils.ApiGetCustomLeaderboards}'.", ex);
                return(false);
            }
            catch (Exception ex)
            {
                App.Instance.ShowError("Unexpected error", "An unexpected error occurred.", ex);
                return(false);
            }
        }
Exemple #13
0
        /// <summary>
        /// 获取临时素材
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="media_id"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static MediaGetRes Media_Get(string access_token, string media_id, string filepath)
        {
            string filename = null;

            string url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";

            url = string.Format(url, access_token, media_id);

            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.DownloadFile(url, filepath);

            string disposition = wc.ResponseHeaders["Content-disposition"];

            if (string.IsNullOrEmpty(disposition))
            {
                string json = System.IO.File.ReadAllText(filepath);
                return(JsonConvert.DeserializeObject <MediaGetRes>(json));
            }
            else
            {
                filename = StringHelper.SubString(disposition, "filename=\"", "\"");
            }

            return(new MediaGetRes()
            {
                errcode = "0", filename = filename
            });
        }
        public Spawnset DownloadSpawnset(string fileName)
        {
            string url = UrlUtils.ApiGetSpawnset(fileName);

            try
            {
                Spawnset spawnset;

                using (TimeoutWebClient client = new TimeoutWebClient(Timeout))
                    using (Stream stream = new MemoryStream(client.DownloadData(url)))
                        if (!Spawnset.TryParse(stream, out spawnset))
                        {
                            App.Instance.ShowError("Error parsing file", "Could not parse file.");
                        }

                return(spawnset);
            }
            catch (WebException ex)
            {
                App.Instance.ShowError("Error downloading file", $"Could not connect to '{url}'.", ex);

                return(null);
            }
            catch (Exception ex)
            {
                App.Instance.ShowError("Unexpected error", "An unexpected error occurred.", ex);

                return(null);
            }
        }
Exemple #15
0
    public bool Download(string url, string filename)
    {
        bool flag = false;

        try
        {
            if (!Directory.Exists(Path.GetDirectoryName(filename)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
            }
            if (File.Exists(filename + ".tmp"))
            {
                File.Delete(filename + ".tmp");
            }
            using (var client = new TimeoutWebClient())
            {
                ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;

                if (Path.GetExtension(filename).Contains("png"))
                {
                    client.Timeout = 6500;
                }
                if (Path.GetExtension(filename).Contains("jpg"))
                {
                    client.Timeout = 3500;
                }
                if (Path.GetExtension(filename).Contains("cdb"))
                {
                    client.Timeout = 30000;
                }
                if (Path.GetExtension(filename).Contains("conf"))
                {
                    client.Timeout = 3000;
                }
                client.DownloadFile(new Uri(url), filename + ".tmp");
            }
            flag = true;
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
            File.Move(filename + ".tmp", filename);
        }
        catch (Exception)
        {
            if (File.Exists(filename + ".tmp"))
            {
                File.Delete(filename + ".tmp");
            }
            flag = false;
        }
        return(flag);
    }
Exemple #16
0
        /// <summary>
        /// 获取自定义菜单配置接口
        /// </summary>
        /// <param name="access_token"></param>
        /// <returns></returns>
        public static string Get_current_selfmenu_info(string access_token)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=";

            url += access_token;

            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.Encoding = Encoding.UTF8;
            var json = wc.GetLoadString(url, string.Empty);

            return(json);
        }
        private bool DownloadFile(string Url, string SavePath)
        {
            try {
                TimeoutWebClient client = new TimeoutWebClient();
                client.TimeOut = 5000;
                client.DownloadFile(Url, SavePath);

                return(true);
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e);
                return(false);
            }
        }
Exemple #18
0
        /// <summary>
        /// Get请求并反馈解码后的Json对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T GetObject <T>(string url, string param = "")
            where T : BaseRes
        {
            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.Encoding = Encoding.UTF8;
            var json = wc.GetLoadString(url, param);
            var rel  = JsonConvert.DeserializeObject <T>(json);

            if (string.IsNullOrEmpty(rel.errcode))
            {
                rel.errcode = "0";
            }
            return(rel);
        }
Exemple #19
0
        /// <summary>
        /// Post请求并反馈解码后的Json对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="post"></param>
        /// <returns></returns>
        public static T PostObject <T>(string url, string post)
            where T : BaseRes
        {
            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.Encoding = Encoding.UTF8;
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var json = wc.PostLoadString(url, post);
            var rel  = JsonConvert.DeserializeObject <T>(json);

            if (string.IsNullOrEmpty(rel.errcode))
            {
                rel.errcode = "0";
            }
            return(rel);
        }
        private async Task UpdatePlayerbase()
        {
            try
            {
                var webClient = new TimeoutWebClient {
                    Timeout = 120
                };
                var response = webClient.DownloadString(PLAYERBASE_URL).Trim();

                await _log.LogMessage($"Got the following response when updating playerbase: `{response}`",
                                      color : LOG_COLOR);
            }
            catch (Exception e)
            {
                await _log.LogMessage($"Failed to update playbase!\n{e}", false, color : LOG_COLOR);
            }
        }
        public bool RetrieveSpawnsetList()
        {
            try
            {
                Spawnsets.Clear();
                Authors.Clear();

                string downloadString = string.Empty;
                using (TimeoutWebClient client = new TimeoutWebClient(Timeout))
                    downloadString = client.DownloadString(UrlUtils.ApiGetSpawnsets);
                List <SpawnsetFile> spawnsetFiles = JsonConvert.DeserializeObject <List <SpawnsetFile> >(downloadString);

                Authors.Add(new AuthorListEntry(SpawnsetListHandler.AllAuthors, spawnsetFiles.Count));
                foreach (SpawnsetFile sf in spawnsetFiles)
                {
                    AuthorListEntry author = new AuthorListEntry(sf.Author, spawnsetFiles.Where(s => s.Author == sf.Author).Count());
                    if (!Authors.Any(a => a.Name == author.Name))
                    {
                        Authors.Add(author);
                    }
                }

                foreach (SpawnsetFile spawnsetFile in spawnsetFiles)
                {
                    Spawnsets.Add(new SpawnsetListEntry {
                        SpawnsetFile = spawnsetFile
                    });
                }

                return(true);
            }
            catch (WebException ex)
            {
                App.Instance.ShowError("Error retrieving spawnset list", $"Could not connect to '{UrlUtils.ApiGetSpawnsets}'.", ex);
                return(false);
            }
            catch (Exception ex)
            {
                App.Instance.ShowError("Unexpected error", "An unexpected error occurred.", ex);
                return(false);
            }
        }
Exemple #22
0
        private void UpdateBankCodes()
        {
            if (this.ListAge < this.options.MaxAge)
            {
                return;
            }

            // Download list from ČNB site
            string csv;

            try {
                using (var wc = new TimeoutWebClient(this.options.Timeout)) {
                    csv = wc.DownloadString(this.options.ListUrl);
                }
            } catch (WebException wex) when(wex.Status == WebExceptionStatus.Timeout && !this.options.ThrowExceptionOnTimeout)
            {
                return;
            } catch (WebException) when(!this.options.ThrowExceptionOnFail)
            {
                return;
            }

            // Parse the data
            var lines = csv.Split('\r', '\n');
            var list  = new List <string>();

            foreach (var item in lines)
            {
                if (string.IsNullOrEmpty(item))
                {
                    continue;
                }
                if (Regex.IsMatch(item, @"^\d{4};"))
                {
                    list.Add(item.Substring(0, 4));
                }
            }
            this.bankCodes = list;

            // Set last update time to now
            this.lastUpdate = DateTime.Now;
        }
        public static AppDetails QueryAppDetails(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query       = string.Format(kAPI_PackagesQuery, connectInfo.IP);
                string appListJSON = client.DownloadString(query);

                AppList appList = JsonUtility.FromJson <AppList>(appListJSON);
                for (int i = 0; i < appList.InstalledPackages.Length; ++i)
                {
                    string appName = appList.InstalledPackages[i].PackageFullName;
                    if (appName.Contains(baseAppName))
                    {
                        return(appList.InstalledPackages[i]);
                    }
                }
            }
            return(null);
        }
        public static bool IsAppRunning(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query        = string.Format(kAPI_ProcessQuery, connectInfo.IP);
                string procListJSON = client.DownloadString(query);

                ProcessList procList = JsonUtility.FromJson <ProcessList>(procListJSON);
                for (int i = 0; i < procList.Processes.Length; ++i)
                {
                    string procName = procList.Processes[i].ImageName;
                    if (procName.Contains(baseAppName))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        private bool SendMessage(string message, int timeout)
        {
            using (var client = new TimeoutWebClient(timeout))
            {
                client.Headers.Add("X-ApiKey", _apiKey);
                client.Headers.Add("content-type", "application/json; charset=utf-8");
                client.Encoding = System.Text.Encoding.UTF8;

                try
                {
                    client.UploadString(RaygunSettings.Settings.ApiEndpoint, message);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Error Logging Exception to Raygun.io {0}", ex.Message));
                    return(false);
                }
            }
            return(true);
        }
Exemple #26
0
        private static async Task <bool> CheckForInternetConnection()
        {
            bool haveInternet;

            try
            {
                using (var client = new TimeoutWebClient(1000))
                {
                    using (var stream = await client.OpenReadTaskAsync(DeployProperties.MonoUrl))
                    {
                        haveInternet = true;
                    }
                }
            }
            catch
            {
                haveInternet = false;
            }

            return(haveInternet);
        }
Exemple #27
0
        public void upload(String path)
        {
            TimeoutWebClient client = new TimeoutWebClient();

            txtbox.AppendText("\n\n" + MainWindow.globalLanguage.bPLists.code.uploadingBPList);
            Uri uri = new Uri("http://" + MainWindow.config.IP + ":50000/host/beatsaber/upload?overwrite");

            try
            {
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate
                {
                    client.UploadFileCompleted += new UploadFileCompletedEventHandler(finished_upload);
                    client.UploadFileAsync(uri, path);
                }));
            }
            catch
            {
                txtbox.AppendText(MainWindow.globalLanguage.global.BMBF100);
                Running = false;
            }
        }
            /// <summary>
            /// returns whether if device is connecte to internet
            /// </summary>
            /// <returns>
            /// true if device is connected to internet,
            /// else false
            /// </returns>
            public static bool IsConnectedToInternet()
            {
                bool connectedToInternet;

                try
                {
                    // init a connection and send request to a stable web host
                    using (TimeoutWebClient timeoutWebClient = new TimeoutWebClient(CONNECTION_TIMEOUT_MILLIS))
                        using (timeoutWebClient.OpenRead(STABLE_WEB_HOST_URL))
                        {
                            // connection succeeded
                            connectedToInternet = true;
                        }
                }
                catch // connection failed
                {
                    connectedToInternet = false;
                }

                return(connectedToInternet);
            }
Exemple #29
0
        // 素材管理接口
        #region 新增临时素材
        /// <summary>
        /// 新增临时素材
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="type"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static MediaUploadRes Media_Upload(string access_token, EnumUploadType type, string file)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";

            url = string.Format(url, access_token, type);

            TimeoutWebClient wc = ThreadWebClientFactory.GetWebClient();

            wc.Encoding = Encoding.UTF8;
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var    bytes = wc.UploadFile(url, "POST", file);
            string json  = Encoding.UTF8.GetString(bytes);

            MediaUploadRes res = JsonConvert.DeserializeObject <MediaUploadRes>(json);

            if (string.IsNullOrEmpty(res.errcode))
            {
                res.errcode = "0";
            }
            return(res);
        }
Exemple #30
0
        public static AppDetails QueryAppDetails(string packageFamilyName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query       = string.Format(API_PackagesQuery, connectInfo.IP);
                string appListJSON = client.DownloadString(query);

                var appList = JsonUtility.FromJson <AppList>(appListJSON);
                for (int i = 0; i < appList.InstalledPackages.Length; ++i)
                {
                    string thisAppName = appList.InstalledPackages[i].PackageFamilyName;
                    if (thisAppName.Equals(packageFamilyName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(appList.InstalledPackages[i]);
                    }
                }
            }

            return(null);
        }
Exemple #31
0
        private void ExportOneTitle(string titleId, string version, int curr, int total)
        {
            titleId = titleId.ToUpper();

            string outputDir = Path.Combine(Environment.CurrentDirectory, "NusExport");

            WebClient nusWC = new TimeoutWebClient(60 * 1000);

            // Create\Configure NusClient
            mNusClient = new libWiiSharp.WiiuNusClient(titleId, version, outputDir);
            mNusClient.ConfigureNusClient(nusWC);
            mNusClient.UseLocalFiles = true;

            mNusClient.SetToWiiServer();

            // Events
            mNusClient.Debug += nusClient_Debug;

            ShowLog("");
            ShowLog(string.Format("  Export [{0}/{1}] - TitleId:{2} Start...", curr + 1, total, titleId));
            mNusClient.exportTitle();
            ShowLog(string.Format("  Export [{0}/{1}] - TitleId:{2} Finish...", curr + 1, total, titleId));
        }
        public static AppInstallStatus GetInstallStatus(ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_InstallStatusQuery, connectInfo.IP);
                string statusJSON = client.DownloadString(query);
                InstallStatus status = JsonUtility.FromJson<InstallStatus>(statusJSON);

                if (status == null)
                {
                    return AppInstallStatus.Installing;
                }
                else if (status.Success == false)
                {
                    Debug.LogError(status.Reason + "(" + status.CodeText + ")");
                    return AppInstallStatus.InstallFail;
                }
                return AppInstallStatus.InstallSuccess;
            }
        }
        private static async Task<bool> CheckForInternetConnection()
        {
            bool haveInternet;
            try
            {
                using (var client = new TimeoutWebClient(1000))
                {
                    using (var stream = await client.OpenReadTaskAsync(DeployProperties.MonoUrl))
                    {
                        haveInternet = true;
                    }
                }
            }
            catch
            {
                haveInternet = false;
            }

            return haveInternet;
        }
        public static AppDetails QueryAppDetails(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_PackagesQuery, connectInfo.IP);
                string appListJSON = client.DownloadString(query);

                AppList appList = JsonUtility.FromJson<AppList>(appListJSON);
                for (int i = 0; i < appList.InstalledPackages.Length; ++i)
                {
                    string appName = appList.InstalledPackages[i].Name;
                    if (appName.Contains(baseAppName))
                    {
                        return appList.InstalledPackages[i];
                    }
                }
            }
            return null;
        }
        public static bool IsAppRunning(string baseAppName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
                string query = string.Format(kAPI_ProcessQuery, connectInfo.IP);
                string procListJSON = client.DownloadString(query);

                ProcessList procList = JsonUtility.FromJson<ProcessList>(procListJSON);
                for (int i = 0; i < procList.Processes.Length; ++i)
                {
                    string procName = procList.Processes[i].ImageName;
                    if (procName.Contains(baseAppName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        private bool SendMessage(string message, int timeout)
        {
            using (var client = new TimeoutWebClient(timeout))
              {
            client.Headers.Add("X-ApiKey", _apiKey);
            client.Headers.Add("content-type", "application/json; charset=utf-8");
            client.Encoding = System.Text.Encoding.UTF8;

            try
            {
              client.UploadString(RaygunSettings.Settings.ApiEndpoint, message);
            }
            catch (Exception ex)
            {
              System.Diagnostics.Debug.WriteLine(string.Format("Error Logging Exception to Raygun.io {0}", ex.Message));
              return false;
            }
              }
              return true;
        }