Here's my method:
public bool UserExistsActiveDir()
{
try
{
const int ADS_UF_ACCOUNTDISABLE = 0x00000002;
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainname;
DirectorySearcher objADSearcher = new DirectorySearcher(de);
de.AuthenticationType = AuthenticationTypes.Secure;
objADSearcher.SearchRoot = de;
objADSearcher.Filter = "(SAMAccountName=" + txtUserName.Text + ")";
SearchResult results = objADSearcher.FindOne();
if (results.ToString() != "")
{
int flags = Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
return false;
}
}
Where am I going wrong? It says missing return but as far I know, all my return statements are there.
You need an else to this if statement:
if (results.ToString() != "")
What happens if the string is not empty? You need to return a value for that case.
there is no return in case
if (results.ToString() == "")
public bool UserExistsActiveDir()
{
try
{
const int ADS_UF_ACCOUNTDISABLE = 0x00000002;
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainname;
DirectorySearcher objADSearcher = new DirectorySearcher(de);
de.AuthenticationType = AuthenticationTypes.Secure;
objADSearcher.SearchRoot = de;
objADSearcher.Filter = "(SAMAccountName=" + txtUserName.Text + ")";
SearchResult results = objADSearcher.FindOne();
if (results.ToString() != "")
{
int flags = Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
// <-here
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
return false;
}
}
There's no return value when if (results.ToString() != "") returns false.
All of your returns are inside this if statement:
if (results.ToString() != "")
{
int flags =
Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
But what heppens if results.ToString() is ""...there's no return value.
There's no else for the if (results.ToString() != "") statement.
if (results.ToString() != "")
{
...
}
else
{
return false; // or whatever fits in your logic
}
Or without nesting:
if (results.ToString() != "")
{
...
}
return false; // or whatever fits in your logic
Related
I have a way here how I check multiple variables for null, and fill them with the correct data according to the nullness. However, this way is very messy and I am now wondering if there is a better way to do this.
`
try
{
user = new ADUser();
nextEntry = ldapSearch.Next();
var attName = nextEntry.getAttribute("name");
var attMail = nextEntry.getAttribute("mail");
var attTelephone = nextEntry.getAttribute("telephoneNumber");
if(attName == null || attMail == null || attTelephone == null)
{
if( attName == null)
{
user.name = "";
}
else
{
user.name = attName.StringValue;
}
if(attMail == null)
{
user.mail = "";
}
else
{
user.mail = attMail.StringValue;
}
if(attTelephone == null)
{
user.telephone = "";
}
else
{
user.telephone = attTelephone.StringValue;
}
}
else
{
user.name = attName.StringValue;
user.mail = attMail.StringValue;
user.telephone = attTelephone.StringValue;
}
model.ADUserList.Add(user);
}
catch
{
continue;
}
`
I have tried it my way, but I think it can be done cleaner.
yes, you can achive the same result without any 'if-else':
user.name = attName?.StringValue ?? "";
user.mail = attMail?.StringValue ?? "";
user.telephone = attTelephone?.StringValue ?? "";
you can also write an extension method to return the empty string:
public static class StringExtensions
{
public static string EmptyIfNull(this string str)
{
return str ?? String.Empty;
}
}
and then use it like this:
user.name = attName?.StringValue.EmptyIfNull();
user.mail = attMail?.StringValue.EmptyIfNull();
user.telephone = attTelephone?.StringValue.EmptyIfNull();
I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.
I am creating a method for checking the product key. everything working fine in bltoolkit the code is
private void CheckKey()
{
try
{
using (DbManager db = new DbManager())
{
DataTable dt = db
.SetCommand("SELECT TOP 1 * FROM TblReg WHERE ProductKey=#ProductKey",
db.Parameter("#ProductKey", CommanClass.strRegkey))
.ExecuteDataTable();
if (dt.Rows.Count == 0)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = dt.Rows[0].Field<string>("ProductKey");
GetSoftKey = true;
}
}
if ((GetSoftKey == true) && (strSoftKey != null))
{
if (strSoftKey == CommanClass.strRegkey)
{
SoftwareKey = true;
}
else
{
SoftwareKey = false;
}
}
}
catch (Exception)
{
SoftwareKey = false;
}
}
Now in When I try to write a method using entity framework for checking product key, it's confusing me at how to pass DataTable variable DataTable dt = login into entity context and set entity query parameter login.Parameter("#ProductKey", CommanClass.strRegkey), the code is
private void CheckKey()
{
try
{
using (loginEntities login = new loginEntities())
{
var pKey= from pk in login.tblSoftRegs
where pk.ProductKey == pk.ProductKey
select pk.ProductKey.FirstOrDefault();
if (pKey.Count() == 0)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = ("ProductKey");
GetSoftKey = true;
}
}
if ((GetSoftKey == true) && (strSoftKey != null))
{
if (strSoftKey == CommanClass.busRegkey)
{
SoftwareKey = true;
}
else
{
SoftwareKey = false;
}
}
}
catch (Exception)
{
SoftwareKey = false;
}
}
Waiting for community contribution...
You've almost got it. FirstOrDefault will return null if there are none found, and you bind local variables directly into your LINQ query. Like this:
var pKey= from pk in login.tblSoftRegs
where pk.ProductKey == CommanClass.strRegkey
select pk.ProductKey.FirstOrDefault();
if (pKey == null)
{
GetSoftKey = false;
strSoftKey = null;
}
else
{
strSoftKey = ("ProductKey");
GetSoftKey = true;
}
I'm trying to update the user properties but I get an error :
The attribute syntax specified to the directory service is invalid
It happens when I do CommitChanges(), this code worked for me before so I don't know what is wrong.
This is the code:
DirectoryEntry de = new DirectoryEntry(_ldap);
DirectorySearcher ds = new DirectorySearcher(de) { Filter = "(&(objectClass=user)(SamAccountName=" + logon_tb.Text + "))" };
SearchResult sr = ds.FindOne();
DirectoryEntry userEntry = sr.GetDirectoryEntry();
try { userEntry.Properties["givenName"].Value = fn_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["sn"].Value = ln_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["displayName"].Value = dispName_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["description"].Value = description_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["physicalDeliveryOfficeName"].Value = office_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["telephoneNumber"].Value = telephone_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["mobile"].Value = mobile_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["title"].Value = jobTitle_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["department"].Value = department_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["postOfficeBox"].Value = poBox_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["homeDirectory"].Value = homeFolder_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute10"].Value = extAtt10_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute11"].Value = extAtt11_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute12"].Value = extAtt12_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute13"].Value = extAtt13_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute14"].Value = extAtt14_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute15"].Value = extAtt15_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["SamAccountName"].Value = logon_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["userPrincipalName"].Value = logonPrincipal_tb.Text; }
catch (Exception) { }
if (pwNeverExpire_cb.Checked)
userEntry.Properties["userAccountControl"].Value = 66048;
userEntry.CommitChanges();
userEntry.Close();
DirectoryEntry de = new DirectoryEntry(_ldap);
DirectorySearcher ds = new DirectorySearcher(de) { Filter = "(&(objectClass=user)(SamAccountName=" + logon_tb.Text + "))" };
SearchResult sr = ds.FindOne();
DirectoryEntry userEntry = sr.GetDirectoryEntry();
if (fn_tb.Text != "")
userEntry.Properties["givenName"].Value = fn_tb.Text;
else
userEntry.Properties["givenName"].Value = null;
if (ln_tb.Text != "")
userEntry.Properties["sn"].Value = ln_tb.Text;
else
userEntry.Properties["sn"].Value = null;
if (dispName_tb.Text != "")
userEntry.Properties["displayName"].Value = dispName_tb.Text;
else
userEntry.Properties["displayName"].Value = null;
if (description_tb.Text != "")
userEntry.Properties["description"].Value = description_tb.Text;
else
userEntry.Properties["description"].Value = null;
if (office_tb.Text != "")
userEntry.Properties["physicalDeliveryOfficeName"].Value = office_tb.Text;
else
userEntry.Properties["physicalDeliveryOfficeName"].Value = null;
if (telephone_tb.Text != "")
userEntry.Properties["telephoneNumber"].Value = telephone_tb.Text;
else
userEntry.Properties["telephoneNumber"].Value = null;
if (mobile_tb.Text != "")
userEntry.Properties["mobile"].Value = mobile_tb.Text;
else
userEntry.Properties["mobile"].Value = null;
if (jobTitle_tb.Text != "")
userEntry.Properties["title"].Value = jobTitle_tb.Text;
else
userEntry.Properties["title"].Value = null;
if (department_tb.Text != "")
userEntry.Properties["department"].Value = department_tb.Text;
else
userEntry.Properties["department"].Value = null;
if (poBox_tb.Text != "")
userEntry.Properties["postOfficeBox"].Value = poBox_tb.Text;
else
userEntry.Properties["postOfficeBox"].Value = null;
if (homeFolder_tb.Text != "")
userEntry.Properties["homeDirectory"].Value = homeFolder_tb.Text;
else
userEntry.Properties["homeDirectory"].Value = null;
if (extAtt10_tb.Text != "")
userEntry.Properties["extensionAttribute10"].Value = extAtt10_tb.Text;
else
userEntry.Properties["extensionAttribute10"].Value = null;
if (extAtt11_tb.Text != "")
userEntry.Properties["extensionAttribute11"].Value = extAtt11_tb.Text;
else
userEntry.Properties["extensionAttribute11"].Value = null;
if (extAtt12_tb.Text != "")
userEntry.Properties["extensionAttribute12"].Value = extAtt12_tb.Text;
else
userEntry.Properties["extensionAttribute12"].Value = null;
if (extAtt13_tb.Text != "")
userEntry.Properties["extensionAttribute13"].Value = extAtt13_tb.Text;
else
userEntry.Properties["extensionAttribute13"].Value = null;
if (extAtt14_tb.Text != "")
userEntry.Properties["extensionAttribute14"].Value = extAtt14_tb.Text;
else
userEntry.Properties["extensionAttribute14"].Value = null;
if (extAtt15_tb.Text != "")
userEntry.Properties["extensionAttribute15"].Value = extAtt15_tb.Text;
else
userEntry.Properties["extensionAttribute15"].Value = null;
if (logon_tb.Text != "")
userEntry.Properties["SamAccountName"].Value = logon_tb.Text;
else
userEntry.Properties["SamAccountName"].Value = null;
if (idNumber_tb.Text != "")
userEntry.Properties["userPrincipalName"].Value = idNumber_tb.Text;
else
userEntry.Properties["userPrincipalName"].Value = null;
userEntry.CommitChanges();
userEntry.Close();
I did it like that and it worked with no problems.
I can't figure this out why I keep getting the compilation error: "not all code paths return a value". I am writing a simple class method that is supposed to return true if the account is available to use and false if the account is not available or is null/empty. The code for the method is below:
public static bool AccountAvailable(int AccountId)
{
try
{
bool accountavailable;
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
return accountavailable;
}
catch
{
}
}
Any help or advice on this would be appreciated. Thanks!!
If an exception is thrown in your code before you return a value then control moves to the catch block. It then reaches the end of the method without returning anything.
Either return something within, or after, the catch block.
In your catch block, add a return:
catch (Exception ex)
{
// your code
return null;
}
The suggest to try this code
public static bool AccountAvailable(int AccountId)
{
bool accountavailable = false;
try
{
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
}
catch
{
}
return accountavailable;
}