Find out User cannot change password value of ldap - c#

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;
}
}

Related

How to create complex filter for DataGrid WPF

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();
...
}

Word Interop - How to determine if a word doc has page number in Header/footer

I want to know if a Word Document has page number in the Header/Footer using Interop.Word in C#.
I have gone this far
try
{
foreach (Section SectionObj in DocObj.Sections)
{
foreach (HeaderFooter HeaderObj in SectionObj.Footers)
{
if (HeaderObj.Exists && (HeaderObj.Shapes.Count > 0 || !(string.IsNullOrEmpty(HeaderObj.Range.Text) || HeaderObj.Range.Text.Equals("\r"))))
{
if(HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInDash
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleUppercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleNumberInCircle
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseRoman
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleLowercaseLetter
|| HeaderObj.PageNumbers.NumberStyle == WdPageNumberStyle.wdPageNumberStyleHindiLetter1)
{
PageNumber = true;
}
}
}
}
}
catch (Exception e) { }
But the checks cannot determine if it is Page number or not. What should I do to determine if it has page numbers?
You should check the Header and the Footer of Section using the PageNumbers.Count propertie.
private bool HeaderOrFooterHasPageNumber(Word.HeaderFooter headOrFooter)
{
if (headOrFooter != null)
return headOrFooter.PageNumbers.Count > 0;
else
return false;
}
And you can call this like...
bool hasNumberPages = false;
Word.Document doc = WordApp.ActiveDocument;
try
{
Word.HeaderFooter headOrFooter = null;
Word.Section section = null;
for (int i = 1; i <= doc.Sections.Count; i++)
{
try
{
section = doc.Sections[i];
if(section != null)
{
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
headOrFooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
hasNumberPages = HeaderOrFooterHasPageNumber(headOrFooter);
if (hasNumberPages)
break;
}
}
finally
{
if(headOrFooter != null)
{
Marshal.ReleaseComObject(headOrFooter);
headOrFooter = null;
}
if (section != null)
Marshal.ReleaseComObject(section);
}
}
}
finally
{
if (doc != null)
Marshal.ReleaseComObject(doc);
}

How to get selected value or index of a dropdownlist upon entering a page?

I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init

Hide/Show radio buttons on a questionnaire application

I am doing an assignment involving the creation of a simple Quiz type form application. However, whenever I run the program, only the first answer shows for a multiple question and I cannot for the life of me figure out why.
This is the contstructor:
MultipleChoice dlg =
new MultipleChoice(
new Question("What is the capital of Zimbabwe?",
new Answer("Paris", false),
new Answer("Washington D.C.", false),
new Answer("Harare", true),
new Answer("Cairo", false),
new Answer("N'Djamena", false)));
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.Correct) MessageBox.Show("You got something right!");
else MessageBox.Show("You couldn't be more wrong");
}
And this is the Question Form Code:
private Question Q;
public MultipleChoice (Question q)
{
Q = q;
InitializeComponent();
textPrompt.Text = Q.Prompt;
if (Q.A != null)
{
radioA.Text = Q.A.Prompt;
}
else radioA.Hide();
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide();
if (Q.C != null)
{
radioC.Text = Q.C.Prompt;
}
radioC.Hide();
if (Q.D != null)
{
radioD.Text = Q.D.Prompt;
}
radioD.Hide();
if (Q.E != null)
{
radioE.Text = Q.E.Prompt;
}
radioE.Hide();
}
public bool Correct
{
get
{
if (Q == null) return false;
if (Q.A != null && Q.A.Correct && radioA.Checked) return true;
if (Q.B != null && Q.B.Correct && radioB.Checked) return true;
if (Q.C != null && Q.C.Correct && radioC.Checked) return true;
if (Q.D != null && Q.D.Correct && radioD.Checked) return true;
if (Q.E != null && Q.E.Correct && radioE.Checked) return true;
return false;
}
}
Where have I gone wrong?
There is no else for any option after A:
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide(); //This is **always** going to be called - hiding radioB :)
Should be:
if (Q.B != null)
radioB.Text = Q.B.Prompt;
else
radioB.Hide();

Data list binding with some text and validating datalist

I am using this code for datalist validation.
I am binding the image in datalist after that i am trying to give the caption to each image suppose there is 3 image is datalist then for the first image i am able to give but for the other one i am unable to.. i think there is some error in conditions help me in this. code is following..
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "")
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "" || htble[id] == null) // New code implemented here
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}
Now its working fine...

Categories