I am trying to make a bool property that would toggle the pwdLastSet property.
public bool UserMustChangePassword
{
get { return (long)Entry.Properties["pwdLastSet"].Value == 0; }
set
{
if (value)
{
Entry.Properties["pwdLastSet"].Value = 0;
}
else
{
Entry.Properties["pwdLastSet"].Value = -1;
}
}
}
I can set the property successfully however I cant read the property. I keep getting the following casting error.
System.InvalidCastException: 'Specified cast is not valid.'
Is there a specific way to read this property. I know it may be possible to UserPrincipal, however I would like to use DirectoryEntry to keep the code consistent.
Edit: check null before casting
public bool UserMustChangePassword
{
get
{
var value = Entry.Properties["pwdLastSet"].Value;
if (value != null)
return (long)Entry.Properties["pwdLastSet"].Value == 0;
return false;
}
set
{
if (value)
{
Entry.Properties["pwdLastSet"].Value = 0;
}
else
{
Entry.Properties["pwdLastSet"].Value = -1;
}
}
}
You need to check its Count property to make sure there is a value. Try this,
if (Entry.Properties["pwdLastSet"].Count > 0)
{
return (Entry.Properties["pwdLastSet"][0] == 0)
}
else
return false;
Edit:
Seems the problem comes from that you are querying Properties of DirectoryEntry instead of SearchResult. See this question. I have a copy of working code that is also querying SearchResult.
Related
I am trying to perform a delete but I need to make sure that a value is present before trying to delete. The value is pulled from the database. I need to check for dbnull. If it's not, then the delete can go ahead. I have tried the following but it does not work:
if (!DBNull.Value.Equals(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
When I try I get the following exception:
Inner Exception Type: System.InvalidCastException
Unable to cast object of type 'System.DBNull' to type 'System.String'.
Inner Source: App_Code.bvtnyzaw
Inner Stack Trace:
at Products.GetAllProdColoursRow.get_ColourImage() in c:\Users\micha\AppData\Local\Temp\Temporary ASP.NET Files\vs\d9cd3740\a9faac06\App_Code.bvtnyzaw.2.cs:line 2245
Exception Type: System.Data.StrongTypingException
Exception: The value for column 'ColourImage' in table 'GetAllProdColours' is DBNull.
****EDIT****
I have already seen the suggested question but none of those solutions seemed to help. No matter what I try I get the same exception.
**** My complete code using the suggested answer but still I get the same exception ****
public bool DeleteProductColour(int colid, int prd)
{
bool prodColourDeleted = false;
try
{
var x = pcAdp.GetAllProdColours(prd).AsEnumerable().Where(y => y.ColourId == colid).First();
if (x != null && !string.IsNullOrEmpty(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
pcAdp.DeleteProductColour(colid);
prodColourDeleted = true;
}
catch(Exception er)
{
ExceptionUtility.LogException(er, "Delete product colour - ProductsBLL");
}
return prodColourDeleted;
}
* UPDATE *
I have tried the following but I get an exception:
public bool DeleteProductColour(int colid, int prd)
{
bool prodColourDeleted = false;
try
{
var x = pcAdp.GetAllProdColours(prd).ToList();
if (x.Any())
{
var colour = x.Where(y => y.ColourId == colid).FirstOrDefault();
if (colour != null && !string.IsNullOrEmpty(colour.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(colour.ColourImage));
}
}
pcAdp.DeleteProductColour(colid);
prodColourDeleted = true;
}
catch (Exception er)
{
ExceptionUtility.LogException(er, "Delete product colour - ProductsBLL");
}
return prodColourDeleted;
}
The exception I get is
'product.ColourImage' threw an exception of type 'System.Data.StrongTypingException'
In the strongly typed DataSet this kind of problem occurs.
Probably before filling your Dataset, get the respective DataColumn and set the DataColumn.AllowDBNull to true.
https://msdn.microsoft.com/en-us/library/system.data.datacolumn.allowdbnull(v=vs.110).aspx
use
if(!string.IsnullOrEmpty(x.ColourImage)){}
if still getting error you are need to check x is null or is not null;
if(x!=null&&!string.IsnullOrEmpty(x.ColourImage)){}
Or another option would work is;
if(x.ColourImage!= DBNull.Value){}
//I think this method mmight be work
public bool DeleteProductColour(int colid, int prd)
{
bool prodColourDeleted = false;
try
{
var x = pcAdp.GetAllProdColours(prd).AsEnumerable().Where(y => y.ColourId == colid).FirstOrDefault();
if (x != null && !string.IsnullOrEmpty(x.ColourImage))
{
File.Delete(HttpContext.Current.Server.MapPath(x.ColourImage));
}
pcAdp.DeleteProductColour(colid);
prodColourDeleted = true;
}
catch(Exception er)
{
ExceptionUtility.LogException(er, "Delete product colour - ProductsBLL");
}
return prodColourDeleted;
}
I want to script our sap. Actually, I'm scripting the comboboxes. But I don't know, how to select a specific item.
SAPFEWSELib.dll included as refernece
public static bool SelectComboBoxItem(string ItemText)
{
int i = 0, ItInd = -1;
SAPFEWSELib.GuiComboBox GCB = GetComboBox(GFW, Criteria, Type); /*This function returns the SAPFEWSELib.GuiComboBox and works correctly*/
if (GCB != null)
{
foreach (SAPFEWSELib.GuiComboBoxEntry Entry in GCB.Entries)
{
if (Entry.Value.ToUpper().IndexOf(Item.ToUpper()) != -1)
{
/*How to select this Entry?*/
/*GCB.Entries.Item(Entry.Pos).Select() is a not contained methode*/
/*GCB.Entries.Item(Entry.Pos).Selected = true This functions for GuiTableRows and GuiGridViewRows, but not here*/
return true;
} else {
i++;
}
}
}else{
throw new System.Exception("ERROR: Unable to find combobox with current criteria!");
}
return false;
}
Does anybody has an Idea?
Ok, got it.
GCB.Value = Entry.Value;
In my testcase, the combobox was not changeable, so it never functioned.
Sometimes I find myself writing a bool method that looks like this:
public bool isRunning()
{
if (!(move == Moving.None) && staminaRegan == true)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
(This is XNA by the way) As you can see, I have a bool isRunning in which I made an if statement where Im checking if (Player is moving) && (regains stamina, which is set to false once stamina reaches value lesser than 6.0f)
and then I simply check if Space is pressed, if yes then my Animation is faster(the smaller the interval, the faster is spritesheet changing), and then It sends true value, which means that Player is running, else Im not cause Space is not pressed.
And then I have to repeat this 'else' code outside of the first if statement so it sends that Player is not running if Player is not moving or his stamina Regan is false;
So I was just wondering is this kind of a bool method considered a bad practice(where you retrun true and false value in nested if, and then return false outside nested if and repeat the same code) ?
The method has a side effect, that's why it's a bad practice:
public bool isRunning()
When looking on method's signature we expect just true/false answer and nothing more. However, the method changes the instance's state:
...
if (!(move == Moving.None) && staminaRegan == true)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10; // <- Aaa! The interval is changed
return true;
}
...
I suggest splitting the initial method into a property and a method
// No side effect: just answer is running or not
public bool IsRunning {
get {
return (move != Moving.None) && staminaRegan && KeyState.IsKeyDown(Keys.Space);
}
}
// Put the right interval based on instance internal state
// (if it's running etc.)
public void AdjustInterval() {
if (IsRunning) // and may be other conditions
EntityAnimation.interval = 10; //TODO: move magic number into constant
else
EntityAnimation.interval = 65; //TODO: move magic number into constant
}
It is a good practice to have one return statement inside a method. Some argue about this, but it is an opinion.
it is also a good practice to make the if statement clear by removing unnecessary code:
public bool isRunning()
{
bool result = false;
if (move != Moving.None && staminaRegan)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
result = true;
}
else
{
EntityAnimation.interval = 65;
}
}
else
{
EntityAnimation.interval = 65;
}
return result;
}
You can rewrite the code as follows; then the code isn't repeated:
public bool isRunning()
{
if (move != Moving.None && staminaRegan && keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
Or if you don't want the redundant else:
public bool isRunning()
{
if (move != Moving.None && staminaRegan && keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
EntityAnimation.interval = 65;
return false;
}
I would consider introducing a named boolean to self-document somewhat, and I'd rename staminaRegan to staminaIsRegenerating
public bool isRunning()
{
bool isMovingQuickly = (move != Moving.None) && staminaIsRegenerating && keyState.IsKeyDown(Keys.Space);
if (isMovingQuickly)
EntityAnimation.interval = 10;
else
EntityAnimation.interval = 65;
return isMovingQuickly;
}
Most importantly, though, you should rename the method to more accurately describe what it's doing:
public bool CheckIfRunningAndSetAnimationInterval()
I think we write code for people(other developers), of course machine execute a code but 80% of developer's work is reading the code.
Based on that I think flow of reading must be exactly same as flow of executing code - that's why I think multiply return statement not a bad thing, even better then only one return statement on the bottom of your method.
I like this style and i use it too. First, you can read the code more easily and second it has a debugging advantage as you can set breakpoints for the individual else cases. Otherwise you would need to use breakpoint conditions.
here is my code
public bool limitOutput()
{
double lowerLeftPointX = m_mapControl.CurrentExtent.LowerLeftPoint.X;
double lowerLeftPointY = m_mapControl.CurrentExtent.LowerLeftPoint.Y;
double upperRightPointX = m_mapControl.CurrentExtent.UpperRightPoint.X;
double upperRightPointY = m_mapControl.CurrentExtent.UpperRightPoint.Y;
for(int i = locationElements.Count - 1; i >= 0; i--)
{
if (Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) < lowerLeftPointX || Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) > upperRightPointX || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) < lowerLeftPointY || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) > upperRightPointY)
{
locationElements[i].ParentNode.RemoveChild(locationElements[i]);
}
}
if (locationElements.Count == 0)
{
PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
return false;
}
return true;
}
I am trying to delete all the nodes which are not within the boundary I have set. The delete line is executed but does not actually delete as when I count locationElements it is still the same value before the method is executed.
Any ideas what is wrong with the code
The problem is due to the fact that RemoveChild() removed the element from the source XmlDocument, but not from the pre-populated XmlNodeList. So you need to execute again the code that was used to pre-populate locationElements variable, something like this :
//assume that GetLocationElements() is a method...
//...containing the same logic you used to populate locationElements variable
var updatedLocationElements = GetLocationElements();
if (updatedLocationElements.Count == 0)
{
PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
return false;
}
return true;
I'm attempting to iterate through all the textboxes in my WPF window to see if they are empty, and if they are, the method should set a bool to true.
private void checkTextBoxes(DependencyObject obj)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
if (obj is TextBox && ((TextBox)obj).Text == null)
{
isTextBoxEmpty = true;
}
}
}
isTextBoxEmpty is my bool that has been defined outside of the method. I call the method using:
checkTextBoxes(this);
But the bool always returns false no matter what I do, even if all the text boxes are empty.
Try to change this :
((TextBox)obj).Text == null)
To this :
(String.IsNullOrEmpty((TextBox)obj).Text))
The result you got possibly because TextBox's Text is never null, it is empty string ("") by default, thats what I think, just possibly.
Outside of any syntax errors this should give you the result you expect; This only returns true if ALL textboxes are blank
private void checkTextBoxes(DependencyObject obj)
{
var trueforall = true;
var atleastone = false;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
if (obj is TextBox)
{
if(!atleastone){ atleastone = true;}
trueforall &= string.IsNullOrWhiteSpace(((TextBox)obj).Text);
if (!trueforall) { break; }
}
}
isTextBoxEmpty = trueforall && atleastone;
}