namespace DHS.AppBase{
#region Class Using Referencesusing System;using System.Collections.Generic;using System.Text;using System.Web.UI;using System.Web.UI.WebControls;using DHS.AppBase.ErrorLog;using DHS.ARTS.BLL;using System.Web;
#endregion Class Using References//---------------------------------------------------------------------------
/// Namespace: DHS.AppBase
/// Base Class: System.Web.UI.Page
/// Filename: BP_ARTS.cs
/// Author: Department of Human Services / de01t16 / de01t33
/// Date Created: 1/26/2010 7:28:43 AM
/// Updated By:
/// Date Updated:
/// Code Reviewed By:
/// Date Code Reviewed:
/// <summary>
/// Purpose: Parent Base Class for specific section page code-behinds.
/// Works in conjuction with ASP.NET pages as parent for code behind page
/// conrollers to contain common properties, methods, cascading
/// styles sheets or skins, and javascript and XML calls to
/// Business web services through the Domain bll. Not appropriate for oBout
/// Grid page base class.
/// </summary>
//---------------------------------------------------------------------------
public class BP_ARTS : System.Web.UI.Page
{
#region Private and Public Fields and Properties// This will allow Dirty Flag functionality by default.
// to disable dirty flag in your web page, set this property to false in
// your Page_Init event.
protected bool AllowDirtyFlag = true;protected bool AllowCheckinCode = true;// Holds list of controls that you want to bypass the dirty flag.
// Fill this list in your Page_Init event.
protected List<String> BypassDirtyControls { get; set; }private const string JQUERYURL = "~/scripts/jquery/1_4/jquery-1.4.2.min.js";private const string DIRTYFLAGJSCODEURL = "~/scripts/jquery/JQueryDirtyFlag.js";private const string CHECKINJSCODEURL = "~/scripts/jquery/CheckIn.js";private const string CHECKINSVCURL = "~/WebServices/CheckInRecordService.asmx/CheckInFromScreenClose";private const string CHECKINTABLESVCURL = "~/WebServices/CheckInRecordService.asmx/CheckInTableFromScreenClose";private const string CHECKINAPPEALANDRELATEDAPPEALSURL = "~/WebServices/CheckInRecordService.asmx/CheckInAppealAndRelatedAppealsFromScreenClose";private const string CHECKINAPPEALANDRELATEDAPPEALSBYDOCUMENTIDSURL = "~/WebServices/CheckInRecordService.asmx/CheckInAppealAndRelatedAppealsByDocumentID";private const string CSMSVCURL = "~/WebServices/CSM.asmx/DisplayCSMByID";private const string CSMLISTURL = "~/WebServices/CSM.asmx/GetCSMByIDList";private const string CSMJSCODEURL = "~/scripts/UI/CSM.js";private DHS.AppBase.ErrorLog.ARTSError logError = new DHS.AppBase.ErrorLog.ARTSError();ErrorLoggerBLL evLogger = new ErrorLoggerBLL();
#endregion Private and Public Fields and Properties
#region Class Constructorspublic BP_ARTS(){
this.Load += new EventHandler(Page_Load);}
#endregion Class Constructors
#region Page Lifecycle Events//---------------------------------------------------------------------------
/// <summary>
/// Method Name: Page_Load
/// Description: During load, if the current request is a postback, control
/// properties are loaded with information recovered from view state and control state.
/// Use the OnLoad event method to set properties in controls and establish database connections.
/// </summary>
///
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs</param>
//---------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e){
AddDefaultJavascript();
SetModalPageFlag();
if (AllowDirtyFlag){
AddDirtyFlag();
}
if (AllowCheckinCode){
AddCheckinCode();
}
}
#endregion Page Lifecycle Events
#region Instance Methods//---------------------------------------------------------------------------
/// <summary>
/// Method Name: SetModalPageFlag
/// Description: This method adds JavaScript variable to determine if the current page is
/// an ARTS Modal Screen.
/// </summary>
//---------------------------------------------------------------------------
private void SetModalPageFlag(){
var pageName = System.Web.HttpContext.Current.Request.Url.AbsolutePath.ToUpper();if (pageName.Contains("MODAL_")){
var sb = new StringBuilder();sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("var isModalPage = true;");sb.Append("</script>");if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "IsModal")){
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "IsModal", sb.ToString());}
}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: AddDefaultJavascript
/// Description: This method adds JavaScript code and includes to any page that derives
/// from this class. Also Adds a client postback variable to determine if
/// a postback has occurred.
/// </summary>
//---------------------------------------------------------------------------
private void AddDefaultJavascript(){
var sb = new StringBuilder();sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("function addListener(obj, evt, handler) {");sb.Append("if (obj.addEventListener) {");sb.Append("obj.addEventListener(evt, handler, false);");sb.Append("}else if (obj.attachEvent) {");sb.Append("obj.attachEvent('on' + evt, handler);}}");sb.Append("</script>");if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "AddListener")){
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "AddListener", sb.ToString());}
sb.Length = 0;
if (!IsPostBack){
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("var isPostBack = false;");sb.Append("</script>");}
else
{
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("var isPostBack = true;");sb.Append("</script>");}
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "ClientPostBack")){
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientPostBack", sb.ToString());}
sb.Length = 0;
// Check to see if the include script exists already.
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "jQueryLink")){
sb.Append(" <script src=\"");sb.Append(ResolveClientUrl(JQUERYURL));
sb.Append("\" type=\"text/javascript\"></script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "jQueryLink", sb.ToString());}
sb.Length = 0;
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "CSMJS")){
sb.Append(" <script src=\"");sb.Append(ResolveClientUrl(CSMJSCODEURL));
sb.Append("\" type=\"text/javascript\"></script>");sb.Append("<script>CSMByIDURL = \"");sb.Append(this.ResolveClientUrl(CSMSVCURL));sb.Append("\";");sb.Append("CSMListURL = \"");sb.Append(this.ResolveClientUrl(CSMLISTURL));sb.Append("\";");sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CSMJS", sb.ToString());}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: GenerateCSMObjectForClient
/// Description: This method generates
/// javascript code to populate the CMSList object with the ID's and Names
/// of the Customer Service Messages from the string array of CSM ID's.
/// </summary>
//---------------------------------------------------------------------------
public void GenerateCSMObjectForClient(string[] ids){
// Initialize web service variable (Client-side) and
// register client script to call the web service once the browser's DOM has loaded
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "GetCSMMessages")){
var sb = new StringBuilder();sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("$(document).ready(function() {");sb.Append("obj = getCSMMessagesByID([\"");sb.Append(String.Join("\",\"", ids)); //create JavaScript array
sb.Append("\"])");sb.Append("} );");sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCSMMessages", sb.ToString());sb.Length = 0; //clear out sb variable
}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: GenerateCSMObjectForClient
/// Description: This method generates
/// javascript code to populate the CMSList object with the ID's and Names
/// of the Customer Service Messages from the string array of CSM ID's.
/// </summary>
/// <param name="ids">string[]: Array of ID's that need to retrieved</param>
/// <param name="objName">string: The exact Object Name on the Javascript file</param>
//---------------------------------------------------------------------------
public void GenerateCSMObjectForClient(string objName, string[] ids){
// Initialize web service variable (Client-side) and
// register client script to call the web service once the browser's DOM has loaded
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(),objName )){
var sb = new StringBuilder();sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("$(document).ready(function() {");sb.Append(objName);
sb.Append(" = getCSMMessagesByID([\"");sb.Append(String.Join("\",\"", ids)); //create JavaScript array
sb.Append("\"])");sb.Append("} );");sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), objName, sb.ToString());sb.Length = 0; //clear out sb variable
}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: SetCSMsForClient
/// Description: This method generates
/// javascript code to populate the CSM variables
/// by creating a name/value pair for each CSM from
/// its corresponding "Code" field. The messages are written to
/// the Client Browser via the ClientScriptManager.
/// EX. pass in "17,18" and the JavaScript written to the client
/// will be: var CSM_17 = "You must select a letter
/// template."; var CSM_18 = "This appeal cannot be reopened
/// because the status is not Closed.";
/// </summary>
/// <param name="ids">int []: Integer Array of ids</param>
/// <param name="scriptBlockName">string: Script Block Name to make it unique</param>
//---------------------------------------------------------------------------
public void SetCSMsForClient(int[] idArray, string scriptBlockName){
string ids = ConvertIntArrayToSingleString(idArray);if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), scriptBlockName)){
StringBuilder sb = new StringBuilder();DHS.AppBase.CustomerServiceMessagesBLL csmbll = new DHS.AppBase.CustomerServiceMessagesBLL();string errors = csmbll.GetCMSsByIDList(ids);sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append(errors);
sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), scriptBlockName, sb.ToString());}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: SetCSMsForClient
/// Description: This method generates
/// javascript code to populate the CSM variables
/// </summary>
/// <param name="ids">string: String on ID's</param>
/// <param name="scriptBlockName">string: Script Bloack Name to make it unique</param>
//---------------------------------------------------------------------------
public void SetCSMsForClient(string ids, string scriptBlockName){
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), scriptBlockName)){
StringBuilder sb = new StringBuilder();DHS.AppBase.CustomerServiceMessagesBLL csmbll = new DHS.AppBase.CustomerServiceMessagesBLL();string errors = csmbll.GetCMSsByIDList(ids);sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append(errors);
sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), scriptBlockName, sb.ToString());}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: AddDirtyFlag
/// Description: This method adds dirty flag functionality to any page that derives
/// from this class.
/// </summary>
//---------------------------------------------------------------------------
private void AddDirtyFlag(){
var sb = new StringBuilder();// Check to see if the include script exists already.
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "jQueryLink")){
sb.Append(" <script src=\"");sb.Append(ResolveClientUrl(JQUERYURL));
sb.Append("\" type=\"text/javascript\"></script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "jQueryLink", sb.ToString());}
sb.Length = 0;
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "DirtyFlagLink")){
sb.Append(" <script src=\"");sb.Append(ResolveClientUrl(DIRTYFLAGJSCODEURL));
sb.Append("\" type=\"text/javascript\"></script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "DirtyFlagLink", sb.ToString());}
sb.Length = 0;
if (BypassDirtyControls != null && BypassDirtyControls.Count > 0){
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("$(window).load(function() {");sb.Append("setDirtyFlagAttribute([\"");sb.Append(String.Join("\",\"", BypassDirtyControls.ToArray()));sb.Append("\"])");sb.Append("} );");sb.Append("</script>");}
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "ByPassDirtyFlagList")){
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ByPassDirtyFlagList", sb.ToString());}
//Reset the dirty flag on postback
if (IsPostBack){
Control postbackControl = DHS.AppBase.Global.GetPostBackControl(this.Page);if (postbackControl == null || postbackControl.ID == null){
return;}
else
{
if (postbackControl.GetType().ToString() != "System.Web.UI.WebControls.Button" &&postbackControl.GetType().ToString() != "System.Web.UI.WebControls.LinkButton" &&!IsControlInDirtyBypassList(postbackControl.ClientID.ToString()))
{
if (!this.Page.ClientScript.IsStartupScriptRegistered("ResetSetDirtyFlag")){
string jScript = string.Empty;jScript = @"<script language='javascript' type='text/javascript'>if (typeof ($.DHSJQuery.dirtyFlag) != 'undefined')
{
$.DHSJQuery.dirtyFlag = 1;
}
</script>";this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ResetSetDirtyFlag", jScript);}
}
if (postbackControl.ID.ToUpper().Contains("SAVE")){
if (!this.Page.ClientScript.IsStartupScriptRegistered("SaveButtonClicked")){
string jScript = string.Empty;jScript = @"<script language='javascript' type='text/javascript'>if (typeof ($.DHSJQuery.SaveClicked) != 'undefined')
{
$.DHSJQuery.SaveClicked = 1;
}
</script>";this.Page.ClientScript.RegisterStartupScript(this.GetType(), "SaveButtonClicked", jScript);}
}
}
}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: IsControlInDirtyBypassList
/// Description: Method that checks to see if the control that caused
/// a postback exists in the bypass dirty flag list.
/// </summary>
///
/// <param name="ctrlName">The name of the control that caused the postback</param>
/// <returns>boolean</returns>
//---------------------------------------------------------------------------
private bool IsControlInDirtyBypassList(string ctrlName){
bool retVal = false;if (BypassDirtyControls != null){
if (BypassDirtyControls.Contains(ctrlName)){
retVal = true;}
}
return retVal;}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: AddCheckinCode
/// Description: Method that adds a JavaScript function to a derived page that
/// when used calls a web service to check in a record by the primary key
/// value (recordID) and the table name it belongs.
/// </summary>
//---------------------------------------------------------------------------
private void AddCheckinCode(){
var sb = new StringBuilder();if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "CheckInLink")){
sb.Append(" <script src=\"");sb.Append(ResolveClientUrl(CHECKINJSCODEURL));
sb.Append("\" type=\"text/javascript\"></script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CheckInLink", sb.ToString());}
sb.Length = 0;
if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "CheckInRecordClientCode")){
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("$(document).ready(function() {");sb.Append("$.DHSCheckIn.CheckInRecordURL = \"");sb.Append(this.Page.ResolveClientUrl(CHECKINSVCURL));sb.Append("\"; $.DHSCheckIn.CheckInTableURL = \"");sb.Append(this.Page.ResolveClientUrl(CHECKINTABLESVCURL));sb.Append("\"; $.DHSCheckIn.CheckInAppealAndRelatedAppealsURL = \"");sb.Append(this.Page.ResolveClientUrl(CHECKINAPPEALANDRELATEDAPPEALSURL));sb.Append("\"; $.DHSCheckIn.CheckInAppealAndRelatedAppealsByDocumentIDURL = \"");sb.Append(this.Page.ResolveClientUrl(CHECKINAPPEALANDRELATEDAPPEALSBYDOCUMENTIDSURL));sb.Append("\"");sb.Append("} );");sb.Append("</script>");this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CheckInRecordClientCode", sb.ToString());}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: LogError
/// Description: Method that Logs errors to the Errors Database
/// </summary>
///
/// <param name="ex">a reference to the exception object in the method that held the exception </param>
/// <param name="userID">the id of the logged in user </param>
/// <returns>String error message</returns>
//---------------------------------------------------------------------------
public string LogError(ref Exception ex, int userID){
logError.UserID = userID != 0 ? userID : 1;
logError.Module = ex.TargetSite.DeclaringType.Name + "." + ex.TargetSite.ToString();logError.Description = ex.Message;
evLogger.InsertARTSError(logError);
return "An unexpected error has occurred in the ARTS application. The error has been logged. Please contact your supervisor for assistance.";}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: LogError
/// Description: Method that Logs errors to the Errors Database
/// </summary>
///
/// <param name="ex">a reference to the exception object in the method that held the exception </param>
/// <param name="userID">the id of the logged in user </param>
/// <returns>String error message</returns>
//---------------------------------------------------------------------------
public string LogError(ref Exception ex, int userID, string url){
//var bll = new DHS.ARTS.BLL.ARTSBLL();
//bll.CheckInRecord(appealID, "Appeals", userID);
//if (ex is SqlException)
//{
// SqlException abc = (SqlException)ex;
// if (abc.Number == 50005 || abc.Message.Contains("50005"))
// {
// base.ShowMessageBox(bll.GetCSM(830));
// }
// else
// {
// if (abc.Number == 50006 || abc.Message.Contains("50006"))
// {
// base.ShowMessageBox("Modified By or Modified Date not being set");
// }
// else
// {
// base.ShowMessageBox(base.LogError(ref ex, userID));
// bll.CheckInRecord(appealID, "Appeals", userID);
// }
// }
//}
//else
//{
// this.Dispose();
// base.ShowMessageBox(base.LogError(ref ex, userID));
// bll.CheckInRecord(appealID, "Appeals", userID);
//}
logError.UserID = userID != 0 ? userID : 1;
logError.Module = ex.TargetSite.DeclaringType.Name + "." + ex.TargetSite.ToString();logError.Description = ex.Message;
evLogger.InsertARTSError(logError);
string[] clientMessage = this.GetMessageByID(1116);string msg = string.Empty;if (clientMessage[2].ToString() != string.Empty){
msg = clientMessage[2].ToString();
}
else
{
msg = "An unexpected error has occurred in the ARTS application. The error has been logged. Please contact your supervisor for assistance.";}
HttpContext.Current.Response.Redirect("~/UI/UnhandledException.aspx");return msg;}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: LogError
/// Description: Method that Logs errors to the Errors Database
/// </summary>
///
/// <param name="ex">a reference to the exception object in the method that held the exception </param>
/// <param name="customError">a custom error message that will show with the actual error message</param>
/// <param name="userID">the id of the logged in user </param>
/// <returns>String error message</returns>
//---------------------------------------------------------------------------
public string LogError(ref Exception ex, string customError, int userID){
logError.UserID = userID != 0 ? userID : 1;
logError.Module = ex.TargetSite.DeclaringType.Name + "." + ex.TargetSite.ToString();logError.Description = customError + " " + ex.Message;evLogger.InsertARTSError(logError);
return "An unexpected error has occurred in the ARTS application. The error has been logged. Please contact your supervisor for assistance.";}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: CheckOutRecord
/// Description: Checks out the current record preventing other users from
/// editing it while it's checked out.
/// </summary>
///
/// <param name="recordID">record ID</param>
/// <param name="tableName">Table Name</param>
/// <param name="userID">User ID</param>
/// <returns>String Array</returns>
//---------------------------------------------------------------------------
public string[] CheckOutRecord(int recordID, string tableName, int userID){
//Instantiating class
var bll = new CheckInOutBLL();//Call bll method to check out current record
return (bll.CheckOutRecord(recordID, tableName, userID));}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: CheckInRecord
/// Description: Checks in the current record releasing it for other user to use.
/// </summary>
///
/// <param name="recordID">record ID</param>
/// <param name="tableName">Table Name</param>
/// <param name="userID">User ID</param>
//---------------------------------------------------------------------------
public void CheckInRecord(int recordID, string tableName, int userID){
//Instantiating class
var bll = new CheckInOutBLL();//Call bll method to check out current record
bll.CheckInRecord(recordID, tableName, userID);
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: CheckInAppealAndRelatedAppeals
/// Description: Checks in the current appeal and its related appeals records
/// releasing them for other users to use.
/// </summary>
///
/// <param name="appealID">appeal ID</param>
/// <param name="userID">user ID</param>
//---------------------------------------------------------------------------
public void CheckInAppealAndRelatedAppeals(int appealID, int userID){
var bll = new CheckInOutBLL();List<int> relatedAppeals = bll.GetAppealAndItsRelatedAppeals(appealID);foreach (int i in relatedAppeals)CheckInRecord(i, "Appeals", userID);bll = null;}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: CheckOutAppealAndRelatedAppeals
/// Description: Checks out the current appeal and its related appeal records
/// locking them for other users. Also returns string array
/// containing information about another user if they have the
/// record checked out
/// </summary>
///
/// <param name="appealID">appeal ID</param>
/// <param name="userID">user ID</param>
//---------------------------------------------------------------------------
public string[] CheckOutAppealAndRelatedAppeals(int appealID, int userID){
var bll = new CheckInOutBLL();string[] checkedOutInfo = new string[2];List<int> relatedAppeals = bll.GetAppealAndItsRelatedAppeals(appealID);foreach (int id in relatedAppeals){
checkedOutInfo = CheckOutRecord(id, "Appeals", userID);if (Convert.ToBoolean(checkedOutInfo[0].ToString()) == true)break;}
bll = null;return checkedOutInfo;}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: IsRecordCheckedOut
/// Description: Checks in the current record releasing it for other user to use.
/// </summary>
///
/// <param name="recordID">record ID</param>
/// <param name="tableName">Table Name</param>
/// <param name="userID">User ID</param>
///
/// <returns>String Array</returns>
//---------------------------------------------------------------------------
public string[] IsRecordCheckedOut(int recordID, string tableName, int userID){
//Instantiating class
var bll = new CheckInOutBLL();//Call bll method to check out current record
return (bll.IsRecordCheckedOut(recordID, tableName, userID));}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: GetMessageByID
/// Description: Get Customer Service Message by ID
/// </summary>
///
/// <param name="messageID">Primary Key for Customer Service Message</param>
/// <returns>Customer Service Message simple string array</returns>
//---------------------------------------------------------------------------
public string[] GetMessageByID(int messageID){
//Instantiating class
var bll = new CustomerServiceMessagesBLL();//Call bll method to check out current record
return (bll.GetMessageByID(messageID));}
/// <summary>
/// Method Name: AddCharLimit
/// Parameters:
/// tb - The textbox control will be the textbox that the application will limit
/// maxChars - The maximum number of characters that the box will allow.
/// lbl - optional the label control displays a counter that shows the current
/// number of characters that the user has typed.
/// NOTE: to make the label optional, simply pass null instead of a label control.
/// Description:
/// This function generates the javascript code to limit the user from
/// typing in more than the maximum characters.
/// The javascript also dynamically increments a counter(the label passed as a parameter)
/// to display the number of characters typed by the user.
/// when the limit is reached and the sound=true attribute has been added to the textbox,
/// the user should hear a sound (if they have a sound card and speakers).
/// Returns:
/// Nothing
/// Example:
/// In Load_Event do the following:
/// //Adds the Character limit to a textbox and also updates a
/// //label control to reflect the current count of characters
/// addCharLimit(this.TextBox1, 20, this.Label1);
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Web.UI.ITextControl.set_Text(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]protected void AddCharLimit(TextBox tb, int maxChars, Label lbl){
// add the needed attributes that the textbox and label controls.
if (lbl != null){
//pass the label control into the charCounter javascript function
tb.Attributes.Add("onkeyup", "charCounter(document.all('" + lbl.ID + "'));");lbl.Text = "0 of " + maxChars.ToString();}
else
{
//no label control
tb.Attributes.Add("onkeyup", "return charCounter();");}//if(lbl != null)
tb.Attributes.Add("onkeydown", "return limitChars();");tb.Attributes.Add("maxChars", maxChars.ToString());tb.Attributes.Add("sound", "true");ClientScriptManager csm = this.Page.ClientScript;Type cstype = this.GetType();//add the sound object
csm.RegisterClientScriptBlock(cstype, "BgSound", "<bgsound id='ding' src='' loop='0'>");csm.RegisterClientScriptBlock(cstype, "CharLimit",@"<script>// ***************Begin CharLimit********************
var soundFilePath = 'Sounds/Windows_XP_Ding.wav';
function charCounter(label)
{
var obj = event.srcElement;
var num = obj.value.length;
var text = obj.value;
var total = obj.maxChars;
var sound = obj.sound;
if(label)
{
if(num > -1)
{
if (num <= total)
{
label.innerHTML = obj.value.length + "" of "" + total;
}else
{
obj.value = text.substring(0,total);
label.innerHTML = total + "" of "" + total;
if(sound)
{
if(sound.toLowerCase() == 'true')
{
document.all('ding').src = soundFilePath;
}
}
}
}else
{
label.innerHTML = 0 + "" of "" + total;
}
}else
{
if (num > total)
{
obj.value = text.substring(0,total);
if(sound)
{
if(sound.toLowerCase() == 'true')
{
document.all('ding').src = soundFilePath;
}
}
}
}
}
function limitChars()
{
var obj = event.srcElement;
if(obj.maxChars)
{
if(obj.value.length > obj.maxChars)
{
return false;
}
else
{
return true;
}
}
}
// ***************End CharLimit********************
</script>
");}
/// <summary>
/// Method Name: HighlightTextInTextbox
/// Description:
/// This function generates the javascript that will highlight the text in a textbox
/// that is in the strPattern parameter
///
/// Parameters:
/// tb - The Textbox object that will hold the highlighted text
/// strPattern - the text to be highlighted
/// Returns:
/// Nothing
///
/// Example:
/// In an object's Click_Event do the following:
///
/// string strFormat = "yyyy";
///
/// if (isFormattingInsideString(this.txtHighlightBox.Text, strFormat))
/// {
/// this.highlightTextInTextbox(this.txtHighlightBox, strFormat);
/// }
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]protected void HighlightTextInTextbox(TextBox tb, string strPattern){
if (String.IsNullOrEmpty(strPattern) == false){
string strInput = tb.Text;//find pattern inside text before trying to highlight.
if (strInput.IndexOf(strPattern, 0, strInput.Length) > -1){
//replace the \r\n with a single character(#) because these two characters
// seem to be ignored when using index of.
strInput = strInput.Replace("\r\n", "#");//get the starting position of the text to be highlighted
int iStartPos = strInput.IndexOf(strPattern, 0, strInput.Length);int iLengthString = strPattern.Length; // get the total number of characters in the string
//debug code
//Response.Write(strInput.ToString() + "<br>");
//Response.Write("Start Position= " + iStartPos + " Length of Searched String= "
//+ strPattern.Length + " Length of TextBox= " + strInput.Length.ToString());
//Build Javascript client code to highlight the text
//The function that highlights the text works in
// versions of Internet Explorer 5 and greater.
ClientScriptManager csm = this.Page.ClientScript;Type cstype = this.GetType();csm.RegisterClientScriptBlock(cstype, "HighlightText",@"<script language='JavaScript'>
<!--
function highlightText(oTextbox)
{
var oRange = oTextbox.createTextRange();
oRange.moveStart('character', " + (iStartPos) + @");oRange.moveEnd('character'," + (iLengthString + iStartPos) + " - " + strInput.Length.ToString() + @");oRange.select();
oTextbox.focus();
}
// -->
</script>
");// send the javascript code to call the above function
csm.RegisterStartupScript(cstype, "onload", @"<script language=javascript>
highlightText(document.getElementById('" + tb.ID.ToString() + @"'));</script>");}
}
else if (tb == null){
throw new ArgumentNullException(tb.ToString());}
else if (String.IsNullOrEmpty(strPattern)){
throw new ArgumentNullException(strPattern);}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: ShowMessageBox
/// Description: This method is used to validate a date field from server side.
/// It will return true if txtDate parameter holds a valid date.
/// </summary>
/// <param name="aspxPage">An ASP.NET Page</param>
/// <param name="strMessage">The message to display in the message box</param>
/// <returns>na</returns>
///---------------------------------------------------------------------------
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]protected static void ShowMessageBox(System.Web.UI.Page aspxPage, string strMessage){
if ((aspxPage != null) && (String.IsNullOrEmpty(strMessage) == false)){
ClientScriptManager csm = aspxPage.ClientScript;Type cstype = aspxPage.GetType();string sJavaScript = "<script language=javascript>\n";sJavaScript += "alert('" + strMessage + "');\n";sJavaScript += "</script>";csm.RegisterStartupScript(cstype, "MessageBox", sJavaScript);}
else if (aspxPage == null){
throw new ArgumentNullException(aspxPage.ToString());}
else if (String.IsNullOrEmpty(strMessage) == true){
throw new ArgumentNullException(strMessage);}
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: ShowMessageBox
/// Description: This method is used to display an alert(Popup) on the client browser when
/// a server-side error occurs.
/// </summary>
/// <param name="strMessage">The message to display in the message box</param>
/// <returns>na</returns>
///---------------------------------------------------------------------------
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]protected void ShowMessageBox(string strMessage){
var sb = new StringBuilder();sb.Append("<script type=\"text/javascript\" language=\"javascript\">");sb.Append("if (typeof jQuery != 'undefined') {");sb.Append("$(window).load(function() {");sb.Append("alert('");sb.Append(strMessage);
sb.Append("');");sb.Append("});}");sb.Append("else {");sb.Append("alert('");sb.Append(strMessage);
sb.Append("');");sb.Append("}");sb.Append("</script>");if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "ServerSideAlertMessage")){
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ServerSideAlertMessage", sb.ToString());}
sb.Length = 0;
}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: ConvertIntArrayToSingleString
/// Description: Utility Function to take in an array of integers
/// and return a single comma delimited string.
/// </summary>
///
/// <param name="intArray">Integer Array</param>
/// <returns>Comma delimited string of integers passed int method</returns>
//---------------------------------------------------------------------------
protected string ConvertIntArrayToSingleString(int[] intArray){
string[] stringArray =Array.ConvertAll<int, string>(intArray, new Converter<int, string>(ConvertIntToString));
string result = string.Join(",", stringArray);return result;}
//---------------------------------------------------------------------------
/// <summary>
/// Method Name: ConvertIntToString
/// Description: Utility Function to convert any integer to a string.
/// </summary>
///
/// <param name="intArray">Integer Array</param>
/// <returns>string</returns>
//---------------------------------------------------------------------------
protected string ConvertIntToString(int intValue){
return intValue.ToString();}
#endregion Instance Methods
#region Static Methods
#endregion Static Methods}
}