static public bool HandleException(Exception exception, TextBox outputField, MainPage rootPage)
        {
            SyndicationErrorStatus status = SyndicationError.GetStatus(exception.HResult);

            if (status != SyndicationErrorStatus.Unknown)
            {
                outputField.Text += "The response content is not valid. " +
                                    "Please make sure to use a URI that points to an Atom feed.\r\n";
            }
            else
            {
                WebErrorStatus webError = WebError.GetStatus(exception.HResult);

                if (webError == WebErrorStatus.Unauthorized)
                {
                    outputField.Text += "Incorrect username or password.\r\n";
                }
                else if (webError == WebErrorStatus.Unknown)
                {
                    // Neither a syndication nor a web error.
                    return(false);
                }
            }

            rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);

            return(true);
        }
Ejemplo n.º 2
0
        private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
        {
            var rtWebSocket = new WinRTWebSocket();

            _innerWebSocket = rtWebSocket;

            try
            {
                // Change internal state to 'connected' to enable the other methods
                if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting)
                {
                    // Aborted/Disposed during connect.
                    throw new ObjectDisposedException(GetType().FullName);
                }

                await rtWebSocket.ConnectAsync(uri, cancellationToken, Options);
            }
            catch (Exception ex)
            {
                WebErrorStatus     status = RTWebSocketError.GetStatus(ex.HResult);
                var                inner  = new Exception(status.ToString(), ex);
                WebSocketException wex    = new WebSocketException(SR.net_webstatus_ConnectFailure, inner);
                if (Logging.On)
                {
                    Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex);
                }

                throw wex;
            }
        }
Ejemplo n.º 3
0
        public static string BuildWebSocketError(Exception ex)
        {
            ex = ex.GetBaseException();

            if ((uint)ex.HResult == 0x800C000EU)
            {
                // INET_E_SECURITY_PROBLEM - our custom certificate validator rejected the request.
                return("Error: Rejected by custom certificate validation.");
            }

            WebErrorStatus status = WebSocketError.GetStatus(ex.HResult);

            // Normally we'd use the HResult and status to test for specific conditions we want to handle.
            // In this sample, we'll just output them for demonstration purposes.
            switch (status)
            {
            case WebErrorStatus.CannotConnect:
            case WebErrorStatus.NotFound:
            case WebErrorStatus.RequestTimeout:
                return("Cannot connect to the server. Please make sure " +
                       "to run the server setup script before running the sample.");

            case WebErrorStatus.Unknown:
                return("COM error: " + ex.HResult);

            default:
                return("Error: " + status);
            }
        }
Ejemplo n.º 4
0
        public async Task <byte[]> ReceiveMessageFromWebSocketClientAsync(object webSocketClient, byte[] buffer, CancellationToken token)
        {
            var websocket = webSocketClient as StreamWebSocket;

            if (websocket == null)
            {
                throw new InvalidCastException("cannot cast webSocketClient object to StreamWebSocket");
            }
            try
            {
                Stream readStream = websocket.InputStream.AsStreamForRead();
                //await readStream.ReadAsync(buffer.AsBuffer(), Convert.ToUInt16(buffer.Length), InputStreamOptions.Partial);
                while (true)
                {
                    int bytesReceived = 0;
                    Debug.WriteLine("local address: " + websocket.Information.LocalAddress);
                    int read = await readStream.ReadAsync(buffer, 0, buffer.Length, token);

                    bytesReceived += read;
                    bytesReceived -= 4;
                    if (read < 4)
                    {
                        continue;           // TODO: potential problem?
                    }
                    var lengthByte = new byte[4];
                    Array.Copy(buffer, lengthByte, 4);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(lengthByte);
                    }
                    var length = BitConverter.ToInt32(lengthByte, 0);
                    if (length == 0)
                    {
                        continue;              // TODO: empty message?
                    }
                    byte[] incomingData = new byte[length];
                    Array.Copy(buffer, 4, incomingData, 0, read - 4);
                    int index = read - 4;
                    var rest  = length - (read - 4);

                    while (rest > 0)
                    {
                        read = await readStream.ReadAsync(buffer, 0, buffer.Length);

                        bytesReceived += read;
                        rest          -= read;
                        Array.Copy(buffer, 0, incomingData, index, read);
                        index += read;
                    }

                    return(incomingData);
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                Debug.WriteLine("Exception during message sending: " + ex.Message);
                throw;
            }
        }
Ejemplo n.º 5
0
        public async void ConnectAsync()
        {
            if (socket == null)
            {
                Debug.Log("Configure MessageWebSocket");
                ConfigureWebSocket(url, headers);
            }
            AttachHandlers();
            try {
                await socket.ConnectAsync(uri);

                dataWriter = new DataWriter(socket.OutputStream);
                isOpened   = true;
                RaiseOpen();
            } catch (Exception ex) {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                if (status.Equals(WebErrorStatus.Unknown))
                {
                    Debug.LogError("An unknown WebErrorStatus exception occurred.");
                }
                else
                {
                    RaiseError("Error: MessageWebSocket failed to connect: " + status.ToString());
                }
            }
        }
Ejemplo n.º 6
0
 private void HandleOnMessage(object sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     if (OnMessage == null)
     {
         return;
     }
     try {
         using (var reader = args.GetDataReader()) {
             if (args.MessageType == SocketMessageType.Utf8)
             {
                 string text = reader.ReadString(reader.UnconsumedBufferLength);
                 OnMessage.Invoke(sender, new WebSocketMessageEventArgs(text));
             }
             else if (args.MessageType == SocketMessageType.Binary)
             {
                 byte[] data = new byte[reader.UnconsumedBufferLength];
                 reader.ReadBytes(data);
                 OnMessage.Invoke(sender, new WebSocketMessageEventArgs(data));
             }
         }
     } catch (Exception ex) {
         WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
         RaiseError(status.ToString() + " " + ex.Message);
     }
 }
Ejemplo n.º 7
0
#pragma warning disable 0672, 618
            public override void OnReceivedError(Android.Webkit.WebView view, [GeneratedEnum] ClientError errorCode, string description, string failingUrl)
            {
                _webViewSuccess = false;
                _webErrorStatus = ConvertClientError(errorCode);

                base.OnReceivedError(view, errorCode, description, failingUrl);
            }
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                MarshalText(OutputField, "Message Received; Type: " + args.MessageType + "\r\n");
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    MarshalText(OutputField, read + "\r\n");
                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                MarshalText(OutputField, "Error: " + status + "\r\n");

                MarshalText(OutputField, ex.Message + "\r\n");
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Play preinstalled recording button click handler
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="args">Event arguments</param>
        private async void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            SenseRecording recording       = null;
            WebErrorStatus exceptionDetail = new WebErrorStatus();

            try
            {
                recording = await SenseRecording.LoadFromUriAsync(new Uri("https://github.com/Microsoft/steps/raw/master/Steps/Simulations/short%20walk.txt"));
            }
            catch (Exception ex)
            {
                exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
            }
            if (exceptionDetail == WebErrorStatus.HostNameNotResolved)
            {
                MessageDialog dialog = new MessageDialog("Check your network connection. Host name could not be resolved.", "Information");
                await dialog.ShowAsync();
            }
            if (recording != null)
            {
                _stepCounter = await StepCounterSimulator.GetDefaultAsync(recording);

                MessageDialog dialog = new MessageDialog(
                    "Recorded sensor type: " + recording.Type.ToString() +
                    "\r\nDescription: " + recording.Description +
                    "\r\nRecording date: " + recording.StartTime.ToString() +
                    "\r\nDuration: " + recording.Duration.ToString(),
                    "Recording info"
                    );
                await dialog.ShowAsync();
            }
        }
Ejemplo n.º 10
0
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (streamWebSocket != null)
                {
                    rootPage.NotifyUser("Stopping", NotifyType.StatusMessage);
                    streamWebSocket.Close(1000, "Closed due to user request.");
                    streamWebSocket = null;
                }
                else
                {
                    rootPage.NotifyUser("There is no active socket to stop.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                rootPage.NotifyUser("Error: " + status, NotifyType.ErrorMessage);

                OutputField.Text += ex.Message + "\r\n";
            }
        }
Ejemplo n.º 11
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            foreach (Contact item in context.Contacts)
            {
                Master.Items.Add(item.Name);
            }

            this.messageWebSocket = new MessageWebSocket();

            // In this example, we send/receive a string, so we need to set the MessageType to Utf8.
            this.messageWebSocket.Control.MessageType = SocketMessageType.Utf8;

            this.messageWebSocket.MessageReceived += WebSocket_MessageReceived;
            this.messageWebSocket.Closed          += WebSocket_Closed;

            try
            {
                connectTask = this.messageWebSocket.ConnectAsync(new Uri("wss://echo.websocket.org")).AsTask();
            }
            catch (Exception ex)
            {
                WebErrorStatus webErrorStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                // Add additional code here to handle exceptions.
            }
        }
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            string errorMsg = null;

            if (download == null)
            {
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error));

                errorMsg = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", title, error);
            }
            else
            {
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.Guid, title, error));
                errorMsg = String.Format(CultureInfo.CurrentCulture, "{0} - {1}: {2}", download.Guid, title, error);
            }

            // Event calling for status msg
            DownloadStatusMessageChanged?.Invoke("Error", download.ResultFile.Name);

            return(true);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initialize the view model by enumerating all existing downloads.
        /// </summary>
        public override async Task Initialize()
        {
            if (_activeDownloads != null)
            {
                return;
            }

            IsDownloading    = false;
            IsIndeterminate  = false;
            Description      = null;
            InstallationStep = null;
            _activeDownloads = new ConcurrentDictionary <string, DownloadOperation>();

            IEnumerable <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                telemetry.TrackException(ex, new Dictionary <string, string> {
                    { "Scenario", "InitializeDownloads" }
                });
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                await QuranApp.NativeProvider.ShowErrorMessageBox("Error getting active downloads: " + error.ToString());

                return;
            }

            if (downloads.Any())
            {
                await HandleDownloadsAsync(downloads.ToList(), false);
            }
        }
Ejemplo n.º 14
0
    public async void SendString(string data)
    {
        try
        {
            socket.Control.MessageType = SocketMessageType.Utf8;

            messageWriter.WriteString(data);
            await messageWriter.StoreAsync();
        }
        catch (Exception ex)
        {
            WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

            switch (status)
            {
            case WebErrorStatus.OperationCanceled:
                Debug.LogError("Background write canceled.");
                break;

            default:
                Debug.LogError("Error: " + status);
                Debug.LogError(ex.Message);
                break;
            }
        }
    }
Ejemplo n.º 15
0
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Message Received; Type: " + args.MessageType);
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);

                    //Convert to JSON
                    if (read != "")
                    {
                    }
                    System.Diagnostics.Debug.WriteLine(read);
                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                System.Diagnostics.Debug.WriteLine("Error: " + status);

                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 16
0
        private void OnError(WKWebView webView, WKNavigation navigation, NSError error)
        {
            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Error))
            {
                this.Log().ErrorFormat("Could not navigate to web page: {0}", error.LocalizedDescription);
            }

            WebErrorStatus status = WebErrorStatus.OperationCanceled;

            _errorMap.TryGetValue((NSUrlError)(int)error.Code, out status);

            if (status != WebErrorStatus.OperationCanceled)
            {
                Uri uri;
                //If the url which failed to load is available in the user info, use it because with the WKWebView the
                //field webView.Url is equal to last successfully loaded URL and not to the failed URL
                var failedUrl = error.UserInfo.UnoGetValueOrDefault(new NSString("NSErrorFailingURLStringKey")) as NSString;
                if (failedUrl != null)
                {
                    uri = new Uri(failedUrl);
                }
                else
                {
                    uri = webView.Url?.ToUri() ?? _parentWebView.Source;
                }

                _parentWebView.OnNavigationFailed(new WebViewNavigationFailedEventArgs()
                {
                    Uri            = uri,
                    WebErrorStatus = status
                });

                _parentWebView.OnComplete(uri, false, status);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Найти все фоновые загрузки и обработать их.
        /// </summary>
        public async void DiscoverActiveDownloads()
        {
            lock (_lockObject)
            {
                if (_downloadsAttached)
                {
                    return;
                }
                _downloadsAttached = true;
            }

            IsLoading = true;

            await Task.Run(async() =>
            {
                IReadOnlyList <DownloadOperation> downloads = null;

                try { downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup); }
                catch (Exception ex)
                {
                    WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                    _logService.LogText($"Getting downloads error - {error}\n{ex.ToString()}");
                }

                if (downloads != null && downloads.Count > 0)
                {
                    for (int i = 0; i < downloads.Count; i++)
                    {
                        HandleDownloadAsync(downloads[i], false);
                    }
                }
            });

            IsLoading = false;
        }
        private async void GetFeed_Click(object sender, RoutedEventArgs e)
        {
            outputField.Text = "";

            // By default 'FeedUri' is disabled and URI validation is not required. When enabling the text box
            // validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(FeedUri.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Error: Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            SyndicationClient client = new SyndicationClient();

            client.BypassCacheOnRetrieve = true;

            // Although most HTTP servers do not require User-Agent header, others will reject the request or return
            // a different response if this header is missing. Use SetRequestHeader() to add custom headers.
            client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            rootPage.NotifyUser("Downloading feed...", NotifyType.StatusMessage);
            outputField.Text = "Downloading feed: " + uri.ToString() + "\r\n";

            try
            {
                currentFeed = await client.RetrieveFeedAsync(uri);

                rootPage.NotifyUser("Feed download complete.", NotifyType.StatusMessage);

                DisplayFeed();
            }
            catch (Exception ex)
            {
                SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult);
                if (status == SyndicationErrorStatus.InvalidXml)
                {
                    outputField.Text += "An invalid XML exception was thrown. " +
                                        "Please make sure to use a URI that points to a RSS or Atom feed.";
                }

                if (status == SyndicationErrorStatus.Unknown)
                {
                    WebErrorStatus webError = WebError.GetStatus(ex.HResult);

                    if (webError == WebErrorStatus.Unknown)
                    {
                        // Neither a syndication nor a web error. Rethrow.
                        throw;
                    }
                }

                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 19
0
        private async Task <bool> ValidateApplicationUsage()
        {
            // Hanu Epoch time.
            DateTime lastValidationTime = new DateTime(2011, 11, 4);
            DateTime now = DateTime.Now;

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            if (localSettings.Values["ValidationTime"] != null)
            {
                // This is not the first use.
                lastValidationTime = DateTime.Parse(localSettings.Values["ValidationTime"].ToString());
            }

            TimeSpan interval = now.Subtract(lastValidationTime);

            if (interval.Days > 7)
            {
                // Validate again

                try
                {
                    using (HttpClient hc = new HttpClient())
                    {
                        Uri address = new Uri("http://apps.ayansh.com/HanuGCM/Validate.php");

                        var values = new List <KeyValuePair <string, string> >
                        {
                            new KeyValuePair <string, string>("blogurl", _blogURL),
                        };

                        HttpFormUrlEncodedContent postContent = new HttpFormUrlEncodedContent(values);
                        HttpResponseMessage       response    = await hc.PostAsync(address, postContent).AsTask();

                        string response_text = await response.Content.ReadAsStringAsync();

                        if (response_text.Equals("Success"))
                        {
                            // Set Validation time as now
                            localSettings.Values["ValidationTime"] = now.ToString();
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
                catch (Exception e)
                {
                    WebErrorStatus error = WebError.GetStatus(e.GetBaseException().HResult);
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    System.Diagnostics.Debug.WriteLine(error.ToString());
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 20
0
        /// <summary>
        ///  Raw websocket messages from server - convert to message types and call subscribers of events and/or callbacks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void mws_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            string read = null;

            try
            {
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    read = reader.ReadString(reader.UnconsumedBufferLength);
                    Debug.WriteLine("[SOCKET_IO]: < " + read);
                }
                IMessage iMsg = SocketIOClient.Messages.Message.Factory(read);

                if (iMsg.Event == "responseMsg")
                {
                    Debug.WriteLine(string.Format("InvokeOnEvent: {0}", iMsg.RawMessage));
                }

                switch (iMsg.MessageType)
                {
                case SocketIOMessageTypes.Disconnect:
                    this.OnMessageEvent(iMsg);
                    if (string.IsNullOrWhiteSpace(iMsg.Endpoint))     // Disconnect the whole socket
                    {
                        this.Close();
                    }
                    break;

                case SocketIOMessageTypes.Heartbeat:
                    this.OnHeartBeatTimerCallback(null);
                    break;

                case SocketIOMessageTypes.Connect:
                case SocketIOMessageTypes.Message:
                case SocketIOMessageTypes.JSONMessage:
                case SocketIOMessageTypes.Event:
                case SocketIOMessageTypes.Error:
                    this.OnMessageEvent(iMsg);
                    break;

                case SocketIOMessageTypes.ACK:
                    this.registrationManager.InvokeCallBack(iMsg.AckId, iMsg.Json);
                    break;

                default:
                    Debug.WriteLine("unknown mws message Received...");
                    break;
                }
            }
            catch (Exception ex) // For debugging
            {
                this.mwsState = WebSocketState.Closed;
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                Debug.WriteLine("mws_MessageReceived::exception : " + status);
                this.OnErrorEvent(this, new ErrorEventArgs(status.ToString(), ex));
                //this.Close();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 监视指定的后台下载任务
        /// </summary>
        /// <param name="download">后台下载任务</param>
        private async Task HandleDownloadAsync(DownloadManage.HandleModel model)
        {
            try
            {
                DownloadProgress(model.downOp);
                //进度监控
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await model.downOp.AttachAsync().AsTask(model.cts.Token, progressCallback);

                //保存任务信息
                //  StorageFolder folder = ApplicationData.Current.LocalFolder;
                StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists);

                StorageFile file = await DowFolder.GetFileAsync(model.Guid + ".bili");

                //用Url编码是因为不支持读取中文名
                //含会出现:在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。错误
                string        path   = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);

                StorageFile files = await folder.CreateFileAsync(model.Guid + ".json", CreationCollisionOption.OpenIfExists); //await StorageFile.GetFileFromPathAsync(path+@"\" + model.Guid + ".json");

                string json = await FileIO.ReadTextAsync(files);

                DownloadManage.DownModel info = JsonConvert.DeserializeObject <DownloadManage.DownModel>(json);
                info.downloaded = true;
                string      jsonInfo  = JsonConvert.SerializeObject(info);
                StorageFile fileWrite = await folder.CreateFileAsync(info.Guid + ".json", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteTextAsync(fileWrite, jsonInfo);

                //移除正在监控
                HandleList.Remove(model.downModel.Guid);
                GetDownOk_New();
            }
            catch (TaskCanceledException)
            {
                //取消通知
                //ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
                //XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
                //XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                //IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                //((XmlElement)toastNode).SetAttribute("duration", "short");
                //toastTextElements[0].AppendChild(toastXml.CreateTextNode(String.Format("取消任务{0}", model.downModel.title)));
                //ToastNotification toast = new ToastNotification(toastXml);
                //ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                return;
            }
            finally
            {
                list_Downing.Items.Remove(model);
            }
        }
Ejemplo n.º 22
0
        private void OnNavigationFailed(WebErrorStatus webErrorStatus)
        {
            VisualStateManager.GoToState(this, LoadedStateName, true);

            if (_titleBar != null)
            {
                _titleBar.Text = webErrorStatus.ToString();
            }
        }
Ejemplo n.º 23
0
        public bool IsExceptionHandled(string title, Exception ex)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 24
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Starting... ");
            bool connecting = true;

            if (String.IsNullOrEmpty(playerName.Text))
            {
                System.Diagnostics.Debug.WriteLine("Speler naam is niet aangegeven!");
                return;
            }

            try
            {
                if (messageWebSocket == null) //Connection is not there yet.. lets make the bloody connection!
                {
                    Uri server;
                    if (!TryGetUri("ws://192.168.178.105:4141", out server))
                    {
                        return;
                    }

                    //Server is now build..
                    messageWebSocket = new MessageWebSocket();
                    messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
                    messageWebSocket.MessageReceived    += MessageReceived;

                    // Dispatch close event on UI thread. This allows us to avoid synchronizing access to messageWebSocket.
                    messageWebSocket.Closed += async(senderSocket, args) =>
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Closed(senderSocket, args));
                    };

                    await messageWebSocket.ConnectAsync(server);

                    messageWriter = new DataWriter(messageWebSocket.OutputStream);
                    messageWriter.WriteString(playerName.Text);


                    await messageWriter.StoreAsync();
                }
                else if (messageWriter != null)
                {
                    messageWriter.WriteString(playerName.Text);
                    await messageWriter.StoreAsync();
                }
            } catch (Exception er)
            {
                if (connecting && messageWebSocket != null)
                {
                    messageWebSocket.Dispose();
                    messageWebSocket = null;
                }
                WebErrorStatus status = WebSocketError.GetStatus(er.GetBaseException().HResult);
            }
        }
Ejemplo n.º 25
0
        public static string HttpClientExceptionHandler(int code, Exception ex)
        {
            WebErrorStatus error = WebError.GetStatus(code);

            if (error == WebErrorStatus.CannotConnect ||
                error == WebErrorStatus.CertificateCommonNameIsIncorrect ||
                error == WebErrorStatus.CertificateContainsErrors ||
                error == WebErrorStatus.CertificateExpired ||
                error == WebErrorStatus.CertificateIsInvalid ||
                error == WebErrorStatus.CertificateRevoked)
            {
                return("Error establishing a secure connection. This is usually caused by antivirus, firewall or VPN software, or problems with your ISP.");
            }
            else if (error == WebErrorStatus.Timeout)
            {
                return("The connection to AnkiWeb timed out. Please check your network connection and try again.");
            }
            else if (error == WebErrorStatus.InternalServerError)
            {
                return("AnkiWeb encountered an error. Please try again in a few minutes, and if the problem persists, please file a bug report.");
            }
            else if (error == WebErrorStatus.NotImplemented)
            {
                return("Please upgrade to the latest version of Anki.");
            }
            else if (error == WebErrorStatus.BadGateway)
            {
                return("AnkiWeb is under maintenance. Please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.ServiceUnavailable)
            {
                return("AnkiWeb is too busy at the moment. Please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.GatewayTimeout)
            {
                return("504 gateway timeout error received. Please try temporarily disabling your antivirus.");
            }
            else if (error == WebErrorStatus.Conflict)
            {
                return("Only one client can access AnkiWeb at a time. If a previous sync failed, please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.ProxyAuthenticationRequired)
            {
                return("Proxy authentication required.");
            }
            else if (error == WebErrorStatus.RequestEntityTooLarge)
            {
                return("Your collection or a media file is too large to sync.");
            }
            else
            {
                return(String.Format("Error Code: {0:X}! {1}", ex.HResult, ex.Message));
            }
        }
Ejemplo n.º 26
0
 private async Task DisplayCounterUrl()
 {
     if (counter > 0 && counter <= urlsToCapture.Count)
     {
         currentURL         = urlsToCapture[counter - 1];
         counterBox.Text    = counter.ToString();
         counterView.Text   = "/" + urlsToCapture.Count;
         urlView.Text       = currentURL;
         currentErrorStatus = await RefreshCurrentUrl();
     }
 }
        private void LoadFailed(WebView webView, WebErrorStatus status, string message)
        {
            var reactContext = webView.GetReactContext();

            reactContext.GetNativeModule <UIManagerModule>()
            .EventDispatcher
            .DispatchEvent(
                new WebViewLoadingErrorEvent(
                    webView.GetTag(),
                    status,
                    message));
        }
Ejemplo n.º 28
0
        /// 监视指定的后台下载任务
        /// </summary>
        /// <param name="download">后台下载任务</param>
        private async Task HandleDownloadAsync(DownloadModel model)
        {
            try
            {
                DownloadProgress(model.handel.downOp);
                //进度监控
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await model.handel.downOp.AttachAsync().AsTask(model.handel.cts.Token, progressCallback);

                model.videoinfo.downstatus = true;
                var PartFolder = await StorageFolder.GetFolderFromPathAsync(model.videoinfo.folderPath);

                StorageFile sefile = await PartFolder.CreateFileAsync(model.videoinfo.mid + ".json", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(sefile, JsonConvert.SerializeObject(model.videoinfo));

                ////保存任务信息
                ////  StorageFolder folder = ApplicationData.Current.LocalFolder;
                //StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists);
                //StorageFile file = await DowFolder.GetFileAsync(model.Guid + ".bili");
                ////用Url编码是因为不支持读取中文名
                ////含会出现:在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。错误
                //string path = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                //StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                //StorageFile files = await folder.CreateFileAsync(model.Guid + ".json", CreationCollisionOption.OpenIfExists); //await StorageFile.GetFileFromPathAsync(path+@"\" + model.Guid + ".json");
                //string json = await FileIO.ReadTextAsync(files);
                //DownloadManage.DownModel info = JsonConvert.DeserializeObject<DownloadManage.DownModel>(json);
                //info.downloaded = true;
                //string jsonInfo = JsonConvert.SerializeObject(info);
                //StorageFile fileWrite = await folder.CreateFileAsync(info.Guid + ".json", CreationCollisionOption.ReplaceExisting);
                //await FileIO.WriteTextAsync(fileWrite, jsonInfo);
                ////移除正在监控
                SendToast("《" + model.videoinfo.title + " " + model.videoinfo.partTitle + "》下载完成");
                HandleList.Remove(model.videoinfo.downGUID);
                list_Downing.Items.Remove(model);
                //GetDownOk_New();
                GetDownOk();
                // list_Downing.Items.Remove(model);
            }
            catch (TaskCanceledException)
            {
                //取消通知
                SendToast("取消任务《" + model.videoinfo.title + " " + model.videoinfo.partTitle + "》");
                list_Downing.Items.Remove(model);
                GetDownOk();
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                return;
            }
        }
Ejemplo n.º 29
0
        internal static void DisplayWebError(MainPage rootPage, Exception exception)
        {
            WebErrorStatus webErrorStatus = WebError.GetStatus(exception.HResult);

            if (webErrorStatus == WebErrorStatus.Unknown)
            {
                rootPage.NotifyUser("Unknown Error: " + exception.Message, NotifyType.ErrorMessage);
            }
            else
            {
                rootPage.NotifyUser("Web Error: " + webErrorStatus, NotifyType.ErrorMessage);
            }
        }
 public WebViewLoadingErrorEvent(int viewTag, WebErrorStatus error, string description)
     : base(viewTag, TimeSpan.FromTicks(Environment.TickCount))
 {
     _code = (double)error;
     if (description == null)
     {
         _description = ErrorString(error);
     }
     else
     {
         _description = description;
     }
 }
 public WebViewLoadingErrorEvent(int viewTag, WebErrorStatus error, string description)
     : base(viewTag, TimeSpan.FromTicks(Environment.TickCount))
 {
     _code = (double)error;
     if (description == null)
     {
         _description = ErrorString(error);
     }
     else
     {
         _description = description;
     }
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Play preinstalled recording button click handler
 /// </summary>
 /// <param name="sender">Sender object</param>
 /// <param name="args">Event arguments</param>
 private async void LoadButton_Click(object sender, RoutedEventArgs e)
 {
     SenseRecording recording = null;
     WebErrorStatus exceptionDetail = new WebErrorStatus();
     try
     {
         recording = await SenseRecording.LoadFromUriAsync(new Uri("https://github.com/Microsoft/steps/raw/master/Steps/Simulations/short%20walk.txt"));
     }
     catch (Exception ex)
     {
         exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
     }
     if (exceptionDetail == WebErrorStatus.HostNameNotResolved)
     {
         MessageDialog dialog = new MessageDialog("Check your network connection. Host name could not be resolved.", "Information");
         await dialog.ShowAsync();
     }
     if (recording != null)
     {
         _stepCounter = await StepCounterSimulator.GetDefaultAsync(recording);
         MessageDialog dialog = new MessageDialog(
         "Recorded sensor type: " + recording.Type.ToString() +
         "\r\nDescription: " + recording.Description +
         "\r\nRecording date: " + recording.StartTime.ToString() +
         "\r\nDuration: " + recording.Duration.ToString(),
         "Recording info"
         );
         await dialog.ShowAsync();
     }
 }
Ejemplo n.º 33
0
        private void OnNavigationFailed(WebErrorStatus webErrorStatus)
        {
            VisualStateManager.GoToState(this, LoadedStateName, true);

            if (_titleBar != null)
            {
                _titleBar.Text = webErrorStatus.ToString();
            }
        }
 private string ErrorString(WebErrorStatus status)
 {
     switch (status)
     {
         case WebErrorStatus.Unknown:
             return "An unknown error has occurred.";
         case WebErrorStatus.CertificateCommonNameIsIncorrect:
             return "The SSL certificate common name does not match the web address.";
         case WebErrorStatus.CertificateExpired:
             return "The SSL certificate has expired.";
         case WebErrorStatus.CertificateContainsErrors:
             return "The SSL certificate contains errors.";
         case WebErrorStatus.CertificateRevoked:
             return "The SSL certificate has been revoked.";
         case WebErrorStatus.CertificateIsInvalid:
             return "The SSL certificate is invalid.";
         case WebErrorStatus.ServerUnreachable:
             return "The server is not responding.";
         case WebErrorStatus.Timeout:
             return "The connection has timed out.";
         case WebErrorStatus.ErrorHttpInvalidServerResponse:
             return "The server returned an invalid or unrecognized response.";
         case WebErrorStatus.ConnectionAborted:
             return "The connection was aborted.";
         case WebErrorStatus.ConnectionReset:
             return "The connection was reset.";
         case WebErrorStatus.Disconnected:
             return "The connection was ended.";
         case WebErrorStatus.HttpToHttpsOnRedirection:
             return "Redirected from a location to a secure location.";
         case WebErrorStatus.HttpsToHttpOnRedirection:
             return "Redirected from a secure location to an unsecure location.";
         case WebErrorStatus.CannotConnect:
             return "Cannot connect to destination.";
         case WebErrorStatus.HostNameNotResolved:
             return "Could not resolve provided host name.";
         case WebErrorStatus.OperationCanceled:
             return "The operation was canceled.";
         case WebErrorStatus.RedirectFailed:
             return "The request redirect failed.";
         case WebErrorStatus.UnexpectedStatusCode:
             return "An unexpected status code indicating a failure was received.";
         case WebErrorStatus.UnexpectedRedirection:
             return "A request was unexpectedly redirected.";
         case WebErrorStatus.UnexpectedClientError:
             return "An unexpected client-side error has occurred.";
         case WebErrorStatus.UnexpectedServerError:
             return "An unexpected server-side error has occurred.";
         case WebErrorStatus.MultipleChoices:
             return "The requested URL represents a high level grouping of which lower level selections need to be made.";
         case WebErrorStatus.MovedPermanently:
             return "This and all future requests should be directed to the given URI.";
         case WebErrorStatus.Found:
             return "The resource was found but is available in a location different from the one included in the request.";
         case WebErrorStatus.SeeOther:
             return "The response to the request can be found under another URI using a GET method.";
         case WebErrorStatus.NotModified:
             return "Indicates the resource has not been modified since last requested.";
         case WebErrorStatus.UseProxy:
             return "The requested resource must be accessed through the proxy given by the Location field.";
         case WebErrorStatus.TemporaryRedirect:
             return "The requested resource resides temporarily under a different URI.";
         case WebErrorStatus.BadRequest:
             return "The request cannot be fulfilled due to bad syntax.";
         case WebErrorStatus.Unauthorized:
             return "Authentication has failed or credentials have not yet been provided.";
         case WebErrorStatus.PaymentRequired:
             return "Reserved.";
         case WebErrorStatus.Forbidden:
             return "The server has refused the request.";
         case WebErrorStatus.NotFound:
             return "The requested resource could not be found but may be available again in the future.";
         case WebErrorStatus.MethodNotAllowed:
             return " A request was made of a resource using a request method not supported by that resource.";
         case WebErrorStatus.NotAcceptable:
             return "The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.";
         case WebErrorStatus.ProxyAuthenticationRequired:
             return "The client must first authenticate itself with the proxy.";
         case WebErrorStatus.RequestTimeout:
             return "The server timed out waiting for the request.";
         case WebErrorStatus.Conflict:
             return "Indicates that the request could not be processed because of conflict in the request.";
         case WebErrorStatus.Gone:
             return "Indicates that the resource requested is no longer available and will not be available again.";
         case WebErrorStatus.LengthRequired:
             return "The request did not specify the length of its content, which is required by the requested resource.";
         case WebErrorStatus.PreconditionFailed:
             return "The server does not meet one of the preconditions that the requester put on the request.";
         case WebErrorStatus.RequestEntityTooLarge:
             return "The request is larger than the server is willing or able to process.";
         case WebErrorStatus.RequestUriTooLong:
             return "Provided URI length exceeds the maximum length the server can process.";
         case WebErrorStatus.UnsupportedMediaType:
             return "The request entity has a media type which the server or resource does not support.";
         case WebErrorStatus.RequestedRangeNotSatisfiable:
             return "The client has asked for a portion of the file, but the server cannot supply that portion.";
         case WebErrorStatus.ExpectationFailed:
             return "The server cannot meet the requirements of the Expect request-header field.";
         case WebErrorStatus.InternalServerError:
             return "A generic error message, given when no more specific message is suitable.";
         case WebErrorStatus.NotImplemented:
             return "The server either does not recognize the request method, or it lacks the ability to fulfill the request.";
         case WebErrorStatus.BadGateway:
             return "The server was acting as a gateway or proxy and received an invalid response from the upstream server.";
         case WebErrorStatus.ServiceUnavailable:
             return "The server is currently unavailable.";
         case WebErrorStatus.GatewayTimeout:
             return "The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.";
         case WebErrorStatus.HttpVersionNotSupported:
             return "The server does not support the HTTP protocol version used in the request.";
         default:
             return "An unknown error has occurred.";
     }
 }