I have an if else tree that is going to grow as I add additional items for it to maintain and I'm looking at the best way to write it for maintainability I'm starting with this code
private void ControlSelect()
{
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = true;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = true;
multiLoadControl.Visible = false;
}
}
and thinking of re-factoring it to something like this
private void ControlSelect()
{
List<UserControl> controlList = GetControlList();
string visableControl = singleLoadControl.ID;
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
visableControl = singleLoadControl.ID;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
visableControl = singleTruckControl.ID;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
visableControl = multiLoadControl.ID;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
visableControl = multiTruckControl.ID;
}
foreach (UserControl userControl in controlList)
{
userControl.Visible = (userControl.ID == visableControl);
}
}
private List<UserControl> GetControlList()
{
List<UserControl> controlList = new List<UserControl>
{
singleLoadControl,
multiTruckControl,
singleTruckControl,
multiLoadControl
};
return controlList;
}
I take a performance hit but I can manage all of my controls is a single place
my other thought was to make each selected control block it own method, something like this
private void SetSingleLoadControlAsSelected()
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
I don't take a performance hit but I'm maintaining the controls in multiple location
I'm leaning for option one just because I like maintainability aspect of it.
what about
singleLoadControl.Visible =
PostingType == PostingTypes.Loads && !IsMultiPost;
singleTruckControl.Visible =
PostingType == PostingTypes.Trucks && !IsMultiPost;
multiTruckControl.Visible =
PostingType == PostingTypes.Loads && IsMultiPost;
multiLoadControl.Visible =
PostingType == PostingTypes.Trucks && IsMultiPost;
if you want capability to make multiple controls visible (or add more enumerated values) decorate the enum with [Flags] attribute as follows:
[Flags]
public enum PostTyp { None=0, IsMultiPost = 1, Loads = 2, Trucks = 4 }
and modify Code as follows:
singleLoadControl.Visible =
((PostingType & (PostTyp.Loads | ~PostTyp.MultiCast))
== PostingType );
singleTruckControl.Visible =
((PostingType & (PostTyp.Trucks | ~PostTyp.MultiCast))
== PostingType );
multiTruckControl.Visible =
((PostingType & (PostTyp.Loads | PostTyp.MultiCast))
== PostingType );
multiLoadControl.Visible =
((PostingType & (PostTyp.Trucks | PostTyp.MultiCast))
== PostingType );
As you appear to be using an enumeration, I would recommend a switch with a default case to cope with unknown values. I believe this approach makes intentions clearer than doing all the checking in the assignment.
switch (PostingType)
{
case PostingTypes.Loads:
singleLoadControl.Visible = !IsMultiPost;
multiTruckControl.Visible = IsMultiPost;
singleTruckControl.Visible = false;
multiTruckLoadControl.Visible = false;
break;
case PostingTypes.Trucks:
singleLoadControl.Visible = false;
multiTruckControl.Visible = false;
singleTruckControl.Visible = !IsMultiPost;
multiLoadControl.Visible = IsMultiPost;
break;
default:
throw InvalidOperationException("Unknown enumeration value.");
}
What about this:
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleTruckControl.Visible = true;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
multiLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
multiTruckControl.Visible = true;
}
If it would be otherwise sensible (for example, if these are already domain-specific custom controls), you could encapsulate the logic inside the controls themselves (Replace Conditional with Polymorphism). Perhaps create an interface like this:
public interface IPostingControl {
void SetVisibility(PostingType postingType, bool isMultiPost);
}
Then each control would be responsible for its own visibility rules:
public class SingleLoadControl: UserControl, IPostingControl {
// ... rest of the implementation
public void SetVisibility(PostingType postingType, bool isMultiPost) {
this.Visible = postingType == PostingType.Load && !isMultiPost);
}
}
Finally, in your page, just iterate over your IPostingControls and call SetVisibility(postingType, isMultiPost).
If you are expecting to be adding a lot of different parameters, you could create a multi-dimensional array of objects
Arr[0][0] = singleLoadControl
Arr[0][1] = singleTruckControl
Arr[1][0] = multiLoadControl
Arr[1][1] = multiTruckControl
This is pretty scary, but makes for simpler if statements. If you're going to have loads of references to the controls anyhow, I'd rather use a code-based representation of what those loads are. Such an array can be wrapped in a class to let you access the elements using something more like:
ControlClassInstance.single.truck
You'd have code like this:
p1 = IsMultiPost ? ControlClassInstance.multi : ControlClassInstance.single
p2 = p1[PostingType] //(this call would mean adding an indexer)
This kind of solution is way too sophisticated unless you expect things to get complicated...and might be poor then, too.
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
singleLoadControl.Visible = (PostingType == PostingTypes.Loads && !IsMultiPost);
singleTruckControl.Visible = (PostingType == PostingTypes.Trucks && !IsMultiPost);
multiLoadControl.Visible = (PostingType == PostingTypes.Loads && IsMultiPost);
multiTruckControl.Visible = (PostingType == PostingTypes.Trucks && IsMultiPost);
Have you considered the State Pattern?
private void ControlSelect()
{
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
return;
}
if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = true;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
return;
}
if (PostingType == PostingTypes.Loads && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = true;
return;
}
if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = true;
multiLoadControl.Visible = false;
return;
}
}
Related
I managed to create a TreeView method for NodeMouseClick and CursorChanged events.
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
// my action code here...
}
private void TvwPanel_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
Node_Selection_Action(sender, e);
}
However, I am getting an error on e parameter when I applied the method to the CursorChanged:
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
Node_Selection_Action(sender, e); //error on `e` here
}
I supposed this is due to the parameter EventArgs that is not compatible with my method parameter TreeNodeMouseClickEventArgs.
Is there any workaround that I could use to trigger the CursorChanged event with my method?
UPDATE 1:
As requested, here's the bunch of code for the Node_Selection_Action method:
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
TvwPanel.SelectedNode = e.Node;
if (Convert.ToString(e.Node.Tag) == "a") //profile Convert.ToInt16()
{
TsmNewPr.Enabled = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Enabled = true;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Enabled = true;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "b") //database
{
TsmNewPr.Visible = false;
TsmNewDb.Enabled = true;
// arbitrary control if database already exists. If exists disable, otherwise enable.
#region TsmNewDb.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Type" || childText.Value != "Name" || childText.Value != "Connection")
{
// enable TsmNewDb ContextMenu button if does not exists yet
TsmNewDb.Enabled = false;
}
}
// initialize the attribute tags to null
string TypeTag = null;
string NameTag = null;
string ConnTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
TypeTag = childTag.Value;
}
else if (count == 1)
{
NameTag = childTag.Value;
}
else if (count == 2)
{
ConnTag = childTag.Value;
}
count++;
}
// check if database exists
if (db.Databases_Exists(ConnTag) == true)
{
// convert the password to "*" for display purposes
string s = ConnTag;
int start = s.LastIndexOf("pwd=") + "pwd=".Length;
int end = s.IndexOf(";", start);
string result = s.Substring(start, end - start);
s = s.Replace(result, "********");
ConnTag = s;
// transfer data FrmDatabase form to main form tabcontrol panel
LblDbTypeDef.Text = TypeTag;
LblDbNameDef.Text = NameTag;
LblDbConnDef.Text = ConnTag;
// make the main tabcontrol panel visible to true
TbcMain.SelectedIndex = 0;
TbcMain.Visible = true;
}
else
{
// make the main tabcontrol panel visible to false
TbcMain.SelectedIndex = 0;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Enabled = true;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Enabled = true;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "c") //company file
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Enabled = true;
// arbitrary control if company file already exists. If exists, disable, otherwise enable.
#region TsmNewCo.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Company Name" || childText.Value != "File Path")
{
// enable TsmNewCo ContextMenu button if does not exists yet
TsmNewCo.Enabled = false;
}
}
// initialize the attribute tags to null
string CoFileTag = null;
string FilePathTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
CoFileTag = childTag.Value;
}
else if (count == 1)
{
FilePathTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (CoFileTag != null || FilePathTag != null)
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = true;
LblCompanyFileDef.Text = CoFileTag;
LblFilePathDef.Text = FilePathTag;
}
else
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Enabled = true;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Enabled = true;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "d") //tasks
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Enabled = true;
#region Enable/Disable "New" if database and company file are not saved yet
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.PrevNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
// inquire if database has child or db already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeDbSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
}
// inquire if company file has child or has file already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeCoSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
else
{
foreach (XElement enc in profNode)
{
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get company details for showing on the right panel of the main form specified below for task creation
foreach (var childTag in childrenTags)
{
if (count == 1)
{
qbFilePath = childTag.Value;
}
count++;
}
}
}
}
#endregion
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Enabled = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Enabled = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks summary
#region Extract data from Xml and show in the main form tabcontrol
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
if (Xml_Extract_Data_TaskSum(selNodeParentName, selNodeName) == true)
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = false;
}
#endregion
}
else // for the task credentials
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Enabled = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Enabled = true;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Enabled = true;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = true;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks details
#region Extract data from Xml and show in the main form tabcontrol
selNodeGrandParentName = TvwPanel.SelectedNode.Parent.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.Text;
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profileTask =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeGrandParentName
select ep;
foreach (XElement ep in profileTask)
{
IEnumerable<XElement> profNodeTask =
from en in ep.Elements("node")
where (string)en.Attribute("text") == selNodeParentName
select en;
foreach (XElement ept in profNodeTask)
{
IEnumerable<XElement> profNodeTaskCred =
from en in ept.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement eptc in profNodeTaskCred)
{
// initialize the attribute tags to null
string ActionTag = null;
string TablesTag = null;
string FiltersTag = null;
string ScheduleTag = null;
// get the attribute tags
var childrenTags = eptc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
ActionTag = childTag.Value;
}
else if (count == 1)
{
TablesTag = childTag.Value;
}
else if (count == 2)
{
FiltersTag = childTag.Value;
}
else if (count == 3)
{
ScheduleTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (ActionTag != null || FiltersTag != null || ScheduleTag != null)
{
LblActionDef.Text = ActionTag;
// TablesTag
string[] TablesTagArray = TablesTag.Split(','); //(new char[] { ',', ' ' });
LvwTables.Items.Clear();
foreach (string tt in TablesTagArray)
{
string table = tt.TrimStart();
ListViewItem lvi = new ListViewItem(table);
LvwTables.Items.Add(lvi);
}
// FiltersTag
// filter period
string filterPeriod;
int Pos1 = FiltersTag.IndexOf("Transactions: ") + "Transactions: ".Length;
int Pos2 = FiltersTag.IndexOf(" | Migration");
filterPeriod = FiltersTag.Substring(Pos1, Pos2 - Pos1);
LblFtrPeriodDef.Text = filterPeriod;
// migration type
string migrationType;
int Pos3 = FiltersTag.IndexOf("Type: ") + "Type: ".Length;
int Pos4 = FiltersTag.IndexOf(" | No");
migrationType = FiltersTag.Substring(Pos3, Pos4 - Pos3);
LblFtrMigTypeDef.Text = migrationType;
// no of record per query
string numberRecords;
int Pos5 = FiltersTag.IndexOf("Query: ") + "Query: ".Length;
numberRecords = FiltersTag.Substring(Pos5);
LblFtrRpqDef.Text = numberRecords;
// filter head
if (filterPeriod == "All" && migrationType == "Overwrite" && numberRecords == "0")
{
LblFiltersDef.Text = "Default";
}
else
{
LblFiltersDef.Text = "Custom";
}
LblSchedDef.Text = ScheduleTag;
TbcMain.SelectedIndex = 3;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 3;
TbcMain.Visible = false;
}
}
}
}
// capture the db credentials for task running
Capture_DB_Credentials_for_NodeMouseClick_And_Task_Saving(selNodeGrandParentName, selNodeDbSiblingName, selNodeCoSiblingName);
#endregion
}
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
}
In the Node_Selection_Action method, the last if statement block:
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
is the only block of code that needs the TreeNodeMouseClickEventArgs properties. If you really need to pass this type of argument to the method then create one:
// Still no idea what is the relation, however...
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
var s = sender as TreeView;
var p = s.PointToClient(Cursor.Position);
var ht = s.HitTest(p);
if (ht.Node != null)
{
var args = new TreeNodeMouseClickEventArgs(ht.Node, MouseButtons, 1, p.X, p.Y);
Node_Selection_Action(s, args);
}
}
Unless I'm missing an access to the sender param in your code, you can omit it to simplify the method signature:
private void Node_Selection_Action(TreeNodeMouseClickEventArgs e) { }
Also, you can determine which mouse button is pressed anywhere in your code through the Control.MouseButtons property. The Control.MousePosition property gets the cursor's position in screen coordinates. So, maybe these two properties are all what you need.
Maybe the mentioned above last if block is in the wrong method and moving it into a new method or elsewhere in the context could be better.
Hope that helps.
I want to create filrer for 4 fields. But I get too many code.
I need filter when just one field choosen or a few (2,3 or 4) fields at the same time. How to create logic for it?
My ugly code:
void ViewSource_Filter(object sender, FilterEventArgs e)
{
if (e.Item is Event evnt)
{
bool selectedModel = filterEventsControl.ComboBoxModels.SelectedIndex != 0 && filterEventsControl.ComboBoxModels.SelectedItem != null;
bool selectedIp = filterEventsControl.ComboBoxIPs.SelectedIndex != 0 && filterEventsControl.ComboBoxIPs.SelectedItem != null;
bool selectedParameter = filterEventsControl.ComboBoxParameters.SelectedIndex != 0 && filterEventsControl.ComboBoxParameters.SelectedItem != null;
bool selectedStatus = filterEventsControl.ComboBoxStatus.SelectedIndex != 0 && filterEventsControl.ComboBoxStatus.SelectedItem != null;
if (selectedModel && !selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
if (evnt.DeviceName == model)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
else if (selectedModel && selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
var ip = filterEventsControl.ComboBoxIPs.SelectedItem.ToString();
if (evnt.DeviceName == model && evnt.Ip == ip)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
...
else
{
e.Accepted = true;
}
}
}
It can be something like this:
bool FilterByName(Event evnt)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem?.ToString();
return evnt.DeviceName == model;
}
bool FilterByIp(Event evnt)
{
var ip = filterEventsControl.ComboBoxIPs.SelectedItem?.ToString();
return evnt.Ip == ip;
}
void ViewSource_Filter(object sender, FilterEventArgs e)
{
...
bool res = true;
if (selectedModel)
res = res && FilterByName();
if (selectedIp)
res = res && FilterByIp();
...
}
how can i do so if my username are Anton, then show, if not then dont show.
I already tried the following thing.
if(Session["username"] == "Anton")
{
btnNew.Visible = true;
}
else
{
btnNew.Visible = false;
}
if(!string.IsNullOrEmpty((string)Session["username"]) && (string)Session["username"] == "Anton")
{
btnNew.Visible = true;
}
else
{
btnNew.Visible = false;
}
So I have this code. What it does is to show the selected usercontrol when user tap a button. If that particular usercontrol is already visible, tapping its button will hide it.
The code is rather repetitive, any suggestion how can I make it more succinct?
private void changeControl(TextControl control)
{
switch (control)
{
case TextControl.TextBox:
if (IsRadTextBoxVisible == true)
{
IsRadTextBoxVisible = false;
}
else
{
IsRadTextBoxVisible = true;
}
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Font:
if (IsCountriesListBoxVisible == true)
{
IsCountriesListBoxVisible = false;
}
else
{
IsCountriesListBoxVisible = true;
}
IsRadTextBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Size:
if (IsSliderFontSizeVisible == true)
{
IsSliderFontSizeVisible = false;
}
else
{
IsSliderFontSizeVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Rotate:
if (IsSliderFontRotateVisible == true)
{
IsSliderFontRotateVisible = false;
}
else
{
IsSliderFontRotateVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
break;
default:
break;
}
}
var stateRad= IsRadTextBoxVisible;
var stateSlider = IsSliderFontRotateVisible;
var ........
var ........
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
IsRadTextBoxVisible = false
switch (control)
{
case TextControl.TextBox:
IsRadTextBoxVisible = !stateRad
break;
case TextControl.Font:
IsCountriesListBoxVisible = !statexxx
break;
case TextControl.Size:
IsSliderFontSizeVisible = !statexxx
break;
case TextControl.Rotate:
IsSliderFontRotateVisible = !statexxx
break;
default:
break;
}
private void changeControl(TextControl control)
{
IsRadTextBoxVisible = control == TextControl.TextBox ? !IsRadTextBoxVisible : false;
IsCountriesListBoxVisible = control == TextControl.Font ? !IsCountriesListBoxVisible : false;
IsSliderFontSizeVisible = control == TextControl.Size ? !IsSliderFontSizeVisible : false;
IsSliderFontRotateVisible = control == TextControl.Rotate ? !IsSliderFontRotateVisible : false;
}
What it does:
control == TextControl.TextBox
returns either true or false.
Now, ternary operator ?: executes code after ? if expression before ? returned true,
or code after : if expression before ? returned false
In this case, if control matches, we're executing code after ?, which in this case toggles the property.
If we control doesn't match, we're executing code after :, which sets the property to false.
I such cases i would not use switch-case, becuase you can't make complex boolean-operations. Maybe you can make your code more efficent with some if-else statements. Switch-Cases are some times very limited and would not use them.
I am trying to find out that in ad, user has allowed to change password or not.
I have used SearchResponse to find out that user exists or not.
SearchResponse response = (SearchResponse)connection.SendRequest(request);
DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];
if (attribute != null)
{
const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
bool fEveryone = false;
bool fSelf = false;
ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
foreach (ActiveDs.IADsAccessControlEntry ace in acl)
{
if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
{
if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fEveryone = true;
}
if ((ace.Trustee == #"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fSelf = true;
}
break;
}
}
if (fEveryone || fSelf)
{
return Global.RequestContants.CANT_CHANGE_PASSWORD;
}
else
{
return string.Empty;
}
}