public static IsHostReachable ( string host ) : bool | ||
host | string | |
Результат | bool |
async void AdRGButton_TouchUpInside(object sender, EventArgs e) { //Get current view controller var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } if (Reachability.IsHostReachable(Settings._baseDomain)) { SpecResponse specResponse = new SpecResponse(); var specification = await specResponse.GetSpecBySpecIDDesignationIDAsync(ad.SpecId, ad.DesignationId); if (specification.SpecId != 0) { MapViewController mapViewController = (MapViewController)vc.Storyboard.InstantiateViewController("MapViewController"); mapViewController.SpecFieldList = specification.SpecFieldDictionary[SpecTableViewSource._rangeSection]; vc.ShowDetailViewController(mapViewController, this); } } else { HelperMethods.SendBasicAlert("Connect to a Network", Settings._networkProblemMessage); } }
private async void SubmitButton_Clicked(object sender, EventArgs e) { if (AreAllMandatoryQuestionsCompleted()) { Dictionary <int, string> AllAnswers = GetAllAnswers(); ISurveyAnswerHandler SurveyAnswer = new SurveyAnswerHandler(); IAnswersHandler _QuestionAnswer = new AnswerHandler(); if (Reachability.IsHostReachable("http://www.google.co.uk")) { string SurveyAnswerId = ""; await Task.Run(() => SurveyAnswerId = SurveyAnswer.InsertSurveyAnswer(new cSurveyAnswer { Platform = Device.Idiom.ToString(), SurveyId = SurveyId, AppVersion = App.Version, SurveyVersion = SurveyVersion })); foreach (var QuestionAnswer in AllAnswers) { await Task.Run(() => _QuestionAnswer.InsertAnswer(new cAnswer { AnswerId = int.Parse(SurveyAnswerId), Answer = QuestionAnswer.Value, QuestionId = QuestionAnswer.Key, AnswerDateTime = DateTime.Now })); } await DisplayAlert("Message", "Thank You For Completing This Survey.", "OK"); await App.Current.MainPage.Navigation.PopModalAsync(); } } }
partial void FindOutButton_TouchUpInside(UIButton sender) { var date = DateTime.Parse(QueryDatePicker.Date.ToString()); if (date <= KnownFirstDayOff) { var dateErrorAlert = UIAlertController.Create("Invalid Date", $"Please choose a date after {KnownFirstDayOff.ToShortDateString()}.", UIAlertControllerStyle.Alert); dateErrorAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(dateErrorAlert, true, null); return; } StatusLabel.Hidden = true; StatusLabel.Text = "Please wait..."; StatusLabel.Hidden = false; if (CrossConnectivity.Current.IsConnected && Reachability.IsHostReachable(BaseUri)) { IsBroOffApiCall(date); } else { ClearLabels(); StatusLabel.Text = "Unable to connect to server."; StatusLabel.Hidden = false; } }
public Agenda(IntPtr handle) : base(handle) { Title = NSBundle.MainBundle.LocalizedString("Notícias", "Notícias"); var attrs = new UITextAttributes() { TextColor = UIColor.FromRGB(168, 0, 0), }; UITabBarItem.Appearance.SetTitleTextAttributes(attrs, state: UIControlState.Normal); View.BackgroundColor = UIColor.White; webView = new UIWebView(View.Bounds); webView.ScrollView.ContentInset = new UIEdgeInsets(0, 0, 45, 0); View.AddSubview(webView); webView.ScalesPageToFit = true; if (!Reachability.IsHostReachable("tum.pt")) { Reachability.InternetConnectionStatus(); UIAlertView alert = new UIAlertView(); alert.Title = "Sem ligação à rede"; alert.AddButton("Continuar"); alert.Message = "Não conseguirá usar a aplicação sem conexão à rede."; alert.Show(); } else { webView.LoadRequest(new NSUrlRequest(new NSUrl(url))); } }
async void FetchCopyright() { if (Reachability.IsHostReachable("www.google.com")) { try { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; var trans = GetTranslation(translation); var copyright = await BiblesDotOrg.GetCopyrightForTranslationAsync(trans); copyrightView.Text = copyright; } catch (Exception) { if (translation == Translation.MSG) { copyrightView.Text = "Copyright information not available. Please see messagebible.com for more information."; } else { copyrightView.Text = "An error fetching the copyright occurred. Please visit Bibles.org for copyright information."; } } finally { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } } else { new UIAlertView("Network Failure", "Oops! Please connect to the internet to download verses.", null, "Okay", null).Show(); } }
private async void Import() { if (Reachability.IsHostReachable(AppSettings.ApiEndpoint)) { var scanner = new MobileBarcodeScanner(this); var result = await scanner.Scan(); if (result == null) { View.Add(_loadPopup); await Task.Run(() => _accountService.TryImport(result.Text)).ContinueWith(r => { if (r.Result) { _loadPopup.Hide(); tableView.ReloadData(); } else { this.ShowError(IosLocalizator.Translate(Constants.MESSAGE_IMPORT_ERROR)); } }, TaskScheduler.FromCurrentSynchronizationContext()); } } else { this.ShowError(IosLocalizator.Translate(Constants.MESSAGE_CHECK_CONNECTION)); } }
private void Export(NSIndexPath indexPath) { if (Reachability.IsHostReachable(AppSettings.ApiEndpoint)) { accountController.View.Add(_loadPopup); var userName = GetAccount()[indexPath.Row].UserName; var deviceId = UIDevice.CurrentDevice.IdentifierForVendor.AsString(); Task.Run(() => accountController._accountService.TryExport(deviceId, userName)).ContinueWith(r => { _loadPopup.Hide(); if (r.Result) { var destUrl = Path.Combine(AppSettings.ApiEndpoint, $"{deviceId}_{userName}"); accountController.ShowImageAlert(userName.ToFullName(), GetQRCode(destUrl), IosLocalizator.Translate(Constants.MESSAGE_SCAN_CODE)); } else { accountController.ShowError(IosLocalizator.Translate(Constants.MESSAGE_LOAD_ERROR)); } }, TaskScheduler.FromCurrentSynchronizationContext()); } else { accountController.ShowError(IosLocalizator.Translate(Constants.MESSAGE_CHECK_CONNECTION)); } }
public bool IsNetworkAvailable() { #if WINDOWS if (NetworkInterface.GetIsNetworkAvailable()) { NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface netInterface in netInterfaces) { if (netInterface.OperationalStatus == OperationalStatus.Up) { if ((netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)) { IPv4InterfaceStatistics statistics = netInterface.GetIPv4Statistics(); // empirical testing indicates that once an interface // comes online it has already acquired statistics for // both received and sent bytes, so we use that fact to // define 'availability' if ((statistics.BytesReceived > 0) && (statistics.BytesSent > 0)) { return(true); } } } } } return(false); #else // MONOTOUCH return(Reachability.IsHostReachable("www.google.com")); #endif }
public Vote(IntPtr handle) : base(handle) { Title = NSBundle.MainBundle.LocalizedString("Votação", "Votação"); View.BackgroundColor = UIColor.White; webView = new UIWebView(View.Bounds); webView.ScrollView.ContentInset = new UIEdgeInsets(0, 0, 65, 0); View.AddSubview(webView); url = "http://poll.fitu.tum.pt"; webView.ScalesPageToFit = false; if (!Reachability.IsHostReachable("tum.pt")) { UIAlertView alert = new UIAlertView(); alert.Title = "Sem ligação à rede"; alert.AddButton("Continuar"); alert.Message = "Não conseguirá usar a aplicação sem conexão à rede."; alert.Show(); } else { webView.LoadRequest(new NSUrlRequest(new NSUrl(url))); } }
public string InsertSurveyAnswer(cSurveyAnswer SurveyAnswer) { string mStatusResponse = ""; if (Reachability.IsHostReachable("http://www.google.co.uk")) { try { var mRequest = HttpWebRequest.Create(""); // removed for security. mRequest.ContentType = "application/json"; mRequest.Method = "POST"; mRequest.Headers[""] = ""; // removed for security. var mJSON = JsonConvert.SerializeObject(SurveyAnswer); using (StreamWriter sw = new StreamWriter(mRequest.GetRequestStream())) { sw.Write(mJSON); sw.Flush(); sw.Close(); } using (HttpWebResponse mResponse = mRequest.GetResponse() as HttpWebResponse) { mStatusResponse = ((HttpWebResponse)mResponse).StatusDescription; if (mResponse.StatusCode != HttpStatusCode.OK) { return("Error"); } else { using (StreamReader sr = new StreamReader(mResponse.GetResponseStream())) { var content = sr.ReadToEnd(); if (string.IsNullOrWhiteSpace(content)) { return("No Content"); } else { string SurveyAnswerId; SurveyAnswerId = JsonConvert.DeserializeObject <string>(content); return(SurveyAnswerId); } } } } } catch (WebException ex) { string mStatus = (ex.Response as HttpWebResponse)?.StatusCode.ToString(); return(mStatus); } } else { return("No internet connectiuon"); } }
/// <summary> /// Is the network available. /// </summary> /// <returns><c>true</c>, if network is available, <c>false</c> otherwise.</returns> /// <param name="testHost">Test host.</param> public static bool IsNetworkAvailable(string testHost = "http://google.com") { //Via Reachability if (HasInternetConnection()) { return(Reachability.IsHostReachable(testHost)); } return(false); }
public bool CheckInternetConnection() { if (!Reachability.IsHostReachable("http://google.com")) { return(false); } else { return(true); } }
public bool IsConnected() { if (!Reachability.IsHostReachable("www.google.com")) { return(false); } else { return(true); } }
/// <summary> /// Respondes the servicio. /// </summary> /// <returns><c>true</c>, if servicio was responded, <c>false</c> otherwise.</returns> /// <param name="Uri">URI.</param> public bool RespondeServicio(string Uri) { try { return(Reachability.IsHostReachable(Uri)); } catch (Exception ex) { Log.RecordLog(ex, TypeLog.Error, Pilicy.Client); return(false); } }
private async void SaveButtonClicked() { controller.FirstTourStepCompleted(); var nonEmptyVerseReferenceTextField = verseReference.Text.Length != 0; if (nonEmptyVerseReferenceTextField) { var verse = new Verse { Category = Category.Queue, Content = "Verse downloading...", Memorized = false, Title = verseReference.Text, Comments = verseComments.Text == "Comments" ? "" : verseComments.Text }; if (Reachability.IsHostReachable("www.google.com")) { try { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; if (VersesTableViewController.Current.Verses.Any(item => item.Title == verse.Title)) { new UIAlertView("Verse Already Exists", "Whoops, this verse is already in your library.", null, "Okay", null).Show(); } else { VersesTableViewController.Current.Locked = true; var translation = TranslationHelper.GetCurrentTranslationForDownload(); verse.Translation = translation; verse.Content = await BiblesDotOrg.GetVerseTextWithoutHtmlOrDigitsAsync(verseReference.Text, translation); controller.AddVerse(verse); VersesTableViewController.Current.Locked = false; LocalyticsSession.Shared.TagEvent("Verse Saved"); } } catch (InvalidVerseException) { new UIAlertView("Invalid Input", "Oops! That verse was not found!", null, "Okay", null).Show(); } finally { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } } else { new UIAlertView("Network Failure", "Oops! Please connect to the internet to download verses.", null, "Okay", null).Show(); } } else { new UIAlertView("Invalid Input", "Oops! Don't forget to add a verse reference!", null, "Okay", null).Show(); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button> (Resource.Id.myButton); this.cancellation = new CancellationTokenSource(); var reachability = new Reachability(); reachability.Ping("http://www.yahoo.com", cancellation.Token, this).ContinueWith(t => { Log.Info(t.ToString(), "Ping has ended"); }); reachability.IsHostReachable("http://dev.virtualearth.net", TimeSpan.FromMinutes(1)).ContinueWith(t => { button.Enabled = t.Result; }); DependencyResolver.Current.RegisterService <IJsonSerializer>(new SimplyMobile.Text.JsonNet.JsonSerializer()); DependencyResolver.Current.RegisterService <IRestClient>(t => new JsonClient(new HttpClient(new OkHttpNetworkHandler()), t.GetService <IJsonSerializer>()) ); button.Click += async delegate { var bingClient = new BingClient( "Apcl0Dzk-uwuqlIpDPjGLaA0oHXERDiGBuE3Vzxx3peRCr8gmSRPr-J6cij7U1pZ", DependencyResolver.Current.GetService <IRestClient>() ); var response = await bingClient.Get(47.64054, -122.12934); if (response.StatusCode == System.Net.HttpStatusCode.OK) { System.Diagnostics.Debug.WriteLine(response.Value.Copyright); CreateIntent(response.Value); } else { System.Diagnostics.Debug.WriteLine(response.Error.Message); } }; }
private async void SaveButtonClicked() { if (VerseReference.Text != "") { var verse = new Verse { Category = MemorizationCategory.Queue, Content = "Verse downloading...", Memorizable = true, Memorized = false, Timestamp = DateTime.Now, Title = VerseReference.Text, Comments = VerseComments.Text == "Comments" ? "" : VerseComments.Text }; TranslationHelper.AddVerseTranslation(verse); if (Reachability.IsHostReachable("www.google.com")) { var path = DatabaseSetupHelper.GetDatabasePath("verses.db3"); var db = new DatabaseHelper(path); var translation = TranslationHelper.GetCurrentTranslationForDownload(); try { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; verse.Content = await BiblesDotOrg.GetVerseTextWithoutHtmlOrDigitsAsync(VerseReference.Text, translation); db.AddVerse(verse); LocalyticsSession.Shared.TagEvent("Verse Saved"); } catch (InvalidVerseException ex) { Console.WriteLine(ex); new UIAlertView("Invalid Input", "Oops! That verse was not found!", null, "Okay", null).Show(); } finally { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } ManagingController.ViewDidAppear(true); ManagingController.VersesTable.ReloadData(); } else { new UIAlertView("Network Failure", "Oops! Please connect to the internet to download verses.", null, "Okay", null).Show(); } } else { new UIAlertView("Invalid Input", "Oops! Don't forget to add a verse reference!", null, "Okay", null).Show(); } }
public void CheckInternetConnection() { if (!Reachability.IsHostReachable("http://google.com")) { UIAlertView _MessagePopUp = new UIAlertView(Lang.ERROR_HEADLINE, Lang.INTERNET_CONNECTION_REQUIERED, null, Lang.BUTTON_OK, null); _MessagePopUp.Show(); _MessagePopUp.Clicked += (object senders, UIButtonEventArgs es) => { if (es.ButtonIndex == 0) { CheckInternetConnection(); } }; } }
public string GetAllQuesitons(int SurveyId) { if (Reachability.IsHostReachable("http://www.google.co.uk")) { Debug.WriteLine(SurveyId); var request = HttpWebRequest.Create(""); // removed for security. request.ContentType = "application/json"; request.Method = "GET"; request.Headers[""] = ""; // removed for security. try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { return("Unauthorized"); } else { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var content = reader.ReadToEnd(); if (string.IsNullOrWhiteSpace(content)) { return("No Content"); } else { string SurveyQuestions = JsonConvert.DeserializeObject <string>(content); return(SurveyQuestions); } } } } } catch (WebException ex) { string mStatus = (ex.Response as HttpWebResponse)?.StatusCode.ToString(); return(mStatus); } } else { return("No Internet Connection"); } }
protected async override void OnAppearing() { if (Reachability.IsHostReachable("http://www.google.co.uk")) { { PinLabel.IsVisible = false; PinPickerLayout.IsVisible = false; PinActivityIndicator.IsVisible = true; string Response = ""; ISurveyHandler Survey = new SurveyHandler(); string AllSurveysResponse = await Task.Run(() => Response = Survey.GetAllSurvey("")); SurveyPicker.ItemsSource = JsonConvert.DeserializeObject <ObservableCollection <cSurvey> >(AllSurveysResponse.ToString()); PinPickerLayout.IsVisible = true; PinActivityIndicator.IsVisible = false; } } }
public void GetData() { if (Reachability.IsHostReachable("www.codecags.com")) { var client = new RestClient("http://www.codecags.com"); var request = new RestRequest("jsonTienda.php", Method.GET); request.RequestFormat = DataFormat.Json; var response = client.Execute(request); RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); jsonObj = deserial.Deserialize <List <JsonTienda> > (response); } else { var alert = new UIAlertView("Connection Error", "Unable to connect to server", null, "OK", new string[] { "Cancel" }); alert.Clicked += (s, b) => { Console.WriteLine("Button " + b.ButtonIndex.ToString() + " clicked"); }; alert.Show(); } }
/// <summary> /// Called when a row is touched /// </summary> public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow(indexPath, true); if (!Reachability.IsHostReachable("www.Amazon.com")) { new UIAlertView(Utils.GetStringFromMainBundle("CFBundleDisplayName"), "Cannot connect to Amazon", null, "OK", null).Show(); return; } // show customer review var detail = mParentViewController.Storyboard.InstantiateViewController("CustomerReviews") as CustomerReviewsViewCtrl; detail.Title = mTableItems [indexPath.Row].Title; detail.SetItemId(mTableItems [indexPath.Row].Id); mParentViewController.NavigationController.PushViewController( detail, true ); }
public void GetPromoData() { if (!Reachability.IsHostReachable("www.codecags.com")) { var alert = new UIAlertView { Title = "Unable to connect to server", Message = "Verify network connections" }; alert.AddButton("OK"); alert.Show(); } else { var client = new RestClient("http://codecags.com"); var request = new RestRequest("jsonAllPromos.php", Method.POST); request.RequestFormat = DataFormat.Json; var response = client.Execute(request); RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); promos = deserial.Deserialize <List <JsonPromos> > (response); } }
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell celda = tableView.DequeueReusableCell(Identificador); if (celda == null) { celda = new UITableViewCell(UITableViewCellStyle.Subtitle, Identificador); } celda.SelectionStyle = UITableViewCellSelectionStyle.Blue; celda.TextLabel.Text = ListaDatos [indexPath.Row].nombre; celda.Accessory = UITableViewCellAccessory.DisclosureIndicator; if (Reachability.IsHostReachable("www.codecags.com")) { celda.ImageView.SetImage( url: new NSUrl("http://www.codecags.com/Img/" + ListaDatos [indexPath.Row].logo), placeholder: UIImage.FromBundle("placeholder.jpg") ); } celda.DetailTextLabel.Text = "Promociones disponibles: " + ListaDatos [indexPath.Row].promociones.ToString(); celda.DetailTextLabel.TextColor = UIColor.Gray; return(celda); }
async void TechnicalSpecButton_TouchUpInside(object sender, EventArgs e) { //Get current view controller var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } SpecResponse specResponse = new SpecResponse(); var specification = await specResponse.GetSpecBySpecIDDesignationIDAsync(ad.SpecId, ad.DesignationId); if (specification.SpecId != 0) { var specTableViewController = vc.Storyboard.InstantiateViewController("SpecViewController_") as SpecViewController_; specTableViewController.Spec = specification; vc.PresentViewController(specTableViewController, true, null); } else { if (!Reachability.IsHostReachable(Settings._baseDomain)) { var alert = UIAlertController.Create("Connect to a Network", "Please connect to a network to retrieve these aircraft specs", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, null)); if (alert.PopoverPresentationController != null) { alert.PopoverPresentationController.SourceView = vc.View; alert.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Up; } vc.PresentViewController(alert, animated: true, completionHandler: null); } } }
protected async override void OnAppearing() { if (Reachability.IsHostReachable("http://www.google.co.uk")) { Online = true; ActivityIndicatorSurveyPage.IsRunning = true; string Response = ""; ISurveyQuestion Survey = new SurveyQuestionsHandler(); string AllSurveyQuestions = await Task.Run(() => Response = Survey.GetAllQuesitons(SurveyId)); ActivityIndicatorSurveyPage.IsRunning = false; MainStackLayout.IsVisible = true; if (!(AllSurveyQuestions == "Unauthorized" || AllSurveyQuestions == "No Content" || AllSurveyQuestions == "No Internet Connection")) { AllSurveys = JsonConvert.DeserializeObject <IEnumerable <cSurveyQuestions> >(AllSurveyQuestions.ToString()); CreateAllQuestions(AllSurveys); FullStackLayout.IsVisible = true; } else { SurveyEmptyStacklayout.IsVisible = true; } } else { var ListOfSurveyQuestions = dbHandler.GetAllQuestionBySurveyId(SurveyId); if (ListOfSurveyQuestions.Count > 0) { CreateAllQuestions(ListOfSurveyQuestions); FullStackLayout.IsVisible = true; MainStackLayout.IsVisible = true; } else { SurveyEmptyStacklayout.IsVisible = true; } } }
public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { var url = _podcastList[indexPath.Row].Url; var fileName = Path.GetFileNameWithoutExtension(url); var offlineFilePath = Path.Combine(_hvc._documents, fileName + ".mp3"); Console.WriteLine ("Selected " + _podcastList[indexPath.Row].Title); var r = new Reachability(); if(!r.IsHostReachable("www.google.com") && _hvc.OfflineMp3Available(offlineFilePath)) _hvc.PlayAudioUrl(url); else if(!r.IsHostReachable("www.google.com")) { using (var alert = new UIAlertView("Whoops", "You'll need to be on the internet to do this", null, "Ok", null)) { alert.Show(); } } else _hvc.PlayAudioUrl(url); tableView.DeselectRow(indexPath, true); }
public override void ViewDidLoad() { base.ViewDidLoad(); //set share button image btnShare.SetImage(UIImage.FromFile("share.png"), UIControlState.Normal); if (Reachability.IsHostReachable("www.laftrip.com")) { this.ParentViewController.ParentViewController.NavigationItem.SetRightBarButtonItem( new UIBarButtonItem(UIBarButtonSystemItem.Add, (sender, args) => { this.TabBarController.NavigationController.PushViewController(new AddJokeView(), true); }) , true); //get liked jokes from db likedJokes = LikeProvider.GetLikedJokes(); // btnShare.TouchUpInside += (object sender, EventArgs e) => { this.TabBarController.NavigationController.PushViewController(new JokesShareViewController(Laftrip.API.Enums.ItemType.Joke, currentJokeTitle, currentJokeDesc, currentJokeId), true); }; btnLike.TouchUpInside += (object sender, EventArgs e) => { if (!isLiked) { int success = -1; Downloader downloader = new Downloader(); DisplayProgress("Liking Joke"); Task.Factory.StartNew(() => { success = downloader.LikeJoke(currentJokeId); }).ContinueWith(task3 => { HideProgress(); View.BackgroundColor = UIColor.White; //save liked joke to db LikeProvider.SaveLikedJoke(currentJokeId); //add jokeid to array btnLike.SetImage(UIImage.FromFile("liked.png"), UIControlState.Normal); likedJokes.Add(currentJokeId); isLiked = true; return(success); }, TaskScheduler.FromCurrentSynchronizationContext()); } else //already liked. dislike. //remove from db { LikeProvider.DeleteLikedPhoto(currentJokeId); btnLike.SetImage(UIImage.FromFile("unliked.png"), UIControlState.Normal); likedJokes.Remove(currentJokeId); isLiked = false; } }; //INITIAL DOWNLOAD DisplayProgress("Getting Jokes"); Download(); // previous swipeRight.AddTarget(() => { jokeIndex--; internalPage--; swipeLeft.Enabled = true; //if this is the first element in the internal list, download previous external page if (internalPage == -1 && jokeIndex > 0) { DisplayProgress("Getting Jokes"); Download(); externalPage--; } else { txtJokeDesc.Text = filteredJokesBatch[internalPage].JokeDesc; lblTitle.Text = filteredJokesBatch[internalPage].Title; currentJokeId = filteredJokesBatch[internalPage].JokeID; currentJokeTitle = filteredJokesBatch[internalPage].Title; currentJokeDesc = filteredJokesBatch[internalPage].JokeDesc; checkLiked(); } if (jokeIndex == 0) { swipeRight.Enabled = false; } lblPage.Text = (jokeIndex + 1) + " of " + jokeCount; }); //next swipeLeft.AddTarget(() => { jokeIndex++; internalPage++; swipeRight.Enabled = true; //if this is the last element in the internal list, download next external page if (internalPage == filteredJokesBatch.Count) { externalPage++; DisplayProgress("Getting Jokes"); Download(); } else { txtJokeDesc.Text = filteredJokesBatch [internalPage].JokeDesc; lblTitle.Text = filteredJokesBatch[internalPage].Title; currentJokeId = filteredJokesBatch[internalPage].JokeID; currentJokeTitle = filteredJokesBatch[internalPage].Title; currentJokeDesc = filteredJokesBatch[internalPage].JokeDesc; checkLiked(); } if ((jokeIndex + 1) == jokeCount) { swipeLeft.Enabled = false; } lblPage.Text = (jokeIndex + 1) + " of " + jokeCount; }); View.AddGestureRecognizer(swipeRight); View.AddGestureRecognizer(swipeLeft); NavigationController.SetNavigationBarHidden(true, true); //admob adView = new GADBannerView(size: GADAdSizeCons.Banner, origin: new PointF(0, 0)) { AdUnitID = AdmobID, RootViewController = this }; adView.DidReceiveAd += (sender, args) => { if (!viewOnScreen) { View.AddSubview(adView); } viewOnScreen = true; }; adView.LoadRequest(GADRequest.Request); } else { connDelegate = new NoConnectionDelegate(this.NavigationController); new UIAlertView("No Internet Detected", "Internet Connection is required." , connDelegate, "ok", null).Show(); } }
public override async void ViewDidLoad() { base.ViewDidLoad(); var btn = new UIButton(UIButtonType.Custom); btn.Frame = new CGRect(0, 0, 0, 0); showIndicator(); btn.SetImage(UIImage.FromBundle("barlogo"), UIControlState.Normal); btn.ContentMode = UIViewContentMode.ScaleAspectFit; searchBar = new UISearchBar() { Placeholder = " ", Prompt = " ", ShowsScopeBar = true }; searchBar.SizeToFit(); searchBar.AutocorrectionType = UITextAutocorrectionType.No; searchBar.AutocapitalizationType = UITextAutocapitalizationType.None; searchBar.ReturnKeyType = UIReturnKeyType.Done; searchBar.EnablesReturnKeyAutomatically = false; searchBar.SearchButtonClicked += (sender, e) => { // Search(); }; searchBar.TextChanged += (sender, e) => { //this is the method that is called when the user searches searchTable(); }; searchBar.CancelButtonClicked += (sender, e) => { searchBar.ResignFirstResponder(); }; searchBar.SelectedScopeButtonIndexChanged += (sender, e) => { searchBar.ResignFirstResponder(); }; searchBar.SearchButtonClicked += (sender, e) => { // searchTable(); searchBar.ResignFirstResponder(); }; this.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem(btn), true); this.NavigationItem.TitleView = searchBar; if (Reachability.IsHostReachable("https://newcities-newurban.firebaseio.com")) { getNews gn = new getNews(); allnews = await gn.GetAllNews(); if (allnews != null) { table = new UITableView(new CGRect(0, 20, View.Bounds.Width - 5, View.Bounds.Height - 20)); table.AutoresizingMask = UIViewAutoresizing.All; table.RowHeight = 300f; table.EstimatedRowHeight = 300f; // defaults to Plain style table.Source = new ListsPhotoModelSource(allnews.ToArray(), this, ""); await RefreshAsync(); AddRefreshControl(); //table.TableHeaderView = searchBar; Add(table); hideIndicator(); table.Add(RefreshControl); } else { var alrt = UIAlertController.Create("Nuca", "يرجي التاكد من الاتصال بالانترنت", UIAlertControllerStyle.Alert); alrt.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alrt, true, null); } } else { PhotoModel pm = new PhotoModel(); pm.id = 0; pm.title = "يرجي التاكد من الاتصال بالانترنت"; pm.image = ""; pm.date = DateTime.Today.ToShortDateString(); pm.dayx = ""; pm.longdesc = ""; // allnews.Add(pm); var alrt = UIAlertController.Create("Nuca", "يرجي التاكد من الاتصال بالانترنت", UIAlertControllerStyle.Alert); alrt.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alrt, true, null); hideIndicator(); } }
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // create a new window instance based on the screen size window = new UIWindow(UIScreen.MainScreen.Bounds); BL.Managers.UpdateManager.UpdateFinished += HandleFinishedUpdate; //NOTE: this is a quick response to Apple's disapproval of the sqlite living in the /Documents/ folder // in the previous versions of the app. A quick way to preserve the favorites when the sqlite is moved // to /Library/ //HACK: not a good idea in the FinishedLaunching method, but it will do for now... //HACK: we need to do this before triggering the static ctor on MwcDatabase! var docsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string oldDBLocation = Path.Combine(docsPath, "MwcDB.db3"); // in Document string newDBLocation = oldDBLocation.Replace("Documents/MwcDB.db3", "Library/MwcDB.db3"); try { ConsoleD.WriteLine("oldDbLocation=" + oldDBLocation); if (File.Exists(oldDBLocation)) // won't normally be there in new installs { File.Delete(newDBLocation); // static ctor will have created it File.Move(oldDBLocation, newDBLocation); ConsoleD.WriteLine("Moved " + oldDBLocation + " to " + newDBLocation); } else { ConsoleD.WriteLine("oldDBLocation didn't exist?"); } } catch (Exception ex) { ConsoleD.WriteLine("Well, we tried! Couldn't save the old favorites..." + ex.Message); File.Delete(oldDBLocation); } // start updating all data in the background // by calling this asynchronously, we must check to see if it's finished // everytime we want to use/display data. new Thread(new ThreadStart(() => { var prefs = NSUserDefaults.StandardUserDefaults; bool hasSeedData = BL.Managers.UpdateManager.HasDataAlready; ConsoleD.WriteLine("hasSeedData=" + hasSeedData); if (!hasSeedData) { // only happens when the database is empty (or wasn't there); use local file update ConsoleD.WriteLine("Load seed data"); var appdir = NSBundle.MainBundle.ResourcePath; var seedDataFile = appdir + "/Images/SeedData.xml"; string xml = System.IO.File.ReadAllText(seedDataFile); BL.Managers.UpdateManager.UpdateFromFile(xml); ConsoleD.WriteLine("Database lives at: " + MWC.DL.MwcDatabase.DatabaseFilePath); // We SHOULDN'T skip backup because we are saving the Favorites in the same sqlite // database as the sessions are stored. A more iCloud-friendly design would be // to keep the user-data separate from the server-generated data... NSFileManager.SetSkipBackupAttribute(MWC.DL.MwcDatabase.DatabaseFilePath, true); } else { // if there's already data in the database, do/attempt server update //ConsoleD.WriteLine("SkipBackup: "+NSFileManager.GetSkipBackupAttribute (MWC.DL.MwcDatabase.DatabaseFilePath)); var earliestUpdateString = prefs.StringForKey(PrefsEarliestUpdate); DateTime earliestUpdateTime = DateTime.MinValue; if (!String.IsNullOrEmpty(earliestUpdateString)) { CultureInfo provider = CultureInfo.InvariantCulture; if (DateTime.TryParse(earliestUpdateString , provider , System.Globalization.DateTimeStyles.None , out earliestUpdateTime)) { ConsoleD.WriteLine("Earliest update time: " + earliestUpdateTime); } } if (earliestUpdateTime < DateTime.Now) { // we're past the earliest update time, so update! if (Reachability.IsHostReachable(Constants.ConferenceDataBaseUrl)) { ConsoleD.WriteLine("Reachability okay, update conference from server"); BL.Managers.UpdateManager.UpdateConference(); } else { // no network ConsoleD.WriteLine("No network, can't update data for now"); } } else { ConsoleD.WriteLine("Too soon to update " + DateTime.Now); } } })).Start(); tabBar = new Screens.Common.TabBarController(); // couldn't do RespondsToSelector() on static 'Appearance' property) var majorVersionString = UIDevice.CurrentDevice.SystemVersion.Substring(0, 1); var majorVersion = Convert.ToInt16(majorVersionString); if (majorVersion >= 5) // gotta love Appearance in iOS5 { UINavigationBar.Appearance.TintColor = ColorNavBarTint; } window.RootViewController = tabBar; window.MakeKeyAndVisible(); return(true); }
/// <summary> /// Gets a list of podcasts from local storage or online. /// </summary> private void GetPodcastList() { var r = new Reachability(); var HasConnection = r.IsHostReachable("www.google.com"); if(HasConnection) { Console.WriteLine ("Have connection - get internet version"); _webClient = new WebClient(); // Make Async... var url = _hanselminuteMp3RssFeed; _webClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { SaveOnDevice(e.Result); DisplayPodcastList (e.Result); StopLoadingScreen(); StopInternetActivity(); }; _webClient.DownloadStringAsync(new Uri(url)); } else if (!HasConnection && HasLocalXml()) { Console.WriteLine ("No connection but use local version"); DisplayPodcastList(GetLocalPodcastListXml()); } else { Console.WriteLine ("No internet - no local version"); using (var alert = new UIAlertView("Whoops", "You'll need to connect to the internet to get a list of Podcasts", null, "Ok", null)) { alert.Dismissed += delegate { Console.WriteLine ("Dismissed Alert"); StopInternetActivity(); StopLoadingScreen(); }; alert.Show(); } } }
public string GetUpdatedSurveyListFromServer(List <SurveyVersions> SurveyIdVersionList) { string mStatusResponse = ""; if (Reachability.IsHostReachable("http://www.google.co.uk")) { try { var mRequest = HttpWebRequest.Create(""); // removed for security. mRequest.ContentType = "application/json"; mRequest.Method = "POST"; mRequest.Headers[""] = "";// removed for security. JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }; var mJSON = JsonConvert.SerializeObject(SurveyIdVersionList, microsoftDateFormatSettings); using (StreamWriter sw = new StreamWriter(mRequest.GetRequestStream())) { sw.Write(mJSON); sw.Flush(); sw.Close(); } using (HttpWebResponse mResponse = mRequest.GetResponse() as HttpWebResponse) { mStatusResponse = ((HttpWebResponse)mResponse).StatusDescription; if (mResponse.StatusCode != HttpStatusCode.OK) { return("Error"); } else { using (StreamReader sr = new StreamReader(mResponse.GetResponseStream())) { var content = sr.ReadToEnd(); if (string.IsNullOrWhiteSpace(content)) { return("No Content"); } else { string ComparedResultsResponse; ComparedResultsResponse = JsonConvert.DeserializeObject <string>(content); return(ComparedResultsResponse); } } } } } catch (WebException ex) { string mStatus = (ex.Response as HttpWebResponse)?.StatusCode.ToString(); return(mStatus); } } else { return("No internet connectiuon"); } }