WPF singelton intance gives null exception, before singelton value is set - c#

I have created a Singelton
static readonly License_plateRequests _instance = new License_plateRequests();
private License_plateRequests()
{
}
public static License_plateRequests instance
{
get { return _instance; }
}
public License_plate license_plateFirst { get; set; }
I run a clickevent in a page, to run some code where i set the singelton value. Its my first application in WPF so, i dont know if the patteren is right.
private async void enterButton_Click(object sender, RoutedEventArgs e)
{
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Denmark-icon.png")
{
nationality = "DK";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Germany-icon.png")
{
nationality = "GER";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Norway-icon.png")
{
nationality = "NOR";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Sweden-icon.png")
{
nationality = "SWE";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/United-Kingdom-flat-icon.png")
{
nationality = "GB";
}
var data = await loginRequest.LoginAsync();
var token = await loginRequest.ParkingToken(data.jwt);
var licenseplate = await licensePlate.LicensePlate(token, nationality, numberplateInput.Content.ToString());
var parkings = await licensePlate.getParkingById(token, licenseplate.id);
try
{
foreach (var parking in parkings)
{
if (parking == null)
{
parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
NavigationService.Navigate(new RegistredPage());
}
else if (parking.time_end == 0)
{
NavigationService.Navigate(paymentPage, licenseplate);
licensePlate.license_plateFirst.country.alpha2 = nationality;
}
else
{
parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
NavigationService.Navigate(new RegistredPage());
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
Then i navigate by NavigationService to the next page PaymentPage.
I get a nullpointer Exception in PaymentPage.
public partial class PaymentPage : Page
{
License_plateRequests licensePlate = License_plateRequests.instance;
public PaymentPage()
{
InitializeComponent();
System.Diagnostics.Debug.WriteLine(licensePlate.license_plateFirst.country.alpha2);
}
}
I get the null pointer when i try to run the application. I havent set the value yet, so offcourse
licensePlate.license_plateFirst.country.alpha2
gives me null. But i havent loaded that page yet, and i havent set the value.
How can i handle this, so i can get the value when the page is first loaded?

Related

C# - Winforms - Combobox - Avoid selecting the first item updating the datasource

I have a combobox in my application, where items are loaded asynchronously depending on a search text you can enter in the text field.
This works fine, but every time the text of the first item is automatically selected during updating the datasource of the combobox.
This leads to unintended behaviour, because I need to have the search text entered by the user to stay in the textfield of the combobox until a selection is done by the user and not automatically overwrite the text with the first entry.
This is my code:
public partial class ProductGroupDescription : UserControl, Interfaces.TabPages.ITabPageProductGroupDescription
{
private Services.IProductGroupDescriptionService _ApplicationService;
public BindingList<ProductGroup> ProductGroups { get; set; } = new BindingList<ProductGroup>();
public string ProductGroupSearchText { get; set; } = string.Empty;
public ProductGroupDescription(Services.IProductGroupDescriptionService applicationService)
{
InitializeComponent();
InitialSetupControls();
_ApplicationService = applicationService;
}
public void InitialSetupControls()
{
var pgBindingSource = new BindingSource();
pgBindingSource.DataSource = ProductGroups;
Cbo_ProductGroup.DataSource = pgBindingSource.DataSource;
Cbo_ProductGroup.DataBindings.Add("Text", ProductGroupSearchText, "");
}
private async void Cbo_ProductGroup_TextChanged(object sender, EventArgs e)
{
if (Cbo_ProductGroup.Text.Length >= 2)
{
ProductGroupSearchText = Cbo_ProductGroup.Text;
Cbo_ProductGroup.SelectedIndex = -1;
bool withStopFlagged = Chk_StopFlag_PGs_Included.Checked;
List<ProductGroup> list = await _ApplicationService.GetProductGroupBySearchString(ProductGroupSearchText, withStopFlagged);
if (list != null && list.Count > 0)
{
ProductGroups.Clear();
list.ForEach(item => ProductGroups.Add(item));
Cbo_ProductGroup.DroppedDown = Cbo_ProductGroup.Items.Count > 0 && Cbo_ProductGroup.Focused;
}
}
}
}
I tried to set Cbo_ProductGroup.SelectedIndex = -1, but it does not solve my issue here.
I also saw this on SO: Prevent AutoSelect behavior of a System.Window.Forms.ComboBox (C#)
But is there really no simpler solution to this issue?
I got it to work now.
It worked, when I removed the binding of the text field of the combobox
Cbo_ProductGroup.DataBindings.Add("Text", ProductGroupSearchText, "");
and set the new (old) value directly to the text field of the combobox.
Cbo_ProductGroup.Text = searchText;
In this case, a new event Text_Changed is fired and so the application has a infinite loop. So I used a property (ShouldTextChangedEventBeIgnored), if the Text_Changed event should be ignored.
Thanks to #CaiusJard for many hints in the comments.
This is my final code:
public partial class ProductGroupDescription : UserControl, Interfaces.TabPages.ITabPageProductGroupDescription
{
private ApplicationLogic.Interfaces.Services.IProductGroupDescriptionService _ApplicationService;
public BindingList<ProductGroup> ProductGroups { get; set; } = new BindingList<ProductGroup>();
public bool ShouldTextChangedEventBeIgnored { get; set; } = false;
public ProductGroupDescription(ApplicationLogic.Interfaces.Services.IProductGroupDescriptionService applicationService)
{
_ApplicationService = applicationService;
InitializeComponent();
InitialSetupControls();
}
public void InitialSetupControls()
{
var pgBindingSource = new BindingSource();
pgBindingSource.DataSource = ProductGroups;
Cbo_ProductGroup.DataSource = pgBindingSource.DataSource;
}
private async Task<List<ProductGroup>> LoadProductGroupItems(string searchText)
{
bool withStopFlagged = Chk_StopFlag_PGs_Included.Checked;
return await _ApplicationService.GetProductGroupBySearchString(searchText, withStopFlagged);
}
private async Task SetProductGroupSearchBoxItems(List<ProductGroup> list, string searchText)
{
await Task.Run(() =>
{
if (list != null && list.Count > 0)
{
ShouldTextChangedEventBeIgnored = true;
Cbo_ProductGroup.Invoke((c) =>
{
ProductGroups.Clear();
list.ForEach(item => ProductGroups.Add(item));
c.DroppedDown = c.Items.Count > 0 && c.Focused;
c.Text = searchText;
c.Select(c.Text.Length, 0);
});
ShouldTextChangedEventBeIgnored = false;
}
});
}
private async void Cbo_ProductGroup_TextChanged(object sender, EventArgs e)
{
try
{
if (Cbo_ProductGroup.Text.Length >= 2 && ShouldTextChangedEventBeIgnored == false)
{
string searchText = Cbo_ProductGroup.Text;
List<ProductGroup> list = await LoadProductGroupItems(Cbo_ProductGroup.Text);
await SetProductGroupSearchBoxItems(list, searchText);
}
}
catch(Exception ex)
{
System.Diagnostics.Trace.Write(ex);
}
}
}

How can I check if an specific field exists in my database and add the record if it doesn't and edit it otherwise

This is my code in my registration form:
public override void Guardar()
{
if (ValidarCampos() == true)
{
try
{
if (MessageBox.Show("Desea guardar este registro?", "Mensaje", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
using (DBEntities db = new DBEntities())
{
bool contactExists = db.cliente.Any(o => o.nombre_cliente.Equals(txtRegCliente.Text));
if (contactExists)
{
MessageBox.Show("El cliente ingresado ya existe");
txtRegCliente.Clear();
return;
}
else
{
if (cliente_id == null)
oCliente = new cliente();
oCliente.nombre_cliente = txtRegCliente.Text;
oCliente.vendedor_id = Convert.ToInt32(cbRegVendedor.SelectedValue);
oCliente.tipo_cliente_id = Convert.ToInt32(cbRegTipoCliente.SelectedValue);
if (cliente_id == null)
{
db.cliente.Add(oCliente);
}
else
{
db.Entry(oCliente).State = EntityState.Modified;
}
db.SaveChanges();
MessageBox.Show("Se ha guardado correctamente");
this.Close();
}
}
}
}
catch (Exception error)
{
MessageBox.Show("Ha ocurrido un error: " + error.Message);
}
}
}
I have 2 buttons, New and Edit, both open the same windows form. If I click "New" the textbox and combobox are clean and if it's "Edit" the form will be open with the values from database. It works fine when it's "New" but when it's "Edit" and I want to modify another textbox that is not "nombre_cliente" I get a message: "The customer already exist". I just want to return to the form if the especific textbox "nombre_cliente" is already in the database in both cases "New" and "Edit" I am using windows form, EF Database, C#
EDIT:
This is my first form:
And it's code(the important part for my problem) :
private int? GetId()
{
try
{
return int.Parse(dgvTablas.Rows[dgvTablas.CurrentRow.Index].Cells[0].Value.ToString());
}
catch
{
return null;
}
}
#endregion
public override void Nuevo()
{
Presentation.FrmRegCliente oCliente = new Presentation.FrmRegCliente();
oCliente.ShowDialog();
Refrescar();
}
public override void Editar()
{
int? cliente_id = GetId();
if (cliente_id != null)
{
Presentation.FrmRegCliente oCliente = new Presentation.FrmRegCliente(cliente_id);
oCliente.ShowDialog();
Refrescar();
}
}
And my second form for add or edit a record:
And the part of code that I skipped at the beginning:
public partial class FrmRegCliente : FrmBaseGuardar
{
public int? cliente_id;
cliente oCliente = null;
public FrmRegCliente(int? cliente_id = null)
{
InitializeComponent();
this.cliente_id = cliente_id;
if (cliente_id != null)
CargaDatos();
else
{
CargarVendedor();
CargarTipoCliente();
}
}
private void CargaDatos()
{
CargarVendedor();
CargarTipoCliente();
using (DBEntities db = new DBEntities())
{
oCliente = db.cliente.Find(cliente_id);
cliente_id = oCliente.cliente_id;
txtRegCliente.Text = oCliente.nombre_cliente;
cbRegVendedor.SelectedValue = Convert.ToInt32(oCliente.vendedor_id);
cbRegTipoCliente.SelectedValue = Convert.ToInt32(oCliente.tipo_cliente_id);
}
}
//button "Guardar" code
PD: Sorry if my grammar is incorrect, english is not my first language

I got connection error it does not read data from database

In Xamarin forms, I tried to make a login form using MVVM. When I write the code there is no error but it does not give the desired output.
public Command Login
{
get
{
return new Command(() =>
{
var d = database.loggin(Usernamelogin, Passwordlogin);
if (d != null)
{
if (d.UserName == Usernamelogin && d.Password == Passwordlogin)
{
App.Current.MainPage.DisplayAlert("Notification", "Successfully Login", "Okay");
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "Error Login", "Okay");
}
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "No data", "Okay");
}
});
}
}
this is login command
public Register_person loggin(string mail,string pass )
{
return Conn.Table<Register_person>().FirstOrDefault(t => (t.Email == mail && t.Password == pass));
}
I only get the display message when the database is null statement. I cannot find why.
public ICommand Login { get; set; }
then add a constructor
public LoginViewModel()
{
Login = new Command(Login_Clicked);
}
then create a method Login_Clicked
private void Login_Clicked()
{
database = new Database();
var Logindata = database.GetUsername(_usernamelogin);
if (string.IsNullOrWhiteSpace(_usernamelogin) || string.IsNullOrWhiteSpace(_passwordlogin))
{
// your code
}
else
{
if (Logindata != null)
{
if (Logindata.UserName == _usernamelogin && Logindata.Password == _passwordlogin)
{
// your code
}
else
{
// your code
}
}
else
{
// your code
}
}
}
linc query
return Conn.Table<your Table name>().FirstOrDefault(t => t.Email == mail);
I extract email in the table

Xamarin.Forms: NavigationController is null in PageRenderer

I am trying to use PageRenderer to customize/reposition elements of ToolbarItem for iOS but here NavigationController throwing null reference exception.
Below my code
public class MyNavigationRenderer: PageRenderer
{
public new MyNavigationBar Element
{
get { return (MyNavigationBar)base.Element; }
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var LeftNavList = new List<UIBarButtonItem>();
var rightNavList = new List<UIBarButtonItem>();
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
for (var i = 0; i < Element.ToolbarItems.Count; i++)
{
var reorder = (Element.ToolbarItems.Count - 1);
var ItemPriority = Element.ToolbarItems[reorder - i].Priority;
if (ItemPriority == 1)
{
UIBarButtonItem LeftNavItems = navigationItem.RightBarButtonItems[i];
LeftNavList.Add(LeftNavItems);
}
else if (ItemPriority == 0)
{
UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
rightNavList.Add(RightNavItems);
}
}
navigationItem.SetLeftBarButtonItems(LeftNavList.ToArray(), false);
navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
}
}
Below MyNavigationBar.cs class in portable/shared forms project
public class MyNavigationBar : NavigationPage
{
public MyNavigationBar(Page content) : base(content)
{
Init();
}
private void Init()
{
this.ToolbarItems.Add(new ToolbarItem() { Icon = "kid", Priority = 0, Order = ToolbarItemOrder.Primary });
this.ToolbarItems.Add(new ToolbarItem() { Text = "License", Priority = 0, Order = ToolbarItemOrder.Primary });
}
}
App starting
public App ()
{
InitializeComponent();
MainPage = new MyNavigationBar(new LoginPage());
}
See below screenshot getting exception
I faced this issue, but in my case, I was trying to get NavigationController from content page which didn't had NavigationController, make sure you null check before calling TopViewController,
var navController = this.NavigationController;
if(navController == null)
{
return;
}
UINavigationItem navigationItem = navController.TopViewController.NavigationItem;
For example,
When User opens the app, he will be presented with Login page, which didn't had any Navigation Bar.

Infinite loop or infinite recursion error in UWP using autosuggestbox

// The class for the search query
public class SearchQueries
{
List<data> list = new List<data>();
string response;
// The method that return the list after it is set
public List<data> GetData()
{
return list;
}
// The method that do the searching from the google API service
public async void SetData()
{
// The problem starts here, when i instantiate the search class in this class in other to get the value of the text in the autosuggestbox for my query, it crashes whenever i try to launch the page. it works fine whenever i give the address default data e.g string address = "London", the page open when i launch it and give me London related result whenever i type in the autosuggestbox.
Search search = new Search();
string address = search.Address;
list.Clear();
// Note the tutorial i used was getting the data from a local folder, but i'm trying to get mine from Google API
string dataUri = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyDBazIiBn2tTmqcSpkH65Xq5doTSuOo22A&input=" + address;
string Api = System.Uri.EscapeDataString(dataUri);
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(1000);
try
{
response = await client.GetStringAsync(Api);
for (uint i = 0; i < jsonarray.Count; i++)
{
string json_string_object = jsonarray.GetObjectAt(i)["description"].ToString();
list.Add(new data() { name = json_string_object });
}
}
catch (TimeoutException e)
{
ContentDialog myDlg = new ContentDialog()
{
PrimaryButtonText = "OK"
};
myDlg.Content = e.ToString();
}
}
// Method to get matched data
public IEnumerable<data> getmatchingCustomer(string query)
{
return list.Where(c => c.name.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) > -1).OrderByDescending(c => c.name.StartsWith(query, StringComparison.CurrentCultureIgnoreCase));
}
// constructor for returning the SetData() method
public SearchQueries()
{
// It points to this method whenever the application crash, with the notification of infinite loop or infinite recursion
SetData();
}
}
// The Main Class of the page
public sealed partial class Search : Page
{
public string theaddress { get; set; }
SearchQueriess queries = new SearchQueriess();
public Search()
{
this.InitializeComponent();
myMap.Loaded += MyMap_Loaded;
theaddress = locationAddress.Text;
}
// The text change method of the autosuggest box.
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
if (sender.Text.Length > 1)
{
var marchingData = queries.getmatchingCustomer(sender.Text);
sender.ItemsSource = marchingData.ToList();
}
else
{
sender.ItemsSource = new string[] { "No suggestion...." };
}
}
}
}

Categories