Exemple #1
0
        public void CancelReservation()
        {
            if (mPositionID == 0)
            {
                return;
            }

            try
            {
                mProgressBar.Visibility = ViewStates.Visible;

                Uri url = new Uri(ConfigManager.WebService + "/" + "cancelNavigation.php?id=" + mPositionID.ToString());
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadDataAsync(url);
                webClient.DownloadDataCompleted += (object s, System.Net.DownloadDataCompletedEventArgs e) =>
                {
                    RunOnUiThread(() => { mProgressBar.Visibility = ViewStates.Invisible; });
                    string          json = Encoding.UTF8.GetString(e.Result);
                    OperationResult op   = JsonConvert.DeserializeObject <OperationResult>(json);

                    // Le aviso a los Raspis que ya no tienen que monitorearme
                    Kill();

                    // Elimino las posiciones de este Cliente
                    ClearUserPositions();

                    // Si falla no me interesa mostrarselo al usuario, entonces redirecciono de una
                    Managment.ActivityManager.TakeMeTo(this, typeof(MainActivity), true);
                };
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
Exemple #2
0
        public void SearchParkinglots()
        {
            try
            {
                string vehicleTypeID = fm.GetValue("vt_id");
                string lat           = ConfigManager.DefaultLatMap.ToString();
                string lng           = ConfigManager.DefaultLongMap.ToString();
                string range         = mProfile.range.ToString();
                string price         = mProfile.maxPrice.ToString();
                string is24          = mProfile.is24.ToString();
                string isCovered     = mProfile.isCovered.ToString();

                string urlRef = "vt_id=" + vehicleTypeID + "&" +
                                "lat=" + lat + "&" +
                                "lng=" + lng + "&" +
                                "range=" + range + "&" +
                                "price=" + price + "&" +
                                "is24=" + is24 + "&" +
                                "isCovered=" + isCovered;


                Uri url = new Uri(ConfigManager.WebService + "/" + "searchParkinglotParam.php?" + urlRef);

                mProgressBar.Visibility = ViewStates.Visible;
                mClient.DownloadDataAsync(url);
                mClient.DownloadDataCompleted += MClient_DownloadDataCompleted;
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
Exemple #3
0
        public void Kill()
        {
            if (mMacAddress == string.Empty)
            {
                return;
            }

            try
            {
                string urlRef = "kill.php" + "?" + "mac=" + mMacAddress;
                Uri    url    = new Uri(ConfigManager.WebService + "/" + urlRef);
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadDataAsync(url);
                webClient.DownloadDataCompleted += (object s, System.Net.DownloadDataCompletedEventArgs e) =>
                {
                    try
                    {
                        string          json = Encoding.UTF8.GetString(e.Result);
                        OperationResult op   = JsonConvert.DeserializeObject <OperationResult>(json);
                        if (op.error)
                        {
                            Console.WriteLine("** No fue posible realizar Kill **");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("** No fue posible realizar Kill **");
                    }
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("** Error al intentar cancelar el monitoreo **");
            }
        }
Exemple #4
0
        public static Task <byte[]> GetTaskAysnc(string url)
        {
            //定义一个任务包装器
            TaskCompletionSource <byte[]> tcs = new TaskCompletionSource <byte[]>();

            System.Net.WebClient client = new System.Net.WebClient();

            //  client.DownloadDataCompleted += Client_DownloadDataCompleted;
            client.DownloadDataCompleted += (sender, e) =>
            {
                try
                {
                    tcs.TrySetResult(e.Result);  //如果下载完成,则将当前的Byte[]格式给Task包装器
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            };

            //从指定的URI中将资源作为Byte数组下载,封装异步操作
            client.DownloadDataAsync(new Uri(url));

            return(tcs.Task);
        }
Exemple #5
0
        /// <summary>
        /// 下载版本文档,并判断是否更新
        /// </summary>
        /// <param name="shouldShowPrompt"></param>
        public static void CheckUpdateStatus(bool shouldShowPrompt)
        {
            System.Threading.ThreadPool.QueueUserWorkItem((s) =>
            {
                string url = Constants.RemoteUrl_xml;
                var client = new System.Net.WebClient();
                client.DownloadDataCompleted += (x, y) =>
                {
                    try
                    {
                        MemoryStream stream           = new MemoryStream(y.Result);
                        XDocument xDoc                = XDocument.Load(stream);
                        UpdateInfo updateInfo         = new UpdateInfo();
                        XElement root                 = xDoc.Element("UpdateInfo");
                        updateInfo.AppName            = root.Element("AppName").Value;
                        updateInfo.AppVersion         = root.Element("AppVersion") == null || string.IsNullOrEmpty(root.Element("AppVersion").Value) ? null : new Version(root.Element("AppVersion").Value);
                        updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(root.Element("RequiredMinVersion").Value) ? null : new Version(root.Element("RequiredMinVersion").Value);
                        updateInfo.Desc               = root.Element("Desc").Value;
                        updateInfo.MD5                = Guid.NewGuid();

                        stream.Close();
                        Updater.Instance.StartUpdate(updateInfo, shouldShowPrompt);
                    }
                    catch
                    {
                    }
                };
                client.DownloadDataAsync(new Uri(url));
            });
        }
Exemple #6
0
 public void ClearUserPositions()
 {
     try
     {
         string urlRef = "clearClientPosition.php" + "?" + "id=" + mNavData[2].ToString();
         Uri    url    = new Uri(ConfigManager.WebService + "/" + urlRef);
         System.Net.WebClient webClient = new System.Net.WebClient();
         webClient.DownloadDataAsync(url);
         webClient.DownloadDataCompleted += (object s, System.Net.DownloadDataCompletedEventArgs e) =>
         {
             try
             {
                 string          json = Encoding.UTF8.GetString(e.Result);
                 OperationResult op   = JsonConvert.DeserializeObject <OperationResult>(json);
                 if (op.error)
                 {
                     Console.WriteLine("** Error al intentar limpiar el historial de posiciones **");
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine("** Error al intentar limpiar el historial de posiciones **");
             }
         };
     }
     catch (Exception ex)
     {
         Console.WriteLine("** Error al intentar limpiar el historial de posiciones **");
     }
 }
        public static void CheckUpdateStatus()
        {
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            System.Threading.ThreadPool.QueueUserWorkItem((s) =>
            {
                string strRemoteUrl = ConfigurationManager.AppSettings["UpdateLink"];
                string url          = strRemoteUrl + Updater.Instance.CallExeName + "/update.xml";

                var client = new System.Net.WebClient();
                client.DownloadDataCompleted += (x, y) =>
                {
                    try
                    {
                        MemoryStream stream = new MemoryStream(y.Result);

                        XDocument xDoc                = XDocument.Load(stream);
                        UpdateInfo updateInfo         = new UpdateInfo();
                        XElement root                 = xDoc.Element("UpdateInfo");
                        updateInfo.AppName            = root.Element("AppName").Value;
                        updateInfo.AppVersion         = root.Element("AppVersion") == null || string.IsNullOrEmpty(root.Element("AppVersion").Value) ? null : new Version(root.Element("AppVersion").Value);
                        updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(root.Element("RequiredMinVersion").Value) ? null : new Version(root.Element("RequiredMinVersion").Value);
                        updateInfo.Desc               = root.Element("Desc").Value;
                        updateInfo.MD5                = Guid.NewGuid();

                        stream.Close();
                        Updater.Instance.StartUpdate(updateInfo, strRemoteUrl);
                    }
                    catch
                    { }
                };
                client.DownloadDataAsync(new Uri(url));
            });
        }
Exemple #8
0
        //private void btnCheckForUpdate_Click(System.Object sender, System.EventArgs e)
        //{
        //	Label2.Text = "Checking for updates...";
        //	Label2.Visible = true;
        //	Application.DoEvents();
        //	using (com.theprodev.www.Common ws = new com.theprodev.www.Common())
        //	{
        //		string AppVer = My.MyApplication.Application.Info.Version.Major + My.MyApplication.Application.Info.Version.Minor + My.MyApplication.Application.Info.Version.Build;
        //		ws.CheckForUpdateCompleted += CheckForUpdateCompleted;
        //		ws.CheckForUpdateAsync(AppVer, My.MyApplication.ProgramID);
        //	}
        //}

        //private void CheckForUpdateCompleted(object sender, com.theprodev.www.CheckForUpdateCompletedEventArgs e)
        //{
        //	try
        //	{
        //		if (e.Result == true)
        //		{
        //			LinkLabel1.Visible = true;
        //			Label2.Visible = false;
        //		}
        //		else
        //		{
        //			Label2.Visible = true;
        //			Label2.Text = "No update is available at this time.";
        //			LinkLabel1.Visible = false;
        //		}
        //	}
        //	catch (System.Web.Services.Protocols.SoapException ex)
        //	{
        //		Label2.Visible = true;
        //	}
        //	Application.DoEvents();
        //}

        private void LinkLabel1_LinkClicked(System.Object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                using (FolderBrowserDialog fbd = new FolderBrowserDialog())
                {
                    fbd.ShowNewFolderButton = true;
                    fbd.Tag = "Select the folder you wish to save this update too.";

                    DialogResult dr = fbd.ShowDialog();

                    if (dr == System.Windows.Forms.DialogResult.OK)
                    {
                        sUpdatePath = fbd.SelectedPath + "/" + My.MyApplication.Application.Info.Title + " Update.zip";
                        System.Uri           uri = new System.Uri("http://www.theprodev.com/files/trials/fdp-00.zip");
                        System.Net.WebClient wc  = new System.Net.WebClient();
                        wc.DownloadDataCompleted += DownloadDataCompleted;
                        wc.DownloadDataAsync(uri);
                    }
                }
            }
            catch (Exception ex)
            {
                Label1.Visible = false;
                MessageBox.Show("Sorry, but we were unable to contact the download server. Please browse to http://www.theprodev.com and download the new Free Version", "Could not connect", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public static void Urldown_DownloadDataCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null || e.Result.Length <= 0 || e.Cancelled)
            {
                return;
            }
            var resultstr = e.Result;
            if (string.IsNullOrEmpty(resultstr)) return;

            var tag = SearchData.JieXiData(resultstr);
            if (tag == null) return;
            if (!string.IsNullOrEmpty(tag.Img))
            {
                using (
                    var imgdown = new System.Net.WebClient
                        {
                            Encoding = System.Text.Encoding.UTF8,
                            Proxy = PublicStatic.MyProxy
                        })
                {
                    imgdown.DownloadDataAsync(new System.Uri(tag.Img), tag);
                    imgdown.DownloadDataCompleted += SearchImg.Imgdown_DownloadDataCompleted;
                }
            }
        }
Exemple #10
0
        public static (MemoryStream result, string errorMessage) FetchString(string url)
        {
            using var wc = new System.Net.WebClient();
            string       downloadError  = null;
            MemoryStream responseStream = null;

            wc.DownloadDataCompleted += (a, args) =>
            {
                downloadError = args.Error?.Message;
                if (downloadError == null)
                {
                    responseStream = new MemoryStream(args.Result);
                }
                lock (args.UserState)
                {
                    //releases blocked thread
                    Monitor.Pulse(args.UserState);
                }
            };
            var syncObject = new Object();

            lock (syncObject)
            {
                Debug.WriteLine("Download file to memory: " + url);
                wc.DownloadDataAsync(new Uri(url), syncObject);
                //This will block the thread until download completes
                Monitor.Wait(syncObject);
            }

            return(responseStream, downloadError);
        }
        private void LinkLabel1_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.ShowNewFolderButton = true;
            fbd.Tag = "Select the folder you wish to save this update too.";

            DialogResult dr = fbd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                try
                {
                    if (dr == DialogResult.OK)
                    {
                        this.sUpdatePath = fbd.SelectedPath + "/Duplicate File Finder Update.zip";
                        Uri uri = new Uri("http://www.theprodev.com/files/trials/DFF-00.zip");
                        System.Net.WebClient wc = new System.Net.WebClient();
                        wc.DownloadDataCompleted += DownloadDataCompleted;
                        wc.DownloadDataAsync(uri);
                    }
                }
                catch (System.Net.WebException ex)
                {
                    MessageBox.Show("Sorry, but we were unable to contact the download server. Please browse to http://www.theprodev.com and download the new Free Version", "Could not connect", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Exemple #12
0
 private void download_Poster(string imgUrl)
 {
     pictureBox1.Image = Properties.Resources.ajax_loader;
     using (var Wc = new System.Net.WebClient())
     {
         Wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(Wc_DownloadDataCompleted);
         Wc.DownloadDataAsync(new Uri(imgUrl));
     }
 }
Exemple #13
0
 public DateTime?ExecuteTask()
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         var url = string.Format(@"http://{0}/Default/TimerCallback/{1}", configService.DeployHostName, this.GetType().Name);
         client.DownloadDataAsync(new Uri(url));
         return(this.NextTaskDateTime);
     }
 }
Exemple #14
0
        private void DownloadUpdateFile()
        {
            FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, System.IO.Directory.GetCurrentDirectory());

            try {
                f.Demand();
            }
            catch (SecurityException e) {
                System.Windows.MessageBox.Show("文件夹权限错误,请检查UAC权限,无法启动更新程序。", "弹幕派",
                                               MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
                return;
            }
            string appDir = System.IO.Path.Combine(System.Reflection.Assembly.GetEntryAssembly().Location.Substring(0,
                                                                                                                    System.Reflection.Assembly.GetEntryAssembly().Location.LastIndexOf(System.IO.Path.DirectorySeparatorChar)));
            string updateFileDir = System.IO.Path.Combine(System.IO.Path.Combine(appDir.Substring(0,
                                                                                                  appDir.LastIndexOf(System.IO.Path.DirectorySeparatorChar))), "Danmakupie v" + updateInfo.AppVersion.ToString());
            string parentDir = appDir.Substring(0, appDir.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
            string fileName  = "Danmakupie v" + updateInfo.AppVersion.ToString() + ".zip";
            string url       = "http://7xr64j.com1.z0.glb.clouddn.com/" + fileName;
            var    client    = new System.Net.WebClient();

            client.DownloadProgressChanged += (sender, e) =>
            {
                UpdateProgressBar(e.BytesReceived / e.TotalBytesToReceive);
            };
            client.DownloadDataCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    string       zipFilePath = System.IO.Path.Combine(parentDir, fileName);
                    byte[]       data        = e.Result;
                    BinaryWriter writer      = new BinaryWriter(new FileStream(zipFilePath, FileMode.OpenOrCreate));
                    writer.Write(data);
                    writer.Flush();
                    writer.Close();
                    try {
                        ExtractZipFile(zipFilePath, "", parentDir);
                        System.IO.File.Delete(zipFilePath);
                        string exePath = parentDir + "\\Danmakupie v" + updateInfo.AppVersion.ToString() + "\\DanmakuPie.exe";
                        var    info    = new System.Diagnostics.ProcessStartInfo(exePath);
                        info.UseShellExecute  = true;
                        info.WorkingDirectory = parentDir + "\\Danmakupie v" + updateInfo.AppVersion.ToString();
                        System.Windows.MessageBox.Show("更新完成,请删除旧版本程序文件。", "弹幕派",
                                                       MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
                        System.Diagnostics.Process.Start(info);
                    }
                    catch {
                        System.Windows.MessageBox.Show("数据包损坏,请重试。", "弹幕派",
                                                       MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
                    }
                    finally {
                        Application.Current.Shutdown();
                    }
                }
            };
            client.DownloadDataAsync(new Uri(url));
        }
Exemple #15
0
        //==================================================================================
        public void GetPosition(bool reRoute)
        {
            try
            {
                mProgressBar.Visibility = ViewStates.Visible;

                Uri url = new Uri(ConfigManager.WebService + "/" + "positionProvider.php?pk_id=" + mNavData[0] + "&vt_id=" + mNavData[1]);
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadDataAsync(url);
                webClient.DownloadDataCompleted += (object s, System.Net.DownloadDataCompletedEventArgs e) =>
                {
                    RunOnUiThread(() => { mProgressBar.Visibility = ViewStates.Invisible; });
                    string          json = Encoding.UTF8.GetString(e.Result);
                    OperationResult op   = JsonConvert.DeserializeObject <OperationResult>(json);

                    if (op.error)
                    {
                        // No hay posicion para ese vehiculo, tengo que levantar el modal
                        trans             = FragmentManager.BeginTransaction();
                        mDialogNoPosition = new DialogNoPosition();
                        mDialogNoPosition.Show(trans, "No Hay Posiciones Disponibles");
                        mDialogNoPosition.mCancelEvent += (object o, OnCancelEvent onCancelEvent) =>
                        {
                            // Elimino las posiciones de ese Usuario
                            ClearUserPositions();

                            // Le aviso a los Raspis que ya no tienen que monitorearme
                            Kill();
                            Managment.ActivityManager.TakeMeTo(this, typeof(MainActivity), true);
                        };
                    }
                    else
                    {
                        // Guardo la posicion
                        mPositionID = Convert.ToInt32(op.data);
                        if (reRoute)
                        {
                            // Tengo que recalcular
                            ReloadBorwser();
                        }
                        else
                        {
                            // Le aviso a los Raspi que me tienen que monitorear a mi
                            Bootstrap();
                            //Levanto el Browser por Primera vez
                            LoadBrowserView();
                        }

                        Console.WriteLine("** Posicion Obtenida: " + mPositionID.ToString() + " **");
                    }
                };
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
        private static void Datadown_DownloadStringCompleted(object sender,
            System.Net.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null || e.Result.Length <= 0 || e.Cancelled)
            {
                return;
            }
            var resultstr = e.Result;
            if (string.IsNullOrEmpty(resultstr)) return;

            // 得到<ul class=\"allsearch dashed boxPadd6\"> ~ </ul>
            var orignlis = resultstr.GetSingle("<table id=\"archiveResult\">", "</table>");
            orignlis = orignlis.Replace("<tbody>", "");
            if (string.IsNullOrEmpty(orignlis))
            {
                return;
            }
            // 得到 <li> ~ </li>
            var orignli = orignlis.GetValue("Detail", "Open");
            if (orignli == null || orignli.Count <= 0) return;

            // 解析数据
            var zuiReDatas = new System.Collections.Generic.List<LiuXingData>();
            foreach (var v in orignli)
            {
                var tag = SearchData.JieXiSearchData(v);
                if (tag != null)
                {
                    zuiReDatas.Add(tag);
                }
            }
            if (zuiReDatas.Count <= 0) return;

            // 遍历数据中的图片
            for (var i = 0; i < zuiReDatas.Count; i++)
            {
                var tag = zuiReDatas[i];
                if (tag != null)
                {
                    var imgtemp = tag.Img;
                    if (!string.IsNullOrEmpty(imgtemp))
                    {
                        using (
                            var imgdown = new System.Net.WebClient
                                {
                                    Encoding = System.Text.Encoding.UTF8,
                                    Proxy = PublicStatic.MyProxy
                                })
                        {
                            imgdown.DownloadDataAsync(new System.Uri(imgtemp), tag);
                            imgdown.DownloadDataCompleted += SearchImg.Imgdown_DownloadDataCompleted;
                        }
                    }
                }
            }
        }
        public void GetHistoric()
        {
            string clientID = mFile.GetValue("id");

            mClient = new System.Net.WebClient();
            Uri url = new Uri(ConfigManager.WebService + "/searchHistoric.php?cl_id=" + clientID);

            mClient.DownloadDataAsync(url);
            mClient.DownloadDataCompleted += MClient_DownloadDataCompleted;
        }
Exemple #18
0
        public static void CheckUpdateStatus(string remoteUrl)
        {
            System.Threading.ThreadPool.QueueUserWorkItem((s) =>
            {
                string url = "";
                if (!string.IsNullOrWhiteSpace(remoteUrl))
                {
                    url = remoteUrl;
                }
                url = url + "/" + Updater.Instance.CallExeName + "/update.xml";

                LogerManager.Current.AsyncDebug("下载:" + url);
                var client = new System.Net.WebClient();
                client.DownloadDataCompleted += (x, y) =>
                {
                    try
                    {
                        MemoryStream stream = new MemoryStream(y.Result);

                        XDocument xDoc         = XDocument.Load(stream);
                        UpdateInfo updateInfo  = new UpdateInfo();
                        XElement root          = xDoc.Element("UpdateInfo");
                        updateInfo.AppName     = root.Element("AppName").Value;
                        updateInfo.PackageName = root.Element("PackageName").Value;
                        updateInfo.AppVersion  = root.Element("AppVersion") == null || string.IsNullOrEmpty(root.Element("AppVersion").Value) ?
                                                 "" : root.Element("AppVersion").Value;
                        updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion") == null || string.IsNullOrEmpty(root.Element("RequiredMinVersion").Value) ?
                                                        "" : root.Element("RequiredMinVersion").Value;
                        updateInfo.DownloadUrl = root.Element("DownloadUrl").Value;
                        updateInfo.MD5         = root.Element("MD5") == null || string.IsNullOrEmpty(root.Element("MD5").Value) ?
                                                 Guid.NewGuid() : new Guid(root.Element("MD5").Value);
                        updateInfo.FileExecuteBefore     = root.Element("FileExecuteBefore") == null ? "" : root.Element("FileExecuteBefore").Value;
                        updateInfo.ExecuteArgumentBefore = root.Element("ExecuteArgumentBefore") == null ? "" : root.Element("ExecuteArgumentBefore").Value;
                        updateInfo.FileExecuteAfter      = root.Element("FileExecuteAfter") == null ? "" : root.Element("FileExecuteAfter").Value;
                        updateInfo.ExecuteArgumentAfter  = root.Element("ExecuteArgumentAfter") == null ? "" : root.Element("ExecuteArgumentAfter").Value;
                        updateInfo.Description           = root.Element("Description") == null ? "" : root.Element("Description").Value;
                        if (updateInfo.MD5 == Guid.Empty)
                        {
                            updateInfo.MD5 = Guid.NewGuid();
                        }

                        stream.Close();

                        Updater.Instance.StartUpdate(updateInfo);
                    }
                    catch (Exception ex)
                    {
                        LogerManager.Current.AsyncError("检查版本更新异常:" + ex.Message);
                    }
                };
                client.DownloadDataAsync(new Uri(url));
            });
        }
Exemple #19
0
        public void LoadClientProfile()
        {
            string clientID = fm.GetValue("id");

            string urlRef = "client_id=" + clientID;

            mClient = new System.Net.WebClient();
            Uri url = new Uri(ConfigManager.WebService + "/" + "searchClientProfile.php?" + urlRef);

            mClient.DownloadDataAsync(url);
            mClient.DownloadDataCompleted += MClient_DownloadDataCompleted;;
        }
 /// <summary>
 /// 使用 GET 方法异步获取某个特定 的 Uri 的资源,获取完成后无论成功还是失败,都将调用 HttpAsyncCompletedCallback 委托,并支持通过 HttpAsyncProgressCallback 报告下载进度。
 /// </summary>
 /// <param name="uri">要下载的资源。</param>
 /// <param name="completedCallback">完成下载后要执行的委托。</param>
 /// <param name="progressCallback">进度报告委托,可以为 null。</param>
 public static void Get(Uri uri, HttpAsyncCompletedCallback<byte[]> completedCallback, HttpAsyncProgressCallback progressCallback = null)
 {
     System.Net.WebClient client = new System.Net.WebClient();
     client.DownloadDataCompleted += (sender, e) => {
         completedCallback(e.Cancelled == false && e.Error == null && e.Result != null, e.Error, e.Result);
     };
     if (progressCallback != null) {
         client.DownloadProgressChanged += (sender, e) => {
             progressCallback(e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
         };
     }
     client.DownloadDataAsync(uri);
 }
Exemple #21
0
        public static string EnsureStaticZippedExecutable(string staticZipName, string foldername, string executablename, Action <long, long> progressCallback = null, string hash = null)
        {
            string staticExecutable = Path.Combine(App.StaticExecutablesDirectory, foldername, executablename);

            if (!File.Exists(staticExecutable)) //In future we will want to have a way to hash check this or something so we can update this if necessary without user intervention.
            {
                using (var wc = new System.Net.WebClient())
                {
                    string downloadError = null;
                    wc.DownloadProgressChanged += (a, args) =>
                    {
                        progressCallback?.Invoke(args.BytesReceived, args.TotalBytesToReceive);
                    };
                    wc.DownloadDataCompleted += (a, args) =>
                    {
                        downloadError = args.Error?.Message;
                        if (downloadError != null)
                        {
                            if (File.Exists(staticExecutable))
                            {
                                File.Delete(staticExecutable);
                            }
                        }
                        else
                        {
                            ZipArchive za        = new ZipArchive(new MemoryStream(args.Result));
                            var        outputdir = Directory.CreateDirectory(Path.Combine(App.StaticExecutablesDirectory, foldername)).FullName;
                            za.ExtractToDirectory(outputdir);
                        }
                        lock (args.UserState)
                        {
                            //releases blocked thread
                            Monitor.Pulse(args.UserState);
                        }
                    };
                    var fullURL    = App.StaticFilesBaseURL + staticZipName;
                    var syncObject = new object();
                    lock (syncObject)
                    {
                        Debug.WriteLine("Fetching zip via " + fullURL);
                        wc.DownloadDataAsync(new Uri(fullURL), syncObject);
                        //This will block the thread until download completes
                        Monitor.Wait(syncObject);
                    }

                    return(downloadError);
                }
            }

            return(null); //File exists
        }
Exemple #22
0
        public void RemVehicle(Vehicle vehicle)
        {
            try
            {
                System.Net.WebClient wclient = new System.Net.WebClient();
                Uri uri = new Uri(ConfigManager.WebService + "/delVehicle.php?id=" + vehicle.id.ToString());

                wclient.DownloadDataAsync(uri);
                wclient.DownloadDataCompleted += Wclient_DownloadDataCompleted;
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
        void RequestRunePreviewFromServer()
        {
            if (QueuedRunePreviewHashes.Count == 0)
            {
                return;
            }

            string hash      = QueuedRunePreviewHashes.Peek();
            Uri    dw_string = new Uri(IMAGE_SERVER + "images/runes/sm/" + hash + ".png");

            while (wc.IsBusy)
            {
                Thread.Sleep(10);
            }
            wc.DownloadDataAsync(dw_string);
        }
        public void Downlaod_mp3_Url(string url, string audioFileName, Xamarin.Forms.ActivityIndicator LoadingDownloadProgress, Xamarin.Forms.Label DownloadingLabel)
        {
            LoadingDownloadProgress.IsRunning = true;
            DownloadingLabel.IsVisible        = true;

            //  LongAlert(audioFileName + " Downloading..");
            var webClient = new System.Net.WebClient();

            webClient.DownloadDataCompleted += (s, e) =>
            {
                var    text          = e.Result; // get the downloaded text
                string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

                string localPath = System.IO.Path.Combine(documentsPath, audioFileName);
                Console.WriteLine(localPath);
                File.WriteAllBytes(localPath, text); // writes to local storage
                LongAlert(audioFileName + " Downloaded to path");
                LoadingDownloadProgress.IsRunning = false;
                DownloadingLabel.IsVisible        = false;
            };

            try
            {
                var urla = new Uri(url);                 // give this an actual URI to an MP3
                webClient.DownloadDataAsync(urla);
            }
            catch (System.Threading.Tasks.TaskCanceledException)
            {
                //   LongAlert("Task Canceled!");
                LoadingDownloadProgress.IsRunning = false;
                DownloadingLabel.IsVisible        = false;
                return;
            }
            catch (Exception a)
            {
                //LongAlert(a.InnerException.Message);
                LoadingDownloadProgress.IsRunning = false;
                DownloadingLabel.IsVisible        = false;
                Download_Completed = false;
                return;
            }


            Download_Completed = false;
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
        }
        /// <summary>
        /// Downloads our rules from the usl site
        /// </summary>
        private void GetUslRules(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return;
            }

            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.DownloadDataCompleted += ParseRules;

            try
            {
                webclient.DownloadDataAsync(new Uri(url));
                webclient.Dispose();
            }
            catch
            { }
        }
Exemple #26
0
        public static void GetPcVersionDetail(Action <bool, System.Net.DownloadDataCompletedEventArgs> completedCB, Action <long> progressCB)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.DownloadDataCompleted += (s, e) => {
                if (!e.Cancelled && e.Error == null)
                {
                    completedCB?.Invoke(true, e);
                    verInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <VersionInfo>(Encoding.UTF8.GetString(e.Result));
                }
                else
                {
                    completedCB?.Invoke(false, e);
                }
            };

            client.DownloadProgressChanged += (s, e) => progressCB?.Invoke(e.BytesReceived);
            client.DownloadDataAsync(new Uri(PcVersionDetail));
        }
 /// <summary>
 /// 5.图片下载
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="imageurl"></param>
 /// <param name="iType"></param>
 public static void StartImageDown(LiuXingData tag, string imageurl, LiuXingType iType)
 {
     if (string.IsNullOrEmpty(imageurl)) return;
     using (
         var imgdown = new System.Net.WebClient
         {
             Encoding = iType.Encoding,
             Proxy = iType.Proxy
         })
     {
         if (!string.IsNullOrEmpty(imageurl))
         {
             var iClass = new LiuXingType
             {
                 Encoding = iType.Encoding,
                 Proxy = iType.Proxy,
                 Type = iType.Type,
                 Data = tag
             };
             var image = FileCachoHelper.ImageCacho(imageurl);
             if (image != null)
             {
                 iClass.Img = image;
                 GoToDisPlay(iClass);
             }
             else
             {
                 try
                 {
                     var imguri = new System.Uri(imageurl);
                     imgdown.Headers.Add(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1581.2 Safari/537.36");
                     imgdown.DownloadDataAsync(imguri, iClass);
                     imgdown.DownloadDataCompleted += Imgdown_DownloadDataCompleted;
                 }
                 // ReSharper disable EmptyGeneralCatchClause
                 catch
                 // ReSharper restore EmptyGeneralCatchClause
                 {
                     // System.Windows.Forms.MessageBox.Show(exception.Message+zuiReDatas[i].Name+zuiReDatas[i].Img+i);
                 }
             }
         }
     }
 }
Exemple #28
0
        public static (MemoryStream result, string errorMessage) DownloadToMemory(string url, Action <long, long> progressCallback = null, string hash = null)
        {
            using var wc = new System.Net.WebClient();
            string       downloadError  = null;
            MemoryStream responseStream = null;

            wc.DownloadProgressChanged += (a, args) => { progressCallback?.Invoke(args.BytesReceived, args.TotalBytesToReceive); };
            wc.DownloadDataCompleted   += (a, args) =>
            {
                downloadError = args.Error?.Message;
                if (downloadError == null)
                {
                    responseStream = new MemoryStream(args.Result);
                    if (hash != null)
                    {
                        var md5 = Utilities.CalculateMD5(responseStream);
                        responseStream.Position = 0;
                        if (md5 != hash)
                        {
                            responseStream = null;
                            downloadError  = $"Hash of downloaded item ({url}) does not match expected hash. Expected: {hash}, got: {md5}";
                        }
                    }
                }
                lock (args.UserState)
                {
                    //releases blocked thread
                    Monitor.Pulse(args.UserState);
                }
            };
            var syncObject = new Object();

            lock (syncObject)
            {
                Debug.WriteLine("Download file to memory: " + url);
                wc.DownloadDataAsync(new Uri(url), syncObject);
                //This will block the thread until download completes
                Monitor.Wait(syncObject);
            }

            return(responseStream, downloadError);
        }
        public void RouteToDestination(LatLng client, LatLng parkinglot)
        {
            try
            {
                string origin      = client.Latitude.ToString() + "," + client.Longitude.ToString();
                string destination = parkinglot.Latitude.ToString() + "," + parkinglot.Longitude.ToString();

                System.Net.WebClient localClient = new System.Net.WebClient();
                Uri url = new Uri(ConfigManager.GoogleService + "origin=" + origin + "&destination=" + destination);

                mProgressBar.Visibility = ViewStates.Visible;
                localClient.DownloadDataAsync(url);
                localClient.DownloadDataCompleted += LocalClient_DownloadDataCompleted;
            }
            catch (Exception ex)
            {
                Console.WriteLine("** Error ** : No se pudo conectar a Google Route /n " + ex.Message);
                //Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
Exemple #30
0
 /// <summary>
 /// 开始下载更新的zip
 /// </summary>
 private void DownloadUpdateFile()
 {
     try
     {
         string url    = Constants.RemoteUrl_zip;
         var    client = new System.Net.WebClient();
         client.DownloadProgressChanged += (sender, e) =>
         {
             UpdateProcess(e.BytesReceived, e.TotalBytesToReceive);
         };
         client.DownloadDataCompleted += client_DownloadDataCompleted_File;
         client.DownloadDataAsync(new Uri(url));
         SetButtonState();
     }
     catch (Exception ex)
     {
         WriteLogHelper.WriteLog_client("DownloadUpdateFile error", ex);
         MessageBox.Show(ex.Message);
     }
 }
Exemple #31
0
        public void SearchParkinglots()
        {
            try
            {
                string clientID      = fm.GetValue("id");
                string vehicleTypeID = fm.GetValue("vt_id");
                string lat           = mCenterPosition.Latitude.ToString();
                string lng           = mCenterPosition.Longitude.ToString();

                string urlRef = "client_id=" + clientID + "&" + "vt_id=" + vehicleTypeID + "&" + "lat=" + lat + "&" + "lng=" + lng;
                Uri    url    = new Uri(ConfigManager.WebService + "/" + "searchParkinglot.php?" + urlRef);

                mProgressBar.Visibility = ViewStates.Visible;
                mClient.DownloadDataAsync(url);
                mClient.DownloadDataCompleted += MClient_DownloadDataCompleted;
            }
            catch (Exception ex)
            {
                Managment.ActivityManager.ShowError(this, new Error(errCode, errMsg));
            }
        }
Exemple #32
0
        private void _start_Click(object sender, EventArgs e)
        {
            string portName = this.PortName;

            if (Properties.Resources.PORT_AUTOSEL == portName)
            {
                try
                {
                    portName      = SkytraqController.AutoSelectPort();
                    this.PortName = portName;
                }
                catch
                {
                    _posrts.Items.Remove(portName);
                    MessageBox.Show(Properties.Resources.MSG1, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }
            try
            {
                _port = new SkytraqController(portName);
                MyEnviroment.LatestPortName = portName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            _port.OnSetEphemeris += _port_OnSetEphemeris;

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Credentials = new System.Net.NetworkCredential(_username.Text, _password.Text);
            string URL = string.Format("ftp://{0}/ephemeris/Eph.dat", _host.Text);

            wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
            wc.DownloadDataCompleted   += Wc_DownloadDataCompleted;
            wc.DownloadDataAsync(new Uri(URL));

            return;
        }
        public void SaveImage(string fileName, string imageURL)
        {
            var webClient = new System.Net.WebClient();

            webClient.DownloadDataCompleted += (s, e) => {
                try
                {
                    var    bytes     = e.Result;          // get the downloaded data
                    string localPath = GetPath("images", fileName);
                    File.WriteAllBytes(localPath, bytes); // writes to local storage
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.InnerException.Message);
                }
            };

            var url = new Uri(imageURL);

            webClient.DownloadDataAsync(url);
        }
Exemple #34
0
        public void Bootstrap()
        {
            if (mMacAddress == string.Empty)
            {
                string var = "No fue posible iniciar el Monitoreo Wifi";
                Managment.ActivityManager.ShowError(this, new Error(errCode, var));
                return;
            }

            try
            {
                string urlRef = "bootstrap.php" + "?" + "mac=" + mMacAddress;
                Uri    url    = new Uri(ConfigManager.WebService + "/" + urlRef);
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadDataAsync(url);
                webClient.DownloadDataCompleted += (object s, System.Net.DownloadDataCompletedEventArgs e) =>
                {
                    try
                    {
                        string          json = Encoding.UTF8.GetString(e.Result);
                        OperationResult op   = JsonConvert.DeserializeObject <OperationResult>(json);

                        if (op.error)
                        {
                            Console.WriteLine("** No fue posible realizar Bootstrap **");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("** No fue posible realizar Bootstrap **");
                    }
                };
            }
            catch (Exception ex)
            {
                string var = "No fue posible iniciar el Monitoreo Wifi";
                Managment.ActivityManager.ShowError(this, new Error(errCode, var));
            }
        }
Exemple #35
0
        /// <summary>
        /// 下载更新信息
        /// </summary>
        void DownloadUpdateInfoInternal(object sender, RunworkEventArgs e)
        {
            if (!IsUpdateInfoDownloaded)
            {
                var client = new System.Net.WebClient();
                client.DownloadProgressChanged += (x, y) =>
                {
                    e.ReportProgress((int)y.TotalBytesToReceive, (int)y.BytesReceived);
                };

                //下载更新信息
                e.PostEvent(OnDownloadUpdateInfo);

                //下载信息时不直接下载到文件中.这样不会导致始终创建文件夹
                var finished = false;
                Exception ex = null;
                client.DownloadDataCompleted += (x, y) =>
                {
                    ex = y.Error;
                    if (ex == null) UpdateContent = System.Text.Encoding.UTF8.GetString(y.Result);
                    finished = true;
                };
                client.DownloadDataAsync(new Uri(UpdateUrl));
                while (!finished)
                {
                    System.Threading.Thread.Sleep(50);
                }
                if (this.Exception != null) throw ex;
                e.PostEvent(OnDownloadUpdateInfoFinished);

                //是否返回了正确的结果?
                if (string.IsNullOrEmpty(UpdateContent))
                {
                    throw new ApplicationException("服务器返回了不正确的更新结果");
                }
            }
            if (UpdateInfo == null)
            {
                if (string.IsNullOrEmpty(UpdateContent))
                {
                    UpdateContent = System.IO.File.ReadAllText(UpdateInfoFilePath, System.Text.Encoding.UTF8);
                }

                UpdateInfo = XMLSerializeHelper.XmlDeserializeFromString<UpdateInfo>(UpdateContent);
            }
        }
        /// <summary>
        /// 4.一级数据解析
        /// </summary>
        /// <param name="resultstr"></param>
        /// <param name="iType"></param>
        private static void JieXiOne(string resultstr, LiuXingType iType)
        {
            var zuiReDatas = new System.Collections.Generic.List<LiuXingData>();
            switch (iType.Type)
            {
                // 迅播影院正常列表
                case LiuXingEnum.XunboListItem:
                case LiuXingEnum.XunboSearchItem:
                    {
                        #region case LiuXingEnum.XunboListItem:

                        // 得到 <ul class=\"piclist\"> ~ </ul>
                        var orignlis = StringRegexHelper.GetSingle(resultstr, "<ul class=\"piclist\">", "</ul>");
                        if (string.IsNullOrEmpty(orignlis))
                        {
                            return;
                        }
                        // 得到 <li> ~ </li>
                        var orignli = StringRegexHelper.GetValue(orignlis, "<li>", "</li>");
                        if (orignli == null || orignli.Count <= 0) return;
                        for (var i = 0; i < orignli.Count; i++)
                        {
                            var celllistr = orignli[i];
                            if (string.IsNullOrEmpty(celllistr)) continue;
                            var tempcell = DataTagHelper.AnalyzeData(celllistr, iType);
                            if (tempcell != null)
                            {
                                zuiReDatas.Add(tempcell);
                            }
                        }
                        // 开始下载图片
                        StartImageDown(zuiReDatas, iType);
                        return;
                        #endregion
                    }
                // 人人影视正常列表
                case LiuXingEnum.YYetListItem:
                    {
                        #region case LiuXingEnum.YYetListItem:

                        // 得到<ul class="boxPadd dashed"> ~ </ul>
                        var orignlis = StringRegexHelper.GetSingle(resultstr, "<ul class=\"boxPadd dashed\">", "</ul>");
                        if (string.IsNullOrEmpty(orignlis))
                        {
                            return;
                        }
                        // 得到 <li> ~ </li>
                        var orignli = StringRegexHelper.GetValue(orignlis, "<li ", "</li>");
                        if (orignli == null || orignli.Count <= 0)
                        {
                            return;
                        }
                        for (var i = 0; i < orignli.Count; i++)
                        {
                            var celllistr = orignli[i];
                            if (!string.IsNullOrEmpty(celllistr))
                            {
                                var tag = DataTagHelper.AnalyzeData(celllistr, iType);
                                if (tag != null)
                                {
                                    zuiReDatas.Add(tag);
                                }
                            }
                        }
                        // 开始下载图片
                        StartImageDown(zuiReDatas, iType);
                        return;
                        #endregion
                    }
                case LiuXingEnum.YYetSearchItem:
                    {
                        #region case LiuXingEnum.YYetSearchItem:
                        if (!string.IsNullOrEmpty(iType.Sign) && iType.Sign.Contains("YYetSearchSecond"))
                        {
                            // 解析影视资料页的数据并生成模型
                            var tag = DataTagHelper.AnalyzeData(resultstr, iType);
                            if (tag == null) return;
                            if (!string.IsNullOrEmpty(tag.Img))
                            {
                                using (
                                    var imgdown = new System.Net.WebClient
                                    {
                                        Encoding = iType.Encoding,
                                        Proxy = iType.Proxy
                                    })
                                {
                                    iType.Data = tag;
                                    imgdown.DownloadDataAsync(new System.Uri(tag.Img), iType);
                                    imgdown.DownloadDataCompleted += Imgdown_DownloadDataCompleted;
                                }
                            }
                        }
                        else
                        {
                            // 得到<ul class=\"allsearch dashed boxPadd6\"> ~ </ul>
                            string orignlis = StringRegexHelper.GetSingle(resultstr, "<ul class=\"allsearch dashed boxPadd6\">", "</ul>");
                            if (string.IsNullOrEmpty(orignlis))
                            {
                                return;
                            }

                            // 得到 <li> ~ </li>
                            var orignli = StringRegexHelper.GetValue(orignlis, "<a href=\"", "\" target=\"_blank\">");
                            if (orignli == null || orignli.Count <= 0) return;

                            // 解析数据
                            for (int i = 0; i < orignli.Count; i++)
                            {
                                iType.Sign = "YYetSearchSecond";
                                StartList(orignli[i], iType);
                            }
                        }

                        return;
                        #endregion
                    }
                case LiuXingEnum.PiaoHuaSearchItem:
                    {
                        #region case LiuXingEnum.PiaoHuaSearchItem:
                        if (!string.IsNullOrEmpty(iType.Sign) && iType.Sign.Contains("PiaoHuaSearchSecond"))
                        {
                            // 解析影视资料页的数据并生成模型
                            var tag = DataTagHelper.AnalyzeData(resultstr, iType);
                            if (tag == null) return;
                            if (!string.IsNullOrEmpty(tag.Img))
                            {
                                using (
                                    var imgdown = new System.Net.WebClient
                                    {
                                        Encoding = iType.Encoding,
                                        Proxy = iType.Proxy
                                    })
                                {
                                    iType.Data = tag;
                                    imgdown.DownloadDataAsync(new System.Uri(tag.Img), iType);
                                    imgdown.DownloadDataCompleted += Imgdown_DownloadDataCompleted;
                                }
                            }
                        }
                        else
                        {
                            // 得到<ul class=\"allsearch dashed boxPadd6\"> ~ </ul>
                            string orignlis = StringRegexHelper.GetSingle(resultstr, "<ul class=\"relist clearfix\">", "</ul>");
                            if (string.IsNullOrEmpty(orignlis))
                            {
                                return;
                            }

                            // 得到 <li> ~ </li>
                            var orignli = StringRegexHelper.GetValue(orignlis, "<li>", "</li>");
                            if (orignli == null || orignli.Count <= 0) return;
                            // 得到Url列表
                            var listurls = new System.Collections.Generic.List<string>();
                            foreach (var v in orignli)
                            {
                                var orign = StringRegexHelper.GetSingle(v, "<div class=\"minfo_op\"><a href=\"", "\" class=\"info\">下载");
                                if (!string.IsNullOrEmpty(orign))
                                {
                                    listurls.Add(orign);
                                }
                            }
                            if (listurls.Count <= 0) return;
                            // 解析数据
                            foreach (var listurl in listurls)
                            {
                                var listtemp = listurl;
                                if (!string.IsNullOrEmpty(listtemp))
                                {
                                    iType.Sign = "PiaoHuaSearchSecond";
                                    StartList(listurl, iType);
                                }
                            }
                        }

                        return;
                        #endregion
                    }
                case LiuXingEnum.DyfmSearchItem:
                    {
                        #region case LiuXingEnum.DyfmSearchItem:
                        if (!string.IsNullOrEmpty(iType.Sign) && iType.Sign.Contains("DyfmSecond"))
                        {
                            // 解析影视资料页的数据并生成模型
                            var tag = DataTagHelper.AnalyzeData(resultstr, iType);
                            if (tag == null) return;
                            if (!string.IsNullOrEmpty(tag.Img))
                            {
                                using (
                                    var imgdown = new System.Net.WebClient
                                    {
                                        Encoding = iType.Encoding,
                                        Proxy = iType.Proxy
                                    })
                                {
                                    iType.Data = tag;
                                    imgdown.DownloadDataAsync(new System.Uri(tag.Img), iType);
                                    imgdown.DownloadDataCompleted += Imgdown_DownloadDataCompleted;
                                }
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(iType.Sign) && iType.Sign.Contains("DyfmSearchItemDOCTYPE"))
                            {
                                // 得到 <li> ~ </li>
                                var orignli = StringRegexHelper.GetValue(resultstr, "<li>", "</li>");
                                if (orignli == null || orignli.Count <= 0) return;
                                // 得到影片页地址
                                var urls = new System.Collections.Generic.List<string>();
                                for (var i = 0; i < orignli.Count; i++)
                                {
                                    var urlkey = StringRegexHelper.GetSingle(orignli[i], "<a target=\"_blank\" href=\"", "\">");
                                    if (!string.IsNullOrEmpty(urlkey))
                                    {
                                        var urltemp = "http://dianying.fm" + urlkey;
                                        urls.Add(urltemp);
                                    }
                                }
                                if (urls.Count > 0)
                                {
                                    foreach (string url in urls)
                                    {
                                        if (!string.IsNullOrEmpty(url))
                                        {
                                            iType.Sign = "DyfmSecond";
                                            StartList(url, iType);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // 得到<ul class=\"x-movie-list nav nav-pills\" style=\"padding-top:0;\"> ~ </ul>
                                string orignlis = StringRegexHelper.GetSingle(resultstr, "var apiURL = '", "'");
                                orignlis = string.Format("http://dianying.fm/{0}?page=1", orignlis);
                                if (string.IsNullOrEmpty(orignlis))
                                {
                                    return;
                                }
                                iType.Sign = "DyfmSearchItemDOCTYPE";
                                StartList(orignlis, iType);
                            }
                        }

                        return;
                        #endregion
                    }
                case LiuXingEnum.TorrentKittySearchItem:
                    {
                        #region case LiuXingEnum.TorrentKittySearchItem:
                        // 得到<ul class=\"allsearch dashed boxPadd6\"> ~ </ul>
                        string orignlis = StringRegexHelper.GetSingle(resultstr, "<table id=\"archiveResult\">", "</table>");
                        orignlis = orignlis.Replace("<tbody>", "");
                        if (string.IsNullOrEmpty(orignlis))
                        {
                            return;
                        }
                        // 得到 <li> ~ </li>
                        var orignli = StringRegexHelper.GetValue(orignlis, "Detail", "Open");
                        if (orignli == null || orignli.Count <= 0) return;

                        // 解析数据
                        foreach (string v in orignli)
                        {
                            LiuXingData tag = DataTagHelper.AnalyzeData(v, iType);
                            if (tag != null)
                            {
                                zuiReDatas.Add(tag);
                            }
                        }
                        // 开始下载图片
                        StartImageDown(zuiReDatas, iType);
                        return;
                        #endregion
                    }
                case LiuXingEnum.M1905ComListItem:
                    {
                        #region case LiuXingEnum.M1905ComListItem:
                        if (resultstr.Contains("flashurl"))
                        {
                            var tag = DataTagHelper.AnalyzeData(resultstr, iType);
                            zuiReDatas.Add(tag);
                        }
                        else
                        {
                            var films = StringRegexHelper.GetValue(resultstr, "<film>", "</film>");
                            if (films == null || films.Count <= 0) return;
                            foreach (var film in films)
                            {
                                var tag = DataTagHelper.AnalyzeData(film, iType);
                                zuiReDatas.Add(tag);
                            }
                        }
                        // 开始下载图片
                        StartImageDown(zuiReDatas, iType);
                        return;
                        #endregion
                    }
                case LiuXingEnum.LuYiXia:
                    {
                        #region  case LiuXingEnum.LuYiXia:
                        if (string.IsNullOrEmpty(resultstr))
                        {
                            AutoCloseDlg.ShowMessageBoxTimeout(@"噢噢!众人一起撸,管子都断了,捏捏泥鳅等修复!", @"亲,不好意思", System.Windows.Forms.MessageBoxButtons.OK, 1000);
                            return;
                        }
                        var urllists = new System.Collections.Generic.List<string>
                        {
                            StringRegexHelper.GetSingle(resultstr, "\"Url\":\"", "\",\"Gcid\":")
                        };
                        if (urllists.Count <= 0)
                        {
                            AutoCloseDlg.ShowMessageBoxTimeout(@"噢噢!众人一起撸,管子都断了,捏捏泥鳅等修复!", @"亲,不好意思", System.Windows.Forms.MessageBoxButtons.OK, 1000);
                            return;
                        }
                        VodCopyHelper.StartToVod(urllists, new LiuXingData());
                        return;
                        #endregion
                    }
                case LiuXingEnum.ZhangYuSearchItem:
                    {
                        #region case LiuXingEnum.ZhangYuSearchItem:

                        var zhangyuapi = JsonMapper.ToObject<ZhangYuApi>(resultstr);
                        if (zhangyuapi != null)
                        {
                            var zhangyuapihtml = zhangyuapi.html;
                            if (!string.IsNullOrEmpty(zhangyuapihtml))
                            {
                                var dataurls = StringRegexHelper.GetValue(zhangyuapihtml, "<span class=\"p reslink\"", "<span class");
                                if (dataurls != null && dataurls.Count > 0)
                                {
                                    foreach (var dataurl in dataurls)
                                    {
                                        if (!string.IsNullOrEmpty(dataurl))
                                        {
                                            var url = StringRegexHelper.GetSingle(dataurl, "data-url=\"", "\"");
                                            if (!string.IsNullOrEmpty(url))
                                            {
                                                if (url.Contains("_id=") && url.Contains("&"))
                                                {
                                                    url = StringRegexHelper.GetSingle(url, "id=", "&");
                                                    if (!string.IsNullOrEmpty(url))
                                                    {
                                                        var name = StringRegexHelper.GetSingle(dataurl, "data-title=\"", "\"");
                                                        if (!string.IsNullOrEmpty(name))
                                                        {
                                                            name = UrlCodeHelper.GetClearVideoName(name);
                                                            url = "magnet:?xt=urn:btih:" + url;
                                                            zuiReDatas.Add(new LiuXingData
                                                            {
                                                                Name = name,
                                                                HDs = QualityHelper.GetHdsSign(name),
                                                                Drl = new System.Collections.Generic.List<string> { url },
                                                                Img = "http://www.qq7.com/uploads/allimg/120510/1s31110w-31.jpg"
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (zuiReDatas.Count > 0)
                                    {
                                        // 开始下载图片
                                        StartImageDown(zuiReDatas, iType);
                                    }

                                }
                            }
                        }

                        return;
                        #endregion
                    }
                case LiuXingEnum.DyfmHotApi:
                    {
                        #region case LiuXingEnum.DyfmHotApi:
                        var tag = DataTagHelper.AnalyzeData(resultstr, iType);
                        if (tag != null)
                        {
                            zuiReDatas.Add(tag);
                        }
                        if (zuiReDatas.Count > 0)
                        {
                            StartImageDown(zuiReDatas,iType);
                        }

                        return;
                        #endregion
                    }
                case LiuXingEnum.EverybodyWatch:
                    {
                        #region case LiuXingEnum.EverybodyWatch:
                        // 二次请求数据
                        if (resultstr.Contains("bigshot_url"))
                        {
                            //var oldimg = iType.Data.Img;
                            var newimg = StringRegexHelper.GetSingle(resultstr, "\"bigshot_url\": \"", "\"}");
                            if (!string.IsNullOrEmpty(newimg))
                            {
                                iType.Data.Img = newimg;
                                if (!string.IsNullOrEmpty(iType.Data.Img))
                                {
                                    StartImageDown(iType.Data, newimg, iType);
                                }

                            }
                        }
                        else
                        {
                            // 一次请求数据
                            System.Collections.Generic.List<ApiItem> apiItems;
                            try
                            {
                                apiItems = JsonMapper.ToObject<System.Collections.Generic.List<ApiItem>>(resultstr);
                            }
                            catch
                            {
                                apiItems = null;
                            }
                            if (apiItems == null || apiItems.Count <= 0) return;
                            foreach (var apiItem in apiItems)
                            {
                                LiuXingData tag;
                                try
                                {
                                    tag = new LiuXingData
                                    {
                                        Name = apiItem.MovieName,
                                        Img =
                                            string.Format("http://i.vod.xunlei.com/req_screenshot?req_list={0}",
                                                apiItem.Gcid),
                                        HDs = "未知",
                                        Drl = new System.Collections.Generic.List<string> { apiItem.Url }
                                    };
                                }
                                catch (System.Exception)
                                {
                                    tag = null;
                                }
                                if (tag != null)
                                {
                                    zuiReDatas.Add(tag);
                                }
                            }
                            if (zuiReDatas.Count <= 0) return;
                            foreach (var zuiReData in zuiReDatas)
                            {
                                iType.Data = zuiReData;
                                StartList(zuiReData.Img, iType);
                            }
                        }
                        return;
                        #endregion
                    }
            }
        }
Exemple #37
0
        private void CheckVersionAsync()
        {
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();

                System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent(false);
                wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(DownloadDataCompletedCallback);

                System.Uri uri = new System.Uri(urlVersionFile);

                wc.DownloadDataAsync(uri, waiter);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #38
0
        ProtocolUpdateStatus Update(bool protocols)
        {
            lock (m_sync)
            {
                string backupPath = Path.Combine(GXCommon.ProtocolAddInsPath, "backup");
                if (!System.IO.Directory.Exists(backupPath))
                {
                    System.IO.Directory.CreateDirectory(backupPath);
                    Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(backupPath);
                }
                DataContractSerializer x = new DataContractSerializer(typeof(GXAddInList));
                GXAddInList localAddins;
                string path = Path.Combine(GXCommon.ProtocolAddInsPath, "updates.xml");
                ProtocolUpdateStatus status = ProtocolUpdateStatus.None;
                if (!System.IO.File.Exists(path))
                {
                    return status;
                }
                using (FileStream reader = new FileStream(path, FileMode.Open))
                {
                    localAddins = (GXAddInList)x.ReadObject(reader);
                }
                System.Net.WebClient client = new System.Net.WebClient();
                client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
                foreach (GXAddIn it in localAddins)
                {
                    if ((protocols && it.Type != GXAddInType.AddIn) ||
                            (!protocols && it.Type != GXAddInType.Application))
                    {
                        continue;
                    }
                    if (it.State == AddInStates.Download || it.State == AddInStates.Update)
                    {
                        string AddInPath = Path.Combine(GXCommon.ProtocolAddInsPath, it.File);
                        if (it.Type == GXAddInType.AddIn ||
                                it.Type == GXAddInType.None)
                        {
                            AddInPath = GXCommon.ProtocolAddInsPath;
                        }
                        else if (it.Type == GXAddInType.Application)
                        {
                            AddInPath = Path.GetDirectoryName(typeof(GXUpdateChecker).Assembly.Location);
                        }
                        else
                        {
                            throw new Exception(Resources.UnknownType + it.Type.ToString());
                        }
                        try
                        {
                            string ext = Path.GetExtension(it.File);
                            if (string.Compare(ext, ".zip", true) == 0 ||
                                    string.Compare(ext, ".msi", true) == 0)
                            {
                                Target = it;
                                string tmpPath = Path.Combine(System.IO.Path.GetTempPath(), it.File);
                                Downloaded.Reset();
                                if (string.Compare(ext, ".zip", true) == 0)
                                {
                                    client.DownloadDataAsync(new Uri("http://www.gurux.org/updates/" + it.File), tmpPath);
                                }
                                else //If .msi
                                {
                                    client.DownloadDataAsync(new Uri("http://www.gurux.org/Downloads/" + it.File), tmpPath);
                                }

                                while (!Downloaded.WaitOne(100))
                                {
                                    Application.DoEvents();
                                }
                                if (string.Compare(ext, ".zip", true) == 0)
                                {
                                    throw new ArgumentException("Zip is not supported");
                                }
                                else //If .msi
                                {
                                    Process msi = new Process();
                                    msi.StartInfo.FileName = "msiexec.exe";
                                    msi.StartInfo.Arguments = "/i \"" + tmpPath + "\" /qr";
                                    msi.Start();
                                }
                            }
                            else
                            {
                                AddInPath = Path.Combine(AddInPath, it.File);
                                System.IO.File.WriteAllBytes(AddInPath, client.DownloadData("http://www.gurux.org/updates/" + it.File));
                                Gurux.Common.GXFileSystemSecurity.UpdateFileSecurity(AddInPath);
                                System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(AddInPath);
                                System.Diagnostics.FileVersionInfo newVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(asm.Location);
                                it.Version = it.InstalledVersion = newVersion.FileVersion;
                            }
                        }
                        //If file is in use.
                        catch (System.IO.IOException)
                        {
                            string cachedPath = Path.Combine(GXCommon.ProtocolAddInsPath, "cached");
                            if (!Directory.Exists(cachedPath))
                            {
                                Directory.CreateDirectory(cachedPath);
                                Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(cachedPath);
                            }
                            cachedPath = Path.Combine(cachedPath, it.File);
                            System.IO.File.WriteAllBytes(cachedPath, client.DownloadData("http://www.gurux.org/updates/" + it.File));
                            Gurux.Common.GXFileSystemSecurity.UpdateFileSecurity(cachedPath);
                            AppDomain domain = AppDomain.CreateDomain("import", null, AppDomain.CurrentDomain.SetupInformation);
                            //Get version number and unload assmbly.
                            System.Reflection.Assembly asm = domain.Load(System.Reflection.AssemblyName.GetAssemblyName(cachedPath));
                            System.Diagnostics.FileVersionInfo newVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(asm.Location);
                            it.Version = it.InstalledVersion = newVersion.FileVersion;
                            AppDomain.Unload(domain);
                            status |= ProtocolUpdateStatus.Restart;
                        }
                        status |= ProtocolUpdateStatus.Changed;
                        it.State = AddInStates.Installed;
                    }
                }
                if ((status & ProtocolUpdateStatus.Changed) != 0)
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    settings.Encoding = System.Text.Encoding.UTF8;
                    settings.CloseOutput = true;
                    settings.CheckCharacters = false;
                    using (XmlWriter writer = XmlWriter.Create(path, settings))
                    {
                        x.WriteObject(writer, localAddins);
                        writer.Close();
                    }
                    Gurux.Common.GXFileSystemSecurity.UpdateFileSecurity(path);
                    //TODO: GXDeviceList.UpdateProtocols();
                }
                return status;
            }
        }
Exemple #39
0
        public static void CheckUpdateStatus(string url,string xmlFileName,string zipFileName)
        {
            Ezhu.AutoUpdater.Lib.Constants.RemoteUrl = url;
            Ezhu.AutoUpdater.Lib.Constants.XmlFileName = xmlFileName;
            Ezhu.AutoUpdater.Lib.Constants.ZipFileName = zipFileName;
            System.Threading.ThreadPool.QueueUserWorkItem((s) =>
            {
                var client = new System.Net.WebClient();
                client.DownloadDataCompleted += (x, y) =>
                {
                    try
                    {
                        MemoryStream stream = new MemoryStream(y.Result);

                        XDocument xDoc = XDocument.Load(stream);
                        UpdateInfo updateInfo = new UpdateInfo();
                        XElement root = xDoc.Element("UpdateInfo");
                        updateInfo.AppName = root.Element("AppName").Value;
                        updateInfo.AppVersion = root.Element("AppVersion").Value;
                        updateInfo.RequiredMinVersion = root.Element("RequiredMinVersion").Value;
                        updateInfo.Desc = root.Element("Desc").Value;
                        updateInfo.MD5 = Guid.NewGuid().ToString();
                        updateInfo.UrlZip = Ezhu.AutoUpdater.Lib.Constants.RemoteUrl + Ezhu.AutoUpdater.Lib.Constants.ZipFileName;

                        stream.Close();
                        Updater.Instance.StartUpdate(updateInfo);
                    }
                    catch
                    { }
                };
                client.DownloadDataAsync(new Uri(Ezhu.AutoUpdater.Lib.Constants.RemoteUrl + Ezhu.AutoUpdater.Lib.Constants.XmlFileName));

            });
        }
        public void DownloadUpdateFile(string urlzip)
        {
            string url = urlzip;
            var client = new System.Net.WebClient();
            client.DownloadProgressChanged += (sender, e) =>
            {
                UpdateProcess(e.BytesReceived, e.TotalBytesToReceive);
            };
            client.DownloadDataCompleted += (sender, e) =>
            {
                string zipFilePath = System.IO.Path.Combine(updateFileDir, "update.zip");
                byte[] data = e.Result;
                BinaryWriter writer = new BinaryWriter(new FileStream(zipFilePath, FileMode.OpenOrCreate));
                writer.Write(data);
                writer.Flush();
                writer.Close();

                System.Threading.ThreadPool.QueueUserWorkItem((s) =>
                {
                    Action f = () =>
                    {
                       txtProcess.Text = "开始更新程序...";
                    };
                    this.Dispatcher.Invoke(f);

                    string tempDir = System.IO.Path.Combine(updateFileDir, "temp");
                    if (!Directory.Exists(tempDir))
                    {
                        Directory.CreateDirectory(tempDir);
                    }
                    UnZipFile(zipFilePath, tempDir);

                    //移动文件
                    //App
                    if(Directory.Exists(System.IO.Path.Combine(tempDir)))
                    {
                        CopyDirectory(System.IO.Path.Combine(tempDir),appDir);
                    }

                    f = () =>
                    {
                        txtProcess.Text = "更新完成!";

                        try
                        {
                            //清空缓存文件夹
                            string rootUpdateDir = updateFileDir.Substring(0, updateFileDir.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
                            System.IO.Directory.Delete(rootUpdateDir, true);
                        }
                        catch (Exception ex)
                        {
                        }

                    };
                    this.Dispatcher.Invoke(f);

                    try
                    {
                        f = () =>
                        {
                            AlertWin alert = new AlertWin("更新完成,是否现在启动软件?") { WindowStartupLocation = WindowStartupLocation.CenterOwner, Owner = this };
                            alert.Title = "更新完成";
                            alert.Loaded += (ss, ee) =>
                            {
                                alert.YesButton.Width = 40;
                                alert.NoButton.Width = 40;
                            };
                            alert.Width=300;
                            alert.Height = 200;
                            alert.ShowDialog();
                            if (alert.YesBtnSelected)
                            {
                                //启动软件
                                string exePath = System.IO.Path.Combine(appDir, callExeName + ".exe");
                                System.IO.File.AppendAllText("d:\\1.txt", "启动软件(exePath):" + exePath);
                                var info = new System.Diagnostics.ProcessStartInfo(exePath);
                                info.UseShellExecute = true;
                                info.WorkingDirectory = appDir;// exePath.Substring(0, exePath.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
                                System.Diagnostics.Process.Start(info);
                            }
                            else
                            {

                            }
                            this.Close();
                        };
                        this.Dispatcher.Invoke(f);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                    }
                });

            };
            client.DownloadDataAsync(new Uri(url));
        }