I got connection error it does not read data from database - c#

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

Related

Static Class Not maintaining its state C#

My question here is why my feed_expiration_date datetime variable becomes null on each request only in server environment it works perfectly on local environment I have a web garden (8 process workers) on both local and server environment.
actually since I have 8 process worker so I have different process ID for example PID:1234 and initially it has the feed_expiration_date value set to some date and when user again request the page with in the expiration period time if the process gets same PID: 1234 then PID:1234 should hold its previous value. in my local it is working as expected but on the server environment it is not working any help would be highly appreciated
public static class CacheManager
{
public static ClientData ClientDataCache
{
get
{
return GetClientDataCacheByID(HostInstanceID);
}
}
public static ClientData GetClientDataCacheByID(int instance_id)
{
try
{
ClientData data = null;
if (instance_id != 0)
data = client_cache_data_dictionary.ContainsKey(instance_id) ? client_cache_data_dictionary[instance_id] : null;
if (data == null || data.GlobalSettingsCache == null || DateTime.UtcNow > data.date_cached.AddHours(1))
return GenerateClientData();
return data;
}
catch (Exception ex)
{
return null;
}
}
private static ClientData GenerateClientData()
{
lock (InstanceLocker)
{
ClientData data = null;
int instance_id = HostInstanceID;
if (instance_id != 0)
data = client_cache_data_dictionary.ContainsKey(instance_id) ? client_cache_data_dictionary[instance_id] : null;
if (data == null || data.GlobalSettingsCache == null || DateTime.UtcNow > data.date_cached.AddHours(1))
{
data = new ClientData(true);
if (data != null && data.InstanceID > 0)
{
int id = data.InstanceID;
HostInstanceID = id;
client_cache_data_dictionary[id] = data; // To prevent race conditions, this has to happen prior to client_data_cache_lock_dictionary[id] = new object();
client_data_cache_lock_dictionary[id] = new object(); // This has to happen 2nd, not first
if (Portals.Utils.IsEC2)
{
try
{
if (!global_cache_mgr_init)
{
GlobalCacheManager.GlobalCacheManager.Initialize(GlobalCacheManager.Enumerations.SystemLocations.AdminPortal, !Portals.Utils.IsEC2 ? "us-west-2" : null);
global_cache_mgr_init = true;
GlobalCacheManager.GlobalCacheManager.Start();
}
}
catch (Exception ex)
{
Emails.SendAdminEmail("Error Init/Start GCM on ClientCache.cs", ex.StackTrace);
}
}
}
Portals.Utils.LogErrorFeed("ReadGSFromDB","true PID: " + System.Diagnostics.Process.GetCurrentProcess().Id);
}
else
{
Portals.Utils.LogErrorFeed("ReadGSFromCache", "true PID: " + System.Diagnostics.Process.GetCurrentProcess().Id);
}
return data;
}
}
public class ClientData
{
public ClientData(bool initdata = false) {
if (initdata) IntializeClientData();
}
private List<SurveysAndFeaturesFeedResult> surveyAndFeaturesFeeds = null;
public DateTime date_cached { get; set; }
public DateTime? feed_expiration_date { get;set;}
private object surveys_features_generate_locker = new object();
public void GenerateSurveysAndFeaturesCache(bool force_refresh = false)
{
if(this.InstanceID != 0)
{
lock(surveys_features_generate_locker)
{
if (this.surveyAndFeaturesFeeds == null || force_refresh)
{
this.surveyAndFeaturesFeeds = CakeFeed.GetSurveysAndFeaturesFeedResult();
this.feed_expiration_date = DateTime.UtcNow.AddHours(this.global_settings.CakeFeedCacheDurationHoursCKM);
}
}
if(force_refresh && this.surveyAndFeaturesFeeds != null)
{
Portals.Utils.RefreshPortals();
}
}
}
public List<SurveysAndFeaturesFeedResult> SurveysAndFeaturesFeed
{
get
{
if(this.global_settings.EnablePresentIcon && (surveyAndFeaturesFeeds == null || feed_expiration_date == null || feed_expiration_date < DateTime.UtcNow))
{
GenerateSurveysAndFeaturesCache();
}
return (surveyAndFeaturesFeeds == null) ? new List<SurveysAndFeaturesFeedResult>() : surveyAndFeaturesFeeds.ToList();
}
}
}
}
And from handler.ashx I call this as CacheManager.ClientDataCache.SurveysAndFeaturesFeed.OrderByDescending(x=>x.PublishDate).ToList();

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

WPF singelton intance gives null exception, before singelton value is set

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?

Select and Match Data from List using LINQ C#

I have data in List, and i want to do login if data matches with any of records.
public HttpResponseMessage Post(form model)
{
List<form> user = new List<form>();
user.Add(new form { username = "admin", password = "admin" });
user.Add(new form { username = "Gopal", password = "123" });
user.Add(new form { username = "niit", password = "niit" });
if (model.username == user.Select(p => p.username.Equals(model.username))
{
}
}
I want to like this - (Done with Hard coded data)
if (model.username == "admin" && model.password == "admin")
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }
This is my Model Class - Form
public class form
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}
I have done this with hard coded data but want to do with list. Please help me this out. How Can I do it?
Try this way
if (user.Where(a => a.username == model.username && a.password == model.password).Select(p => p).Count() != 0)
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
or you can simply use any
if (user.Any( a => a.username.Contains(model.username) && a.password.Contains(model.password)))
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
I hope this isn't production code! You will want to use password salting + hashing if that user data is being stored. Best not to write your own code with this kind of stuff if you aren't experienced.
BUT to answer your question, you most likely want this:
user.Any(u => u.username == model.username && u.password == model.password)
There are better data structures though. For example, a Dictionary will allow O(1) lookup of the user (form?) by username rather than needing to iterate through the whole collection.
You can do this,
if (user.Any(use => model.username.Contains(use.username) && model.username.password(use.password))
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }
Use following code:
if (user.Where(x=> x.username.Equals(model.username) && x.password.Equals(model.password)).FirstOrDefault() != null)
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }
hope it will help you.

Constraint Violation When Creating AD User Object with account management extension class attributes

I'm creating a WCF service to retrieve and update/create AD Person objects, and have run into a snag. I created an extension class to manage extended attributes (delivered schema attributes, but not in the default account management class attribute set). I have no problem retrieving or updating these extended attributes, but when I try to create a new person object in AD, I receive a constraint violation
System.DirectoryServices.DirectoryServicesCOMException: A constraint violation occurred.
I'm currently testing this in debug mode in Visio 2013 on a Windows 8.1 desktop. Code below. Any hints or insight anyone can offer is most appreciated.
Hopefully the code below is documented well enough and makes sense. Thanks in advance!
Update: I should have been more clear. The reason I am pretty sure it is the extension attributes is when I comment out those lines in the calling code (now commented in code section below) that set those attributes it will create the object without errors.
This is my calling code:
....other code.....
PrincipalContext pc = null;
try {
pc = new PrincipalContext(ContextType.Domain, MyProject.ADAccountService.Properties.Settings.Default.Domain, MyProject.ADAccountService.Properties.Settings.Default.PeopleDN, MyProject.ADAccountService.Properties.Settings.Default.AdminAcct, MyProject.ADAccountService.Properties.Settings.Default.AdminPW);
}
catch (Exception e) {
defaultLogger.Warn(MyProject.ADAccountService.App_GlobalResources.Messages.PrincipalContextCreateFail, e);
// Application.Exit();
}
....other code looking for whether ADObject already exists...
// Create the new UserPrincipal object
if (!newADPerson.personExists) {
using (ADeXt userNew = new ADeXt(pc)) {
string randomPassword = System.Web.Security.Membership.GeneratePassword(20, 4);
if (newADPerson.officePhone != null && newADPerson.officePhone.Length > 0) { userNew.VoiceTelephoneNumber = newADPerson.officePhone; }
if (newADPerson.department != null && newADPerson.department.Length > 0) { userNew.department = newADPerson.department; } //offending codeline
if (newADPerson.title != null && newADPerson.title.Length > 0) { userNew.title = newADPerson.title; } //offending codeline
if (newADPerson.faxNumber != null && newADPerson.faxNumber.Length > 0) { userNew.facsimileTelephoneNumber = newADPerson.faxNumber; } //offending codeline
if (newADPerson.officeLocation != null && newADPerson.officeLocation.Length > 0) { userNew.physicalDeliveryOfficeName = newADPerson.officeLocation; } //offending codeline
if (newADPerson.isEmployee) {
//if an employee and (newADPerson.script == null) use default value from global project settings
userNew.ScriptPath = newADPerson.script ?? MyProject.ADAccountService.Properties.Settings.Default.defaultScript;
}
if (newADPerson.lastName != null && newADPerson.lastName.Length > 0) { userNew.Surname = newADPerson.lastName; }
if (newADPerson.firstName != null && newADPerson.firstName.Length > 0) { userNew.GivenName = newADPerson.firstName; }
if (newADPerson.emplID != null) { userNew.EmployeeId = newADPerson.emplID; }
if (newADPerson.displayName != null && newADPerson.displayName.Length > 0) { userNew.DisplayName = newADPerson.displayName; }
userNew.SamAccountName = AccountID;
userNew.Name = AccountID;
userNew.UserPrincipalName = AccountID + MyProject.ADAccountService.Properties.Settings.Default.ExchangeAddress;
try {
userNew.Save();
userNew.SetPassword(randomPassword);
}
catch (Exception e) {
pc.Dispose();
}
}
}
Extension class code:
namespace MyProject.ADAccountService.Classes {
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class ADeXt : UserPrincipal {
public ADeXt(PrincipalContext context)
: base(context) {
}
public ADeXt(
PrincipalContext context,
string Container, //new constructor parameter added resolving issue
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
public static new ADeXt FindByIdentity(PrincipalContext context, string identityValue) {
return (ADeXt)FindByIdentityWithType(context, typeof(ADeXt), identityValue);
}
[DirectoryProperty("physicalDeliveryOfficeName")]
public string physicalDeliveryOfficeName {
get {
object[] result = this.ExtensionGet("physicalDeliveryOfficeName");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("physicalDeliveryOfficeName", value);
}
}
[DirectoryProperty("department")]
public string department {
get {
object[] result = this.ExtensionGet("department");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("department", value);
}
}
[DirectoryProperty("title")]
public string title {
get {
object[] result = this.ExtensionGet("title");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("title", value);
}
}
[DirectoryProperty("facsimileTelephoneNumber")]
public string facsimileTelephoneNumber {
get {
object[] result = this.ExtensionGet("facsimileTelephoneNumber");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("facsimileTelephoneNumber", value);
}
}
}
}
Thanks Marc, that hint helped me solve. added new parameter for the container in the extension constructor and that did the trick.
Changed the constructor in the extension class to add the default container. New constructor now lists like this:
public ADeXt(
PrincipalContext context,
**string Container,**
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
For anyone looking into this error. It could mean a lot of things, the first Google results will show that it has something to do with the PDC Emulator or replicating.
In my case it was due to too many characters for the employeeID (16 max). Sometimes it is initials (6 max) or samAccountName (19 max). Just peel of fields until it works as a starting point.

Categories