I have an active Google Places autocomplete working with Xamarin Forms or Cross Platform. I have a working solution that auto populates the address when the user types in the address. My problem is when the user selects it from the list the address does not go to the search_bar.text… The search bar just remains with the text that was typed? how can I get the text when selected to populate in the search bar.
I am new to Xamarin forms and C#.
public Createbusinessaccount ()
{
InitializeComponent ();
search_bar.ApiKey = GooglePlacesApiKey;
search_bar.Type = PlaceType.Address;
search_bar.Components = new Components("country:us"); // Restrict results to Australia and New Zealand
search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved;
search_bar.TextChanged += Search_Bar_TextChanged;
search_bar.MinimumSearchText = 2;
results_list.ItemSelected += Results_List_ItemSelected;
}
void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result)
{
results_list.ItemsSource = result.AutoCompletePlaces;
spinner.IsRunning = false;
spinner.IsVisible = false;
if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0)
results_list.IsVisible = true;
}
void Search_Bar_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
results_list.IsVisible = false;
spinner.IsVisible = true;
spinner.IsRunning = true;
}
else
{
results_list.IsVisible = true;
spinner.IsRunning = false;
spinner.IsVisible = false;
}
}
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
In your ItemSelected method, you need to set the text of the searchbar:
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
search_bar.Text = prediction.Name? // Your property here
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
I am still trying to fix this, it only adds the street name and number not the whole address
Related
I'm using the ZXing plugin to scan bar codes and I'm using a custom overlay to display information and make a button visible/invisible when I need to perform an action, which in this case is to set a flag and make the button invisible again.
In this code I set up the scanning plugin:
MyButton_Scan.Click += async (sender, e) =>
{
var selectedEvent = string.Format("{0}", MyEventsSpinner.GetItemAtPosition(MyEventsSpinner.SelectedItemPosition));
if (selectedEvent.ToUpper() != "SELECT EVENT")
{
MobileBarcodeScanner.Initialize(Application);
scanner = new MobileBarcodeScanner();
scanner.UseCustomOverlay = true;
zxingOverlay = LayoutInflater.FromContext(this).Inflate(Resource.Layout.scanner, null);
MyScanScreenButton = zxingOverlay.FindViewById<Android.Widget.Button>(Resource.Id.okButton);
MyScanScreenButton.Click += btnOk_Click;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Invisible;
scanner.CustomOverlay = zxingOverlay;
var opt = new MobileBarcodeScanningOptions();
opt.DelayBetweenContinuousScans = 5000;
//Start scanning
scanner.ScanContinuously(this, opt, HandleScanResult);
} else
{
Utils.showMessage("Please select an event from the drop down list");
}
};
The code that handles the scan result and button click:
void btnOk_Click(object sender, System.EventArgs e)
{
popUpOpen = false;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Invisible;
}
void HandleScanResult(ZXing.Result result)
{
if (!popUpOpen)
{
Boolean ConversionGood = true;
TextView MyTextView = zxingOverlay.FindViewById<TextView>(Resource.Id.ticketInfo);
Int32 convertedResult = 0;
Stream successbeepStream = GetType().Assembly.GetManifestResourceStream("eTicket_Scanner.beep.wav");
Stream failbeepStream = GetType().Assembly.GetManifestResourceStream("eTicket_Scanner.buzzer.wav");
MyTextView.SetBackgroundColor(Color.White);
try
{
convertedResult = Convert.ToInt32(result.Text);
}
catch (Exception ex)
{
ConversionGood = false;
bool isSuccess = _simpleAudioPlayer.Load(failbeepStream);
_simpleAudioPlayer.Play();
popUpOpen = true;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
MyTextView.SetBackgroundColor(Color.Red );
MyTextView.Text = "Not a valid ticket for this event.\nErrorif applicable): " + ex.Message;
}
string scanResult = "";
if (ConversionGood)
{
scanResult = MyEventsService.VerifyScannedCode(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
if (scanResult == "Y")
{
MyTextView.SetBackgroundColor(Color.Green);
bool isSuccess = _simpleAudioPlayer.Load(successbeepStream);
popUpOpen = true;
MyTextView.SetBackgroundColor(Color.Green);
MyTextView.Text = MyEventsService.GetTicketInfo(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
_simpleAudioPlayer.Play();
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
}
else
{
bool isSuccess = _simpleAudioPlayer.Load(failbeepStream);
popUpOpen = true;
MyTextView.SetBackgroundColor(Color.Red);
MyTextView.Text = MyEventsService.GetFailedScanTicketInfo(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
_simpleAudioPlayer.Play();
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
}
}
}
}
Its not a very complicated app, scan barcodes and verify the code, set the color of the textview background and display the info. The "Ok" button is never visible, but if I click in the space where the button should appear, it executes the button click code. I'm assuming that there is some sort of thread issue here with the interface, but anything I've tried with the thread hasn't worked. Anyone have any ideas?
Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}
We have aspx page that is being used as a dialog box.
Page has ascx control which has Text box to search available users from oracle DB tables.
Every search click posts back to same control and renders search results.
If I click search and before response is back from server I close the dialog aspx page, then next time I try to open same dialog box it takes forever to render.
Please suggest what could be happening, going wrong?
Any help is highly appreciated
Here is the code
protected void UserListControl_PreRender(object sender, EventArgs e)
{
//set UI text
m_objTitle.Text = TITLE_LABEL;
//Set Properties of search
m_objSearchResults.CacheResults = true;
m_objSearchResults.RefreshCache = true;
m_objSearchResults.DoSearch = true;
m_objSearchResults.Pageable = true;
m_objSearchResults.NoRecordsMessage = NO_RECORDS_MSG;
m_objSearchResults.PageSize = 25;
m_objSearchResults.SearchType = m_sSearchType;
//Add items to the dropdown
if (m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(AVAIL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT).Value = AVAIL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(ALL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT).Value = ALL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(SEARCH_USER_TEXT);
m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT).Value = SEARCH_USER_VALUE;
}
if (this.Page.IsPostBack == false)
{
m_objStatusDropDown.SelectedValue = SEARCH_USER_VALUE;
}
if (IsPostBack)
{
try
{
m_objUserInstructionText.Text = "";
//add the DAO Parameters
string assignmentTypeSelected = Request.QueryString["AssignmentType"];
m_objSearchResults.DAOParams.Add("RequestType", Request.QueryString["RequestType"]);
m_objSearchResults.DAOParams.Add("AssignmentID", Request.QueryString["AssignmentID"]);
m_objSearchResults.DAOParams.Add("AssignmentType", assignmentTypeSelected);
m_objSearchResults.DAOParams["StatusFilter"] = m_objStatusDropDown.SelectedValue.ToUpper();
m_objSearchResults.DAOParams["Name"] = m_objSearchTextBox.Value.Trim();
if (null == SetApplCode(assignmentTypeSelected))
{
throw new ApplicationException("Invalid Assignment Type.");
}
else
{
m_objSearchResults.DAOParams["ApplCode"] = SetApplCode(assignmentTypeSelected).ToUpper();
}
//add searchControl
m_objListPH.Controls.Add(m_objSearchResults);
// Get the values from the ResultsForm
string sRecordsDisplayed = m_objSearchResults.RecordsDisplayed;
string sTableWidth = m_objSearchResults.TableWidth;
bool bPageable = m_objSearchResults.Pageable;
int iCurrentPageIndex = m_objSearchResults.CurrentPageIndex;
int iPageSize = m_objSearchResults.PageSize;
int iRecordCount = m_objSearchResults.RecordCount;
int iEndRecord = m_objSearchResults.EndRecord;
// Create the html if we are paging data
m_objNavigation.Visible = bPageable;
m_objNavigation.DisplayViewAllButton = false;
m_objNavigation.PageSize = iPageSize;
m_objNavigation.Count = iRecordCount;
m_objNavigation.ItemsDisplayText = "Users";
m_objNavigation.CurrentPage = iCurrentPageIndex + 1;
}
catch (ApplicationException ex)
{
m_objInvalidAssignTypeErr.Text = ex.Message;
m_objUserInstructionText.Text = "";
}
}
}
I am creating a Windows Phone 8.1 Universal App. There are some screens on my app. On the first screen, i am navigate my screen to second screen. When i press hardware back button on second screen. My previous page state lost.
I am unable to rectify where was the problem. Here is the code below:
Screen 1 Code
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
this.NavigationCacheMode = NavigationCacheMode.Enabled;
if (e.NavigationMode == NavigationMode.New)
{
BindQuickDateComboBox();
if (Frame.BackStack.Count > 0)
{
var lastPage = Frame.BackStack.Last().SourcePageType;
if (lastPage != null && lastPage.FullName == "Cryoserver.AppLogin")
{
Frame.BackStack.Clear();
}
}
}
}
async private void appBarSearch_Click(object sender, RoutedEventArgs e)
{
try
{
if (IsValidateForm())
{
ProgressBar.IsVisible = true;
cmdBarSearch.IsEnabled = false;
if (await conn.Table<SearchQuery>().CountAsync() > 0)
{
await conn.DropTableAsync<SearchQuery>();
await conn.CreateTableAsync<SearchQuery>();
}
var searchTerms = new SearchQuery();
if (Convert.ToString(cmbQuickDate.SelectedItem) != "Any Date")
{
searchTerms.FromDate = pickerFromDate.Date.ToString("d MMM yyyy");
searchTerms.FromTime = pickerFromTime.Time.ToString();
searchTerms.ToDate = pickerToDate.Date.ToString("d MMM yyyy");
searchTerms.ToTime = pickerToTime.Time.ToString();
}
searchTerms.SearchKeywords = txtKeywords.Text;
searchTerms.Parties = txtParties.Text;
searchTerms.Contributer = txtFrom.Text;
searchTerms.Viewer = txtTo.Text;
searchTerms.AttachmentName = txtAttName.Text;
searchTerms.AttachmentKeywords = txtAttKeywords.Text;
searchTerms.SearchReason = txtSearchReason.Text;
searchTerms.IsHighLight = "false";
await conn.InsertAsync(searchTerms);
object resultMails = await SearchEmailArchive();
if (!String.IsNullOrEmpty(Convert.ToString(resultMails)))
{
GlobalInfo.SelectedRow = -1;
GlobalInfo.SearchPageIndex = -1;
GlobalInfo.IsFindKeyword = false;
var archiveMails = JsonConvert.DeserializeObject<SearchResult>(resultMails.ToString());
Frame.Navigate(typeof(MailList), archiveMails);
}
ProgressBar.IsVisible = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ProgressBar.IsVisible = false;
}
cmdBarSearch.IsEnabled = true;
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
}
Screen 2
I too used this code in second screen and also after removing this code. But it didn't work for me. Still the same problem.
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
Screen 1 state is Blank and behaves as a freshly loaded screen. Why?
Any help would be much appreciated.
I would try setting NavigationCacheMode="Required" in the constructor/XAML instead.
I have a Query that runs when the user submits a search and the gridview is loaded.
I want to page the gridview and would usually have my grid in a LoadGrid(). I have the paging working ok and everything is good until I want to view page 2 of the GridView.
protected void btn_Search_Click(object sender, EventArgs e)
{
// Init()
// -----
pnl_Message.Visible = false;
lbl_message.Text = String.Empty;
// Clear grid of previous results
// ==============================
ResultsGridView.DataSource = null;
ResultsGridView.DataBind();
try
{
using (var db = new dbDataContext())
{
// Check Fields
// ------------
if (txt_CustomerName.Text == string.Empty && txt_CCNo.Text == string.Empty &&
txt_SwiftNo.Text == string.Empty && drp_Provider.SelectedValue == string.Empty)
{
lbl_message.Text += "* Please enter a search term";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
pnl_results.Visible = false;
}
// Search Database
// ---------------
if (lbl_message.Text == String.Empty)
{
var customer = txt_CustomerName.Text.Length > 1 ? txt_CustomerName.Text.Trim() :
"Xcxcx";
//var provider = drp_Provider.SelectedItem.Text.Trim();
var concern = txt_CCNo.Text == "" ? 0 : Convert.ToInt32(txt_CCNo.Text);
var swiftid = txt_SwiftNo.Text == "" ? 0 : Convert.ToInt32(txt_SwiftNo.Text);
// Check which fields populated
// ----------------------------
var result =
from c in db.tbl_Concerns
where (c.ProviderId == Convert.ToInt32(drp_Provider.SelectedValue))
|| (c.person_Fullname.Contains(customer))
|| (c.SwiftId == swiftid)
|| (c.ConcernId == concern)
select new
{
c.ConcernId,
Swift = c.SwiftId,
FullName = c.person_Fullname,
Provider = c.tbl_Provider.provider_Name,
Concern_Detail = c.tbl_RaisedConcern.RaisedConcernText,
DateFrom = c.concern_DateFrom,
DateTo = c.concern_DateTo
};
// If No Results
// -------------
if (!result.Any())
{
lbl_message.Text += "* No results match your search, please try again.";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
}
else
{
// Show Table
// ----------
pnl_results.Visible = true;
ResultsGridView.DataSource = result;
ResultsGridView.DataBind();
// Table Header Names
// ------------------
ResultsGridView.HeaderRow.Cells[0].Text = "Select";
}
}
}
}
catch (SystemException ex)
{
var exceptionUtility = new genericExceptions();
exceptionUtility.genericSystemException(
ex,
Server.MachineName,
Page.TemplateSourceDirectory.Remove(0, 1) + Page.AppRelativeVirtualPath.Remove(0, 1),
ConfigurationManager.AppSettings["emailSupport"],
ConfigurationManager.AppSettings["emailFrom"],
string.Empty);
}
}
My PageIndexChanging event I would usually call the loadGrid() but I do not have that situation. I have tried just adding ResultsGridView.DataBind() but get the error Sequence contains no elements.
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultsGridView.PageIndex = e.NewPageIndex;
** How Can I bind the Grid**
}
Try this..
session["somename"]=result;
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var somename=session["somename"].Tostring();
ResultsGridView.PageIndex = e.NewPageIndex;
ResultsGridview.Datasource=somename;
REsultsGridview.Databind();
}