How to upload Multiple file in Kentico Custom BizForm? - asp.net

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.

Related

Xamarin Forms Custom Map Pin

In one of the apps I'm working on I require the use of custom map pins and I've followed the guide on Xamarin https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/customized-pin/ as well as borrowed their sample code to try and make my own example.
It works to a degree in such that the info window is actually updated to the custom layout but the map pin never changes.
My CustomMapRenderer:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
using WorkingWithMaps.Droid.Renderers;
using WorkingWithMaps;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace WorkingWithMaps.Droid.Renderers
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback
{
GoogleMap map;
List<CustomPin> customPins;
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
((MapView)Control).GetMapAsync(this);
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
map = googleMap;
map.SetInfoWindowAdapter(this);
map.InfoWindowClick += OnInfoWindowClick;
this.NativeMap = googleMap;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
map.Clear();
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
map.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}
}
and my map page, also heavily borrowed from Xamarin's working with maps guide
using Plugin.Geolocator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace WorkingWithMaps
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
CustomMap map;
Geocoder geoCoder;
String navAdd;
public MainPage()
{
InitializeComponent();
var maplocator = CrossGeolocator.Current;
maplocator.DesiredAccuracy = 1;
geoCoder = new Geocoder();
map = new CustomMap
{
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand,
IsShowingUser = true
};
map.MapType = MapType.Street;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(55.237208, 10.479160), Distance.FromMeters(500)));
map.IsShowingUser = true;
var street = new Button { Text = "Street" };
var hybrid = new Button { Text = "Hybrid" };
var satellite = new Button { Text = "Satellite" };
street.Clicked += HandleClickedAsync;
hybrid.Clicked += HandleClickedAsync;
//satellite.Clicked += OnReverseGeocodeButtonClicked;
var segments = new StackLayout
{
Spacing = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Orientation = StackOrientation.Horizontal,
Children = { street, hybrid, satellite }
};
Content = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
Children = { map, segments }
};
Device.BeginInvokeOnMainThread(async () =>
{
try
{
//var currentpos = await maplocator.GetPositionAsync(1000);
//map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(currentpos.Latitude, currentpos.Longitude), Distance.FromMeters(500)));
if (!maplocator.IsListening)
{
await maplocator.StartListeningAsync(1000, 50, true);
}
}
catch (Exception ex)
{
Debug.WriteLine("Fail" + ex);
}
});
var pin = new CustomPin
{
Pin = new Pin
{
Type = PinType.Place,
Position = new Position(55.240121, 10.469895),
Label = "Testing Pins"
}
};
map.CustomPins = new List<CustomPin> { pin };
map.Pins.Add(pin.Pin);
map.PropertyChanged += (sender, e) =>
{
Debug.WriteLine(e.PropertyName + " just changed!");
if (e.PropertyName == "VisibleRegion" && map.VisibleRegion != null)
CalculateBoundingCoordinates(map.VisibleRegion);
};
maplocator.PositionChanged += (sender, e) =>
{
var position = e.Position;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromKilometers(2)));
};
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//async void OnReverseGeocodeButtonClicked(object sender, EventArgs e)
//{
// var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(pin.Position);
// navAdd += possibleAddresses.ElementAt(0) + "\n";
// switch (Device.OS)
// {
// case TargetPlatform.iOS:
// Device.OpenUri(new Uri(string.Format("http://maps.apple.com/?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Android:
// Device.OpenUri(new Uri(string.Format("geo:0,0?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Windows:
// case TargetPlatform.WinPhone:
// Device.OpenUri(new Uri(string.Format("bingmaps:?where={0}", Uri.EscapeDataString(navAdd))));
// break;
// }
//}
void HandleClickedAsync(object sender, EventArgs e)
{
var b = sender as Button;
switch (b.Text)
{
case "Street":
map.MapType = MapType.Street;
break;
case "Hybrid":
map.MapType = MapType.Hybrid;
break;
case "Satellite":
map.MapType = MapType.Satellite;
break;
}
}
static void CalculateBoundingCoordinates(MapSpan region)
{
var center = region.Center;
var halfheightDegrees = region.LatitudeDegrees / 2;
var halfwidthDegrees = region.LongitudeDegrees / 2;
var left = center.Longitude - halfwidthDegrees;
var right = center.Longitude + halfwidthDegrees;
var top = center.Latitude + halfheightDegrees;
var bottom = center.Latitude - halfheightDegrees;
if (left < -180) left = 180 + (180 + left);
if (right > 180) right = (right - 180) - 180;
Debug.WriteLine("Bounding box:");
Debug.WriteLine(" " + top);
Debug.WriteLine(" " + left + " " + right);
Debug.WriteLine(" " + bottom);
}
}
}
On top of the mentioned issue the implementation has also caused IsShowingUser = True to no longer function as well as
var currentpos = await maplocator.GetPositionAsync(1000);
to throw an exception.
Github repository: https://github.com/Mortp/CustomMapPinsXamarin
First of all I would like to provide 2 links that helped me to understand the problem. Thank you guys.
Xamarin.Forms.Maps 2.3.4 custom MapRenderer disables everything and https://forums.xamarin.com/discussion/92565/android-ionmapreadycallback-forms-2-3-4
Latest Xamarin Maps broke OnElementPropertyChanged with VisibleRegion. They defined that MapRenderer now implements IOnMapReadyCallback and that broke somehow OnElementPropertyChanged (I didn't investigate how and why). As you can see in link I provided there are 2 methods you can go. To keep your renderer implementing IOnMapReadyCallback or not. When I kept IOnMapReadyCallback I started to get 2 pins - one of top another - our custom pin and regular pin. I didn't dig more how that happens and removed IOnMapReadyCallback. After that things became really simple because if you let Xamarin handle it and create NativeMap you can remove some code and make renderer simpler.
Before I post the code I also want to mention that when I fixed it the app started crashing with OutOfMemory exception and I found out that your pin image is 2000 pixels width. I changed it to 40. Below is the code:
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter//, IOnMapReadyCallback
{
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
}
bool isMapReady;
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (!isMapReady && (NativeMap != null))
{
NativeMap.SetInfoWindowAdapter(this);
NativeMap.InfoWindowClick += OnInfoWindowClick;
isMapReady = true;
}
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
NativeMap.Clear();
foreach (var pin in ((CustomMap)Element).CustomPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
NativeMap.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in ((CustomMap)Element).CustomPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}

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

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

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

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

Validation controls not applicable to web custom controls in asp.net

I have created a web custom control and used within an aspx page. I found the validation controls provided by asp.net are applicable to the built in server controls. I am not able to attach these validation controls with my custom control.
For ex. If i am using TextBox control then the RequiredFieldValidator is applicable to it. but when i try to apply the same RequiredFieldValidator to my custom control it is not possible. The property "ControlToValidate" does not show the object id of my custom control.
Could someone help me to rectify this problem?
Thanks for sharing your valuable time.
Below is the code from .cs file -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
[assembly: TagPrefix("DatePicker", "SQ")]
namespace DatePicker
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
public class DatePicker : CompositeControl
{
//To retrieve value i am using textbox
private TextBox _TxtDate = new TextBox();
// Image to select the calender date
private Image _ImgDate = new Image();
// Image URL to expose the image URL Property
private string _ImageUrl;
// Exposing autopostback property
private bool _AutoPostBack;
// property get the value from datepicker.
private string _Value;
//CSS class to design the Image
private string _ImageCssClass;
//CSS class to design the TextBox
private string _TextBoxCssClass;
//to formate the date
private string _DateFormat = "%m/%d/%Y";
//to hold javascript on client side
static Literal _litJScript=new Literal();
private bool _includeJS = false;
/**** properties***/
#region "[ Properties ]"
[Bindable(true), Category("Appearance"), DefaultValue("")]
public string ImageUrl
{
set
{
this._ImageUrl = value;
}
}
[Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
public string Text
{
get
{
//String s = (String)ViewState["Text"];
//return ((s == null) ? string.Empty : s);
return _Value = _TxtDate.Text;
}
set
{
ViewState["Text"] = value;
_TxtDate.Text = value;
_TxtDate.BackColor = System.Drawing.Color.White;
}
}
[Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
public string Value
{
get
{
return _Value= _TxtDate.Text;
}
set
{
_Value = _TxtDate.Text = value;
ViewState["Text"] = _Value;
_TxtDate.BackColor = System.Drawing.Color.White;
}
}
[Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
public bool AutoPostBack
{
get
{
return _AutoPostBack;
}
set
{
_AutoPostBack = value;
}
}
[Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
public string ImageCssClass
{
get
{
return _ImageCssClass;
}
set
{
_ImageCssClass = value;
}
}
[Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
public string TextBoxCssClass
{
get
{
return _TextBoxCssClass;
}
set
{
_TextBoxCssClass = value;
}
}
[Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
public string CommandName
{
get
{
string s = ViewState["CommandName"] as string;
return s == null ? String.Empty : s;
}
set
{
ViewState["CommandName"] = value;
}
}
[Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
public string CommandArgument
{
get
{
string s = ViewState["CommandArgument"] as string;
return s == null ? String.Empty : s;
}
set
{
ViewState["CommandArgument"] = value;
}
}
[Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
public string DateFormat
{
get
{
return _DateFormat;
}
set
{
_DateFormat = value;
}
}
[Bindable(true), Category("Behavior"), DefaultValue("True")]
public bool IncludeClientSideJS
{
get { return _includeJS; }
set {
_includeJS = value;
}
}
[Bindable(true), Category("Behavior"), DefaultValue("True")]
public override bool Enabled
{
get { return _TxtDate.Enabled; }
set
{
_TxtDate.Enabled = value;
_ImgDate.Visible = value;
}
}
[Bindable(true), Category("Layout")]
public override Unit Width
{
get
{
return base.Width;
}
set
{
base.Width = value;
_TxtDate.Width = value;
}
}
#endregion
protected static readonly object EventCommandObj = new object();
public event CommandEventHandler Command
{
add
{
Events.AddHandler(EventCommandObj, value);
}
remove
{
Events.RemoveHandler(EventCommandObj, value);
}
}
//this will raise the bubble event
protected virtual void OnCommand(CommandEventArgs commandEventArgs)
{
CommandEventHandler eventHandler = (CommandEventHandler)Events[EventCommandObj];
if (eventHandler != null)
{
eventHandler(this, commandEventArgs);
}
base.RaiseBubbleEvent(this, commandEventArgs);
}
//this will be initialized to OnTextChanged event on the normal textbox
private void OnTextChanged(object sender, EventArgs e)
{
if (this.AutoPostBack)
{
//pass the event arguments to the OnCommand event to bubble up
CommandEventArgs args = new CommandEventArgs(this.CommandName, this.CommandArgument);
OnCommand(args);
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
AddStyleSheet();
AddJavaScript("DatePicker.Resources.prototype.js");
AddJavaScript("DatePicker.Resources.calendarview.js");
// For TextBox
// setting name for textbox. using t just to concat with this.ID for unqiueName
_TxtDate.ID = this.ID + "t";
// setting postback
_TxtDate.AutoPostBack = this.AutoPostBack;
// giving the textbox default value for date
_TxtDate.Text = this.Value;
//Initializing the TextChanged with our custom event to raise bubble event
_TxtDate.TextChanged += new System.EventHandler(this.OnTextChanged);
//Set max length
_TxtDate.MaxLength = 10;
//Setting textbox to readonly to make sure user dont play with the textbox
//_TxtDate.Attributes.Add("readonly", "readonly");
// adding stylesheet
_TxtDate.Attributes.Add("class", this.TextBoxCssClass);
_TxtDate.Attributes.Add("onkeypress", "maskDate(event)");
_TxtDate.Attributes.Add("onfocusout","isValidDate(event)");
// For Image
// setting alternative name for image
_ImgDate.AlternateText = "imageURL";
if (!string.IsNullOrEmpty(_ImageUrl))
_ImgDate.ImageUrl = _ImageUrl;
else
{
_ImgDate.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.CalendarIcon.gif");
}
//setting name for image
_ImgDate.ID = this.ID + "i";
//setting image class for textbox
_ImgDate.Attributes.Add("class", this.ImageCssClass);
//Initialize JS with literal
string s = "<script language=\"javascript\">function maskDate(e){var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
s = s + "var myT=document.getElementById(srcEle.id);var KeyID = evt.keyCode;";
s = s + "if((KeyID>=48 && KeyID<=57) || KeyID==8){if(KeyID==8)return;if(myT.value.length==2){";
s = s + "myT.value=myT.value+\"/\";}if(myT.value.length==5){myT.value=myT.value+\"/\";}}";
s = s + "else{window.event.keyCode=0;}}";
string s1 = "function isValidDate(e){var validDate=true;var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
s1 = s1 + "var myT=document.getElementById(srcEle.id);var mm=myT.value.substring(0,2);var dd=myT.value.substring(5,3);var yy=myT.value.substring(6);";
s1 = s1 + "var originalCss =myT.className; if(mm!=0 && mm>12){myT.value=\"\"; validDate=false;}else{if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0){if(mm==2 && dd>29){";
s1 = s1 + "myT.value=\"\"; validDate=false;}}else{if(mm==2 && dd>28){myT.value=\"\"; validDate=false;}else{if(dd!=0 && dd>31){";
s1 = s1 + "myT.value=\"\"; validDate=false;}else{if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){myT.value=\"\"; validDate=false;}}}}}";
s1 = s1 + "if(!validDate){myT.style.backgroundColor='#FD9593';myT.focus;}else { myT.style.backgroundColor='#FFFFFF';}}</script>";
_litJScript.Text = s+s1;
}
/// <summary>
/// adding child controls to composite control
/// </summary>
protected override void CreateChildControls()
{
this.Controls.Add(_TxtDate);
this.Controls.Add(_ImgDate);
if(_includeJS)
this.Controls.Add(_litJScript);
base.CreateChildControls();
}
public override void RenderControl(HtmlTextWriter writer)
{
//render textbox and image
_TxtDate.RenderControl(writer);
_ImgDate.RenderControl(writer);
if(_includeJS)
_litJScript.RenderControl(writer);
RenderContents(writer);
}
/// <summary>
/// Adding the javascript to render the content
/// </summary>
/// <param name="output"></param>
protected override void RenderContents(HtmlTextWriter output)
{
StringBuilder calnder = new StringBuilder();
//adding javascript first
if (Enabled)
{
calnder.AppendFormat(#"<script type='text/javascript'>
document.observe('dom:loaded', function() {{
Calendar.setup({{
dateField: '{0}',
triggerElement: '{1}',
dateFormat: '{2}'
}})
}});
", _TxtDate.ClientID, _ImgDate.ClientID, _DateFormat);
calnder.Append("</script>");
}
else
{
calnder.AppendFormat(#"<script type='text/javascript'>
document.observe('dom:loaded', function() {{
Calendar.setup({{
dateField: '{0}',
triggerElement: '{1}',
dateFormat: '{2}'
}})
}});
", _TxtDate.ClientID, null, _DateFormat);
calnder.Append("</script>");
}
output.Write(calnder.ToString());
}
private void AddStyleSheet()
{
string includeTemplate = "<link rel='stylesheet' text='text/css' href='{0}' />";
string includeLocation =
Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.calendarview.css");
LiteralControl include = new LiteralControl(String.Format(includeTemplate, includeLocation));
Page.Header.Controls.Add(include);
}
private void AddJavaScript(string javaScriptFile)
{
string scriptLocation = Page.ClientScript.GetWebResourceUrl(this.GetType(),javaScriptFile );
Page.ClientScript.RegisterClientScriptInclude(javaScriptFile, scriptLocation);
}
}
}
You should either use a CustomValidator, or insert the RequiredFieldValidator directly into your custom control. Of course the built-in validators don't work with your control... they have no idea what to do with it! But if your control internally uses a TextBox, then you can also have a RequiredFieldValidator there.
A third possibility is to expose your internal TextBox with a property, which you can then reference with ControlToValidate. However, the first two methods are preferable.
I'm having the same problem and I solved it by adding the attribute [ValidationPropertyAttribute("Text")] to my custom webcontrol class.
The specified value must correspond to the property to validate (see https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.validationpropertyattribute?view=netframework-4.7.2 for more informations).

Resources