ASP.NET: How to persist Page State accross Pages? - asp.net

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?

If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.

use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Related

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

How to upload Multiple file in Kentico Custom BizForm?

I have one Form which created as ascx control.Data was saving in biz form successfully. my problem is how to upload file? i dont know which control i'm using right or not for upload file? and how to add file upload submit here rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID); you can see below click button code.i have both code ascx and .cs in below. my ascx upload control which i'm using is right or not ? design code is below. code .cs is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Base;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.FormControls;
using CMS.FormEngine;
using CMS.Helpers;
using CMS.Localization;
using CMS.MacroEngine;
using CMS.Membership;
using CMS.PortalControls;
using CMS.PortalEngine;
using CMS.Protection;
using CMS.SiteProvider;
using CMS.WebAnalytics;
using System.Data;
using CMS.GlobalHelper;
using CMS.TreeEngine;
using CMS.CMSHelper;
using CMS.SiteProvider;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.DataEngine;
using CMS.WebAnalytics;
using CMS.LicenseProvider;
using CMS.PortalEngine;
using CMS.SettingsProvider;
using CMS.IDataConnectionLibrary;
using CMS.OnlineForms;
using CMS.DataEngine;
using CMS.SiteProvider;
using CMS.Helpers;
using CMS.FormEngine;
using CMS.SettingsProvider;
using CMS.DataEngine;
using CMS.GlobalHelper;
using CMS.ExtendedControls;
using CMS.Helpers;
using CMS.UIControls;
using System.Text;
using System.Web.UI.WebControls;
public partial class CMSWebParts_ePortalWebPart_ePortalControl_GraduateProgramApplication : CMSAbstractWebPart
{
//public static int SaveSignupForm(SignupFormModel model)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetGender();
GetUniversity();
GetStudyArea();
GetSpecializationEng();
}
}
#region "Layout properties"
public override string SkinID
{
get
{
return base.SkinID;
}
set
{
base.SkinID = value;
SetSkinID(value);
}
}
public string NameText
{
get
{
return DataHelper.GetNotEmpty(GetValue("NameText"), ResHelper.LocalizeString("{$GPAName$}"));
}
set
{
SetValue("NameText", value);
lblName.Text = value;
}
}
#endregion
public string DOBText
{
get
{
return DataHelper.GetNotEmpty(GetValue("DOBText"), ResHelper.LocalizeString("{$GPADateOfBirth$}"));
}
set
{
this.SetValue("LastNameText", value);
lblDOB.Text = value;
}
}
public string EmailText
{
get
{
return DataHelper.GetNotEmpty(this.GetValue("EmailText"), ResHelper.LocalizeString("{$Webparts_Membership_RegistrationForm.Email$}"));
}
set
{
this.SetValue("EmailText", value);
lblEmail.Text = value;
}
}
public string Submit
{
get
{
return DataHelper.GetNotEmpty(GetValue("Submit"), ResHelper.LocalizeString("{$custom.custom.Submit$}"));
}
set
{
this.SetValue("Submit", value);
btnOk.Text = value;
}
}
public string Gender
{
get
{
return DataHelper.GetNotEmpty(GetValue("Gender"), ResHelper.LocalizeString("{$GPAGender$}"));
}
set
{
this.SetValue("Gender", value);
lblGender.Text = value;
}
}
public string Email
{
get
{
return DataHelper.GetNotEmpty(GetValue("Email"), ResHelper.LocalizeString("{$GPAEmail$}"));
}
set
{
this.SetValue("Email", value);
lblEmail.Text = value;
}
}
public string GSMNumber
{
get
{
return DataHelper.GetNotEmpty(GetValue("GSMNumber"), ResHelper.LocalizeString("{$GPAGSMNumber$}"));
}
set
{
this.SetValue("GSMNumber", value);
lblGSMNumber.Text = value;
}
}
public string Grade
{
get
{
return DataHelper.GetNotEmpty(GetValue("Grade"), ResHelper.LocalizeString("{$GPAGrade$}"));
}
set
{
this.SetValue("Grade", value);
lblGrade.Text = value;
}
}
public string ExpectGraduateDate
{
get
{
return DataHelper.GetNotEmpty(GetValue("ExpectGraduateDate"), ResHelper.LocalizeString("{$GPAExpectGraduateDate$}"));
}
set
{
this.SetValue("ExpectGraduateDate", value);
lblExpectGraduateDate.Text = value;
}
}
public string University
{
get
{
return DataHelper.GetNotEmpty(GetValue("University"), ResHelper.LocalizeString("{$GPAUniversity$}"));
}
set
{
this.SetValue("University", value);
lblUniversity.Text = value;
}
}
public string StudyArea
{
get
{
return DataHelper.GetNotEmpty(GetValue("StudyArea"), ResHelper.LocalizeString("{$GPAStudyArea$}"));
}
set
{
this.SetValue("StudyArea", value);
lblStudyArea.Text = value;
}
}
public string Specialization
{
get
{
return DataHelper.GetNotEmpty(GetValue("Specialization"), ResHelper.LocalizeString("{$GPASpecialization$}"));
}
set
{
this.SetValue("Specialization", value);
lblSpecialization.Text = value;
}
}
public string WhyJoinPAEW
{
get
{
return DataHelper.GetNotEmpty(GetValue("WhyJoinPAEW"), ResHelper.LocalizeString("{$GPAWhyJoinPAEW$}"));
}
set
{
this.SetValue("WhyJoinPAEW", value);
lblWhyJoinPAEW.Text = value;
}
}
public string UploadCV
{
get
{
return DataHelper.GetNotEmpty(GetValue("UploadCV"), ResHelper.LocalizeString("{$GPAUploadCV$}"));
}
set
{
this.SetValue("UploadCV", value);
lblUploadCV.Text = value;
}
}
public string Certificates
{
get
{
return DataHelper.GetNotEmpty(GetValue("Certificates"), ResHelper.LocalizeString("{$GPACertificates$}"));
}
set
{
this.SetValue("Certificates", value);
lblCertificates.Text = value;
}
}
protected void SetupControl()
{
if (this.StopProcessing)
{
// Do not process
rfvName.Enabled = false;
rfvDOB.Enabled = false;
rfvEmail.Enabled = false;
revEmail.Enabled = false;
rfvGSMNumber.Enabled = false;
revMobile.Enabled = false;
rvGrade.Enabled = false;
rfvGrade.Enabled = false;
rvExpectGraduateDate.Enabled = false;
rfvExpectGraduateDate.Enabled = false;
rfvUniversity.Enabled = false;
rfvWhyJoinPAEW.Enabled = false;
// rfvUploadCV.Enabled = false;
// rfvCertificates.Enabled = false;
}
else
{
// Set texts
lblName.Text = this.NameText;
lblDOB.Text = this.DOBText;
btnOk.Text = this.Submit;
lblGender.Text = this.Gender;
lblEmail.Text = this.Email;
lblGSMNumber.Text = this.GSMNumber;
lblGrade.Text = this.Grade;
lblExpectGraduateDate.Text = this.ExpectGraduateDate;
lblUniversity.Text = this.University;
lblStudyArea.Text = this.StudyArea;
lblSpecialization.Text = this.Specialization;
lblWhyJoinPAEW.Text = this.WhyJoinPAEW;
lblUploadCV.Text = this.UploadCV;
lblCertificates.Text = this.Certificates;
//lddSpecialization.Items.Insert(0, new ListItem(ResHelper.GetString(ResHelper.LocalizeString("{$GPASpecialization$}"),CultureHelper.GetPreferredCulture())));
// BizForm1.OnAfterSave += new BizForm.OnAfterSaveEventHandler(GetGender());
// ObjectEvents.Insert.After += new EventHandler<ObjectEventArgs>(Insert_After);
// Set required field validators texts
rfvName.ErrorMessage = ResHelper.GetString("GPArfv");
rfvDOB.ErrorMessage = ResHelper.GetString("GPArfv");
rfvEmail.ErrorMessage = ResHelper.GetString("GPArfv");
revEmail.ErrorMessage = ResHelper.GetString("GPArfv");
rfvGSMNumber.ErrorMessage = ResHelper.GetString("GPArfv");
revMobile.ErrorMessage = ResHelper.GetString("GPArevMobile");
rvGrade.ErrorMessage = ResHelper.GetString("GPAGradeLess");
rfvGrade.ErrorMessage = ResHelper.GetString("GPArfv");
rvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArvExpectGraduateDate");
rfvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArfv");
rfvUniversity.ErrorMessage = ResHelper.GetString("GPArfv");
rfvWhyJoinPAEW.ErrorMessage = ResHelper.GetString("GPArfv");
// rfvUploadCV.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// rfvCertificates.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// Set SkinID
if (!this.StandAlone && (this.PageCycle < PageCycleEnum.Initialized))
{
SetSkinID(this.SkinID);
}
}
}
void SetSkinID(string skinId)
{
if (skinId != "")
{
lblName.SkinID = skinId;
lblDOB.SkinID = skinId;
}
}
public override void OnContentLoaded()
{
base.OnContentLoaded();
SetupControl();
}
/// <summary>
/// Reloads data
/// </summary>
public override void ReloadData()
{
base.ReloadData();
SetupControl();
}
/////////////////// Append Gender Radio List ///////////////////
private void GetGender()
{
Dictionary<string, string> Genderdic = new Dictionary<string, string>();
Genderdic.Add("1", "Male"); Genderdic.Add("2", "Female");
rvGender.DataSource = Genderdic;
rvGender.DataValueField = "Key";
rvGender.DataTextField = "Value";
rvGender.DataBind();
rvGender.SelectedValue = "1";
}
/////////////////// Append Gender Radio List ///////////////////
private void GetUniversity()
{
Dictionary<string, string> Universitydic = new Dictionary<string, string>();
Universitydic.Add("1", "Sultan Qaboos University"); Universitydic.Add("2", "Higher College of Technology"); Universitydic.Add("3", "Other");
ddlUniversity.DataSource = Universitydic;
ddlUniversity.DataValueField = "Key";
ddlUniversity.DataTextField = "Value";
ddlUniversity.DataBind();
}
private void GetStudyArea()
{
Dictionary<string, string> StudyAreadic = new Dictionary<string, string>();
StudyAreadic.Add("1", "Engineering"); StudyAreadic.Add("2", "Business");
rblStudyArea.DataSource = StudyAreadic;
rblStudyArea.DataValueField = "Key";
rblStudyArea.DataTextField = "Value";
rblStudyArea.DataBind();
rblStudyArea.SelectedValue = "1";
}
private void GetSpecializationEng()
{
Dictionary<string, string> Specializationdic = new Dictionary<string, string>();
if (rblStudyArea.SelectedValue == "1")
{
Specializationdic.Add("1", "Mechanical"); Specializationdic.Add("2", "Instrumentation"); Specializationdic.Add("3", "Civil"); Specializationdic.Add("4", "Chemistry"); Specializationdic.Add("5", "Water Resources"); Specializationdic.Add("6", "Other");
}
else
{
Specializationdic.Add("1", "Finance"); Specializationdic.Add("2", "HR"); Specializationdic.Add("3", "Communication"); Specializationdic.Add("4", "BA"); Specializationdic.Add("5", "Other");
}
lddSpecialization.DataSource = Specializationdic;
lddSpecialization.DataValueField = "Key";
lddSpecialization.DataTextField = "Value";
lddSpecialization.DataBind();
lddSpecialization.SelectedValue = "1";
}
protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlUniversity.SelectedValue == "3")
{ txtUniversity.Visible = true;}
else
{ txtUniversity.Visible = false;}
}
protected void rblStudyArea_SelectedIndexChanged(object sender, EventArgs e)
{
GetSpecializationEng();
}
protected void lddSpecialization_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblStudyArea.SelectedValue == "1")
{
if (lddSpecialization.SelectedValue == "6")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
else
{
if (lddSpecialization.SelectedValue == "5")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
{
// Do not process
}
else
{
rfvName.Validate();
rfvDOB.Validate();
rfvEmail.Validate();
revEmail.Validate();
rfvGSMNumber.Validate();
revMobile.Validate();
rvGrade.Validate();
rfvGrade.Validate();
rvExpectGraduateDate.Validate();
rfvExpectGraduateDate.Validate();
rfvUniversity.Validate();
rfvWhyJoinPAEW.Validate();
Page.Validate();
//if (Page.IsValid)
//{
String siteName = SiteContext.CurrentSiteName;
#region "Banned IPs"
// Ban IP addresses which are blocked for registration
if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
{
lblError.Visible = true;
lblError.Text = GetString("banip.ipisbannedregistration");
return;
}
#endregion
BizFormInfo formObject = BizFormInfoProvider.GetBizFormInfo("GraduateProgramApplication", SiteContext.CurrentSiteID);
if (formObject != null)
{
DataClassInfo formClass = DataClassInfoProvider.GetDataClassInfo(formObject.FormClassID);
if (formClass != null)
{
BizFormItemProvider bProvider = new BizFormItemProvider();
BizFormItem rec = BizFormItem.New(formClass.ClassName, null);
DateTime Applicant_DOB = DateTime.ParseExact(txtDOB.Text.Trim(), "dd/MM/yyyy", null);
DateTime Applicant_ExpectGraduateDate = DateTime.ParseExact(txtExpectGraduateDate.Text.Trim(), "MM/dd/yyyy", null);
rec.SetValue("FullName", txtName.Text.Trim());
rec.SetValue("DOB", Applicant_DOB);
rec.SetValue("Gender", rvGender.SelectedItem.Text.Trim());
rec.SetValue("Email", txtEmail.Text.Trim());
rec.SetValue("GSMNumber", txtGSMNumber.Text.Trim());
rec.SetValue("Grade", txtGrade.Text.Trim());
rec.SetValue("ExpectGraduateDate", Applicant_ExpectGraduateDate);
rec.SetValue("University", ddlUniversity.SelectedItem.Text.Trim());
rec.SetValue("StudyArea", rblStudyArea.SelectedItem.Text.Trim());
rec.SetValue("Specialization", lddSpecialization.SelectedItem.Text.Trim());
rec.SetValue("WhyPAEW", txtWhyJoinPAEW.Text.Trim());
// rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID);
// BasicForm.Data.GetValue("answerText"), "");
rec.SetValue("FormInserted", DateTime.Now);
rec.SetValue("FormUpdated", DateTime.Now);
rec.Insert();
BizFormInfoProvider.RefreshDataCount(formObject.FormName, formObject.FormSiteID);
}
}
string test = "Hello";
Response.Write("<script>alert('" + test + "');</script>");
}
}
}
I think you'll need to trigger the direct uploader to save the file somehow, before it will give you a GUID - I'm not completely familiar with how it works because I've never used it outside of the context of the Kentico form engine.
That being said, I think that the Forms module in Kentico would do everything that I can see you're trying to do here without you needing to write custom code.
Whenever I create a form in Kentico I try to leverage the forms module as much as possible.
I would recommend reading through the documentation for the forms module for whichever version of Kentico you're using to try create the form through the User Interface, and then asking questions if you get stuck on something through that process - unless there's something custom that I've misunderstood.

windows forms, async task exception catching

I have a form, 2 buttons , 1 textbox. Button 1 processes the TaskException_click.
What I wanted to do is understanding the async task/void difference. But checking multiple examples I still do not understand or get it to work. Below my code.
When I click the taskexception button, the unobservedtaskexception is not executed (I expected that).
When I click it another time, the event is executed with the exception of the first click. However the UI is not updated (actually it hangs). Would like to know what I am doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class main : Form
{
public main()
{
InitializeComponent();
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
//textBox1.Text = "Unobserved Exception caught ";
e.SetObserved();
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate()
{
//codes to do whatever i wan to do with the GUI
//Examples of it would be disposing a flowlayout panel
//and re-adding it back and populating it again to
//show the refreshed values.
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
});
}
else
{
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
private int i = 0;
// Add async here! You can always add these to events
private async void TaskException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
Task t = TaskThrowAnException();
textBox1.Text = "done";
t = null;
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch (Exception ex)
{
textBox1.Text = "Exception caught";
}
}
private async Task TaskThrowAnException()
{
//await Task.Delay(1000);
i++;
throw new Exception("Task" + i.ToString());
}
private async void VoidException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
VoidThrowAnException();
textBox1.Text = "done";
}
catch (Exception ex )
{
textBox1.Text = "Exception caught";
}
}
private async void VoidThrowAnException()
{
//await Task.Delay(1000);
throw new Exception("Void");
}
}
}
For the TaskException case the exception is stored in the Task this is the expected behavior for async methods returning Task. If you want the exception to be thrown you need to observe the exception by awaiting the Task or calling Result or Wait() on the Task.
If the exception is unobserved it should get thrown when the Task is finalized, the only thing I can conclude is that somehow the task is not being finalized when you call
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
I am nor sure why the local variable is not GCed, if add another button and you put the code above in the button handler (e.g Clear_Click) everything works as expected. I thought the generated code must somehow have a link to the task variable but I couldn't find any link.
Here is the generated code from Reflector:
namespace WindowsFormsApplication1
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public class Form1 : Form
{
private IContainer components = null;
private int i = 0;
private Button TaskException;
private TextBox textBox1;
private Button VoidException;
public Form1()
{
this.InitializeComponent();
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(this.TaskScheduler_UnobservedTaskException);
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.textBox1 = new TextBox();
this.TaskException = new Button();
this.VoidException = new Button();
base.SuspendLayout();
this.textBox1.Location = new Point(13, 13);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new Size(0x20d, 0x13f);
this.textBox1.TabIndex = 0;
this.TaskException.Location = new Point(13, 0x16d);
this.TaskException.Name = "TaskException";
this.TaskException.Size = new Size(0x9b, 0x17);
this.TaskException.TabIndex = 1;
this.TaskException.Text = "TaskException";
this.TaskException.UseVisualStyleBackColor = true;
this.TaskException.Click += new EventHandler(this.TaskException_Click);
this.VoidException.Location = new Point(0xda, 0x16d);
this.VoidException.Name = "VoidException";
this.VoidException.Size = new Size(0xab, 0x17);
this.VoidException.TabIndex = 2;
this.VoidException.Text = "VoidException";
this.VoidException.UseVisualStyleBackColor = true;
this.VoidException.Click += new EventHandler(this.VoidException_Click);
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.ClientSize = new Size(550, 430);
base.Controls.Add(this.VoidException);
base.Controls.Add(this.TaskException);
base.Controls.Add(this.textBox1);
base.Name = "Form1";
this.Text = "Form1";
base.ResumeLayout(false);
base.PerformLayout();
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<TaskException_Click>d__4))]
private void TaskException_Click(object sender, EventArgs e)
{
<TaskException_Click>d__4 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskException_Click>d__4>(ref d__);
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
MethodInvoker method = null;
e.SetObserved();
if (base.InvokeRequired)
{
if (method == null)
{
method = (MethodInvoker) (() => (this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message));
}
base.BeginInvoke(method);
}
else
{
this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
[AsyncStateMachine(typeof(<TaskThrowAnException>d__6)), DebuggerStepThrough]
private Task TaskThrowAnException()
{
<TaskThrowAnException>d__6 d__;
d__.<>4__this = this;
d__.<>t__builder = AsyncTaskMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskThrowAnException>d__6>(ref d__);
return d__.<>t__builder.Task;
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<VoidException_Click>d__8))]
private void VoidException_Click(object sender, EventArgs e)
{
<VoidException_Click>d__8 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<VoidException_Click>d__8>(ref d__);
}
[AsyncStateMachine(typeof(<VoidThrowAnException>d__a)), DebuggerStepThrough]
private void VoidThrowAnException()
{
<VoidThrowAnException>d__a _a;
_a.<>4__this = this;
_a.<>t__builder = AsyncVoidMethodBuilder.Create();
_a.<>1__state = -1;
_a.<>t__builder.Start<<VoidThrowAnException>d__a>(ref _a);
}
[CompilerGenerated]
private struct <TaskException_Click>d__4 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
Task task = this.<>4__this.TaskThrowAnException();
this.<>4__this.textBox1.Text = "done";
task = null;
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <TaskThrowAnException>d__6 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncTaskMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.i++;
throw new Exception("Task" + this.<>4__this.i.ToString());
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidException_Click>d__8 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
this.<>4__this.VoidThrowAnException();
this.<>4__this.textBox1.Text = "done";
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidThrowAnException>d__a : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
SynchronizationContext current = SynchronizationContext.Current;
throw new Exception("Void");
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
}
}

DateTimeControl Custom OnDateChange event not firing in SharePoint

The custom event for a DateTimeControl is not firing. Instead the CreateChildControls() is firing, every-time I change the date on Calendar.
namespace myn
{
class StopTimeFieldControl : BaseFieldControl
{
protected DateTimeControl dateTime;
public override object Value
{
get
{
EnsureChildControls();
if (dateTime == null)
{
return string.Empty;
}
return dateTime.SelectedDate;
}
set
{
EnsureChildControls();
dateTime.SelectedDate = Convert.ToDateTime(this.ItemFieldValue);
}
}
protected override string DefaultTemplateName
{
get
{
return "StopTimeFieldControl";
}
}
public override void Validate()
{
if (ControlMode == SPControlMode.Display || !IsValid)
{
//this.ViewState["StopTimeFieldControl"] = Value.ToString();
return;
}
base.Validate();
if (dateTime.IsDateEmpty)
{
this.ErrorMessage = " Du måste ange ett värde för det här obligatoriska fältet.";
IsValid = false;
return;
}
try
{
StartTimeFieldControl child = (StartTimeFieldControl)FindControlRecursive(this.Page, "startDateTime").Parent;
if (dateTime.SelectedDate < Convert.ToDateTime(child.Value))
{
this.ErrorMessage = " Du måste ange ett värde som är senare än startdatum.";
IsValid = false;
return;
}
}
catch (Exception e)
{
PortalLog.LogString("## Exception Occurred: Fail when trying to catch startDateTime ** {0} || {1}", e.Message, e.StackTrace);
}
this.Page.Session["startDateTime"] = Value;
}
protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)
return;
if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
{
dateTime = new DateTimeControl();
dateTime.CssClassTextBox = "ms-long";
dateTime.TimeZoneID = 1053;
dateTime.LocaleId = 1053;
dateTime.ID = "stopDateTime";
dateTime.AutoPostBack = true;
this.dateTime.DateChanged += new EventHandler(dateTime_DateChanged);
Controls.Add(dateTime);
}
//ChildControlsCreated = true;
}
void dateTime_DateChanged(object sender, EventArgs e)
{
string hi = "hej";
}
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
}
}
Try to create your DateTimeControl control in PreInit or Init phase and not in CreateChildControls. Possible reason of such behaviour - your control is created too late, when page life cycle passed through postback event handling.
CreateChildControls() is firing,
every-time I change the date on
Calendar
But is the event handler being bound every time?
In most cases i dont create controls in if statements, things tend to not get wired up correctly.
Try just making the control invisible instead.
dateTime = new DateTimeControl();
if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
{
datetime.Visible = false;

ASP custom controls don't fire correct events

I'm building a library of custom controls. My controls are inherited from CompositeControl.
Depending on the user's answer I have to insert more custom control. I have a PlaceHolder (_ph) passed in from the client code. I insert my controls into that PlaceHolder.
My problem is the control I inserted in the event handler does not fire its event, but it fires the parent event. For example, if I have an EddDropDown A, and the user picks an answer, I have to create EddDropDown B and C in edd_SelectedIndexChanged. When I pick an answer for B, it fires SelectedIndexChanged for A instead of B.
I think it has something to do with entering the page cycle late. I don't know how to fix it. Please help. Really appreciate any assistant.
Thanks in advance.
this is an example of my controls:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommerceBank.DueDiligence.ServiceProxies.Internal.Edd;
using System.Collections.Specialized;
using System.Runtime.Serialization;
namespace CommerceBank.DueDiligence.ClientFacade.WebForms
{
public class EddDropDownListArgs : EventArgs
{
private int _iQuestionID;
string _sAnswer = string.Empty;
private DueDiligenceProfile _customerProfile;
public EddDropDownListArgs(int iQuestionID, string sAnswer,DueDiligenceProfile customer)
{
_iQuestionID = iQuestionID;
_sAnswer = sAnswer;
_customerProfile = customer;
}
public int QuestionID
{
get
{
return _iQuestionID;
}
set
{
_iQuestionID = value;
}
}
public string Answer
{
get
{
return _sAnswer;
}
set
{
_sAnswer = value;
}
}
public DueDiligenceProfile customerProfile
{
get
{
return _customerProfile;
}
set
{
_customerProfile = value;
}
}
}
public delegate void EddDropDownSelectedIndexChangedHandler(object sender, EddDropDownListArgs ce);
[
AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
DefaultProperty("ID"),
ToolboxData("<{0}:EddDropDown runat=\"server\"> </{0}:EddDropDown>"),
Serializable
]
public class EddDropDown : CompositeControl, IChannelControl,ISerializable, IPostBackEventHandler, IPostBackDataHandler
{
[Serializable]
struct EddDropDownData
{
public int _iQuestionID;
public String _sQuestion;
//public AnswerOption[] _PossibleAnswers;
public String _sAnswer;
//public DueDiligenceProfile _customerProfile;
}
[
Bindable(true),
Category("Appearance"),
DefaultValue(""),
Description("This is EddCheckBox"),
Localizable(true)
]
private int _iQuestionID=-1;
private String _sQuestion = string.Empty;
private AnswerOption[] _PossibleAnswers;
private String _sAnswer = string.Empty;
private DueDiligenceProfile _customerProfile;
private EddDropDownData _data = new EddDropDownData();
Label _lQuestion = null;
DropDownList _ddl = null;
#region implement custom events
public event EddDropDownSelectedIndexChangedHandler SelectedIndexChanged;
protected virtual void OnSelectedIndexChanged(EddDropDownListArgs eddEvent)
{
if (SelectedIndexChanged != null)
{
System.Diagnostics.Trace.WriteLine("OnSelectedIndexChanged. QuestionID:"
+ eddEvent.QuestionID
+ " Answer: "
+ eddEvent.Answer);
SelectedIndexChanged(this, eddEvent);
}
}
#endregion
#region IPostBackEventHandler_implementation
// Define the method of IPostBackEventHandler that raises change events.
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
System.Diagnostics.Trace.WriteLine("in RaisePostBackEvent" + eventArgument);
OnSelectedIndexChanged(new EddDropDownListArgs(EDDQuestionID(), EDDAnswerValue(), _customerProfile));
}
#endregion
#region IPostBackDataHandler_implementation
bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
{
//System.Diagnostics.Trace.WriteLine("in LoadPostData");
//int i = int.Parse(postCollection["SelectedIndex"]);
//string s = postCollection["SelectedValue"];
//if (SelectedIndex >= 0)
// Page.RegisterRequiresRaiseEvent(this);
//return false;
return true;
}
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
System.Diagnostics.Trace.WriteLine("in RaisePostDataChangedEvent");
}
#endregion
#region ISerializable_implementation
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ControlType", GetType().Name);
info.AddValue("ControlID", ID);
info.AddValue("QuestionID", _iQuestionID);
info.AddValue("Question", Question);
info.AddValue("Answer", EDDAnswerValue());
info.AddValue("PossibleAnswerCount", _PossibleAnswers.Length);
for (int i=0; i < _PossibleAnswers.Length; i++)
{
info.AddValue("a" + i.ToString(), _PossibleAnswers[i]);
}
}
#endregion
#region IChannel_implementation
public int EDDQuestionID()
{
return QuestionID;
}
public string EDDAnswerValue()
{
EnsureChildControls();
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i].ID == "ans" + QuestionID)
{
_sAnswer = ((DropDownList)Controls[i]).SelectedValue;
_data._sAnswer = ((DropDownList)Controls[i]).SelectedValue;
ViewState["SelectedIndex"] = ((DropDownList)Controls[i]).SelectedIndex;
return ((DropDownList)Controls[i]).SelectedValue;
}
}
return null;
}
#endregion
#region Overriden properties
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
#endregion
#region Properties
public int QuestionID
{
get
{
_iQuestionID = (int)ViewState["QuestionID"];
return _iQuestionID;
}
set
{
ViewState["QuestionID"] = value;
_iQuestionID = value;
}
}
public string Question
{
get
{
_sQuestion = (string)ViewState["Question"];
return _sQuestion;
}
set
{
ViewState["Question"] = value;
_sQuestion = value;
}
}
public string Answer
{
get
{
return _sAnswer;
}
set
{
_sAnswer = value;
}
}
public int SelectedIndex
{
get {
EnsureChildControls();
if (ViewState["SelectedIndex"] != null)
_ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
else
_ddl.SelectedIndex = 0;
return _ddl.SelectedIndex;
}
set {
EnsureChildControls();
ViewState["SelectedIndex"] = value;
_ddl.SelectedIndex = value;
}
}
public string SelectedValue
{
get
{
EnsureChildControls();
_ddl.SelectedValue =(string)ViewState["SelectedValue"];
return _ddl.SelectedValue;
}
set
{
EnsureChildControls();
ViewState["SelectedValue"] = value;
_ddl.SelectedValue = value;
}
}
#endregion
public EddDropDown(int iQuestionID
, string sQuestion
, DueDiligenceProfile cust
, AnswerOption[] sPossibleAnswers
)
{
System.Diagnostics.Trace.WriteLine("Add EddDropDown. QuestionID :"
+ iQuestionID.ToString()
+ sQuestion);
QuestionID = iQuestionID;
Question = sQuestion;
_data._iQuestionID = iQuestionID;
_data._sQuestion = sQuestion;
_PossibleAnswers = sPossibleAnswers;
_customerProfile = cust;
ID = iQuestionID.ToString()+GetCustomerID();
}
public EddDropDown(SerializationInfo info, StreamingContext context)
{
string sControlType = info.GetString("ControlType");
ID = info.GetString("ControlID");
QuestionID = info.GetInt32("QuestionID");
Question = info.GetString("Question");
string sAnswer = info.GetString("Answer");
int iAnswerCount = info.GetInt32("PossibleAnswerCount");
List<AnswerOption> answerOptions = new List<AnswerOption>();
for (int i = 0; i < iAnswerCount; i++)
{
Type t = typeof(AnswerOption);
AnswerOption ao = (AnswerOption)info.GetValue("a" + i.ToString(), t);
answerOptions.Add(ao);
}
_PossibleAnswers = answerOptions.ToArray();
}
protected override object SaveViewState()
{
ViewState["SelectedIndex"] = _ddl.SelectedIndex;
return base.SaveViewState();
}
protected override void LoadViewState(object savedState)
{
//if (ViewState["SelectedIndex"] != null)
// _ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
//else
// _ddl.SelectedIndex = 0;
if (savedState != null)
{
Pair mystate = (Pair)savedState;
ArrayList al =(ArrayList)mystate.First;
for (int i = 0; i < al.Count;i++ )
{
if (al[i].GetType().Name == "IndexedString")
{
if (((IndexedString)al[i]).Value == "SelectedIndex")
{
ViewState["SelectedIndex"] = al[i + 1].ToString();
System.Diagnostics.Trace.WriteLine(al[i + 1].ToString());
}
}
}
}
base.LoadViewState(savedState);
}
//need this to get the post back
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ID);
writer.AddAttribute(HtmlTextWriterAttribute.Onchange,
Page.ClientScript.GetPostBackEventReference(this, ID));
//writer.AddAttribute(HtmlTextWriterAttribute.Onchange,
// Page.ClientScript.GetPostBackEventReference(_ddl, _ddl.ID));
base.AddAttributesToRender(writer);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
Page.RegisterRequiresPostBack(this);//must register postback in OnPreRender
}
protected override void Render(HtmlTextWriter writer)
{
//Ensures that this control is nested in a server form
if (Page != null)
{
Page.VerifyRenderingInServerForm(this);
}
base.Render(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
RenderChildren(writer);
}
protected override void CreateChildControls()
{
Controls.Clear();
_lQuestion = new Label();
_lQuestion.ID = "quest" + QuestionID;
_lQuestion.Text = Question;
_ddl = new DropDownList();
_ddl.ID = "ans" + QuestionID;
//add "select one"
ListItem liSelectOne = new ListItem("Please select one");
_ddl.Items.Add(liSelectOne);
for (int i = 0; i < _PossibleAnswers.Count(); i++)
{
AnswerOption a = _PossibleAnswers[i];
ListItem li = new ListItem(a.Value.ToString());
_ddl.Items.Add(li);
//if (a.ChildQuestions == null)//default it to the answer that don't have some children
// ddl.Items[i].Selected = true;
}
if (_sAnswer != string.Empty)
_ddl.SelectedValue = _sAnswer;
_ddl.AutoPostBack = true;//must have
_ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
if (ViewState["SelectedIndex"] != null)
_ddl.SelectedIndex = (int)ViewState["SelectedIndex"];
//else
// _ddl.SelectedIndex = 0;
Page.RegisterRequiresPostBack(_ddl);
Page.RegisterRequiresControlState(_ddl);
Controls.Add(new LiteralControl("<br>"));
Controls.Add(_lQuestion);
Controls.Add(new LiteralControl("<br>"));
Controls.Add(_ddl);
ChildControlsCreated = true;
//ClearChildViewState();
}
private string GetCustomerID()
{
if (_customerProfile.Customer.PermanentId >0)
return _customerProfile.Customer.PermanentId.ToString();
else if (_customerProfile.Customer.RcifId != null && _customerProfile.Customer.RcifId != "")
return _customerProfile.Customer.RcifId;
else
return _customerProfile.Customer.TaxId.ToString();
}
//to do: delete
//void edd_SelectedIndexChanged(object sender, EddDropDownListArgs ea)
//{
// System.Diagnostics.Trace.WriteLine("get here");
//}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Control c = (Control)sender;
System.Diagnostics.Trace.WriteLine("ddl_SelectedIndexChanged "
+ c.GetType().Name);
OnSelectedIndexChanged(new EddDropDownListArgs(EDDQuestionID(), EDDAnswerValue(),_customerProfile));
}
protected override void RenderChildren(HtmlTextWriter output)
{
if (HasControls())
{
for (int i = 0; i < Controls.Count; i++)
{
Controls[i].RenderControl(output);
}
}
}
}
}
This is the code that create the controls:
public EddDropDown GetDropDown(DueDiligenceProfile cust, Question quest)
{
Control c = null;
if (HasControl(quest.Id.ToString(), "EddDropDown", ref c))
return (EddDropDown)c;
string sQuestion = null;
AnswerOption[] sPossAnswers;
sPossAnswers = FindPossibleAnswers(cust.Questions, quest.Id, ref sQuestion);
if (sPossAnswers == null)
throw (new Exception("failed to get possible answers"));
EddDropDown edd = new EddDropDown(quest.Id,
sQuestion,
cust,
sPossAnswers
);
edd.ID = quest.Id.ToString();
edd.SelectedIndexChanged += new EddDropDownSelectedIndexChangedHandler(edd_SelectedIndexChanged);
_data._EDDControls.Add(edd);
int iParentQuestionID = FindParentQuestionID(cust.Questions, quest.Id, ref sQuestion);
int iControlIdx = GetIndexOf(iParentQuestionID, _ph.Controls);
if (iControlIdx >-1)
_ph.Controls.AddAt(iControlIdx + 1, edd);
else
_ph.Controls.Add(edd);
//build children questions if they have result
if (quest.Results.Length >0)
{
foreach (Result r in quest.Results)
{
edd.SelectedValue = r.Value;
foreach (AnswerOption ao in quest.AnswerOptions)
{
if (r.Value == ao.Value)
{
if (ao.ChildQuestions == null)
continue;
foreach (Question q in ao.ChildQuestions)
{
EddDropDown e = GetDropDown(cust, q);
e.BackColor = System.Drawing.Color.CadetBlue;
}
}
}
}
}
return edd;
}
void edd_SelectedIndexChanged(object sender, EddDropDownListArgs ea)
{
System.Diagnostics.Trace.WriteLine("EddQuestionare--edd_SelectedIndexChanged. QuestionID:"
+ ea.QuestionID
+ " Answer: "
+ ea.Answer);
//Control parentControl = null;
//if (sender.GetType().Name == "EddDropDown")
//{
// parentControl = (Control)sender;
//}
//Control c = (Control)sender;
//while (c.GetType().Name != "PlaceHolder")
// c = c.Parent;
string sQuestion = null;
AnswerOption[] ansOptions = FindPossibleAnswers(ea.customerProfile.Questions
, ea.QuestionID
, ref sQuestion);
foreach (AnswerOption ao in ansOptions)
{
if (ao.Value == ea.Answer)//found answer
{
if (ao.ChildQuestions == null)
break;
//create sub questions
for (int i = 0; i < ao.ChildQuestions.Length; i++)//and there are subquestions
{
_ph.Controls.Add(new LiteralControl(" "));
if (ao.ChildQuestions[i].AnswerOptions.Length > 2)
{
EddDropDown subQues = GetDropDown(ea.customerProfile
, ao.ChildQuestions[i]);
subQues.BackColor = System.Drawing.Color.Aqua;
}
else if (ao.ChildQuestions[i].AnswerOptions.Length == 2)
{
EddRadioButtonList erb = GetRadioButtonList(ea.customerProfile
, ao.ChildQuestions[i].Id);
erb.BackColor = System.Drawing.Color.BlueViolet;
}
else
{
EddTextArea eta = GetTextArea(ea.customerProfile
, ao.ChildQuestions[i].Id);
eta.BackColor = System.Drawing.Color.Bisque;
}
}
break;
}
}
//DisplayControls();
//Serialize();
}
There are a few things that I haven't cleaned out, but you get the idea.
The postback events might not be getting to your control.
In the page that is using your controls, try overriding the RaisePostbackEvent and call the RaisePostBackEvents for each control:
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
this.yourcustomcontrol1.RaisePostBackEvent(sourceControl, eventArgument);
this.yourcustomcontrol2.RaisePostBackEvent(sourceControl, eventArgument);
base.RaisePostBackEvent(sourceControl, eventArgument);
}

Resources