Test Results Viewer Source Code – Grid Page – C#

Sample Source Code


//************************************************************************
//                                                                       *
//                           Aero Engine Controls                        *
//                                                                       *
//************************************************************************
//
//       TITLE:-         AECData - Serial Number Lookup Application
//       IDENTITY:-      Default.aspx.cs
//       WRITTEN BY:-    R.J.Tyler
//       MODIFIED BY:-
//       DATE:-          25-JAN-2013
//
//
//
//       ©2011 - 2013 Rolls-Royce Goodrich Engine Control Systems Limited.
//       The data contained in this document, is the property of Rolls-Royce Goodrich
//       Engine Control Systems Limited ("the Company") and it may not be copied or
//       communicated to a third party, or used for any purpose, other than that for
//       which it was supplied, without the Company's prior written consent.
//
//************************************************************************
//                                                                       *
//       Change History of Default.aspx.cs                               *
//                                                                       *
//************************************************************************
//
//      The Serial Number lookup application allows test results for any 
//      serial number stored within the IntraStage database to be viewed
//      in a web browser.
//
//      On entering a Serial Number (or sub-string) the Application returns
//      a list of matching serial number instances, associated event details
//      and a hierarchical grid of the relevant tests results for each event
//      in the database   
//
//
//       Version         Author				Date            Change
//															Description
//
//      00A				R.Tyler			    26-JAN-2010		1. Original
//		00B				R.Tyler			    08-JUN-2010		2. Published on Intra2 as Trial
//		00C				R.Tyler/J.Melling	04-OCT-2011		3. Rework of Default.aspx.cs logic
//		00D				R.Tyler				15-NOV-2011		4. Prepare for Eworq baseline
//      00E			    R.Tyler				21-MAY-2012		5. Improve Operation and Features
//      00F			    R.Tyler				15-OCT-2012		6. Added 'AddMeta' option to menu
//      00G			    R.Tyler				12-NOV-2012		7. Added Strip Line Logic
//      00H             R.Tyler             25-JAN-2013     8. Added Multi Event Enum Selection
//      00I             R.Tyler             01-MAY-2013     9. Added SPC Limits Output, Link to DMS
//
//************************************************************************
//
using DBauer.Web.UI.WebControls;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;


namespace Search
{
    public partial class Search : System.Web.UI.Page
    {
        #region A1 - Search class Parameters
        /// 
        // A1 - Parameters for the Search Class 
        ///  
        /////////////////////////////////////////////////////////////////////////////////////

        // A2 - General
        private String cmdString = "";
        private SqlConnection conn;
        private GlobalParam.AccessSiteDb currentSiteAccess;

        // User entered parameter handling
        private string remoteSN = "";
        private string remoteEID = "none";
        private string remotePFStatus = "empty";
        String requiredSortOpt = "-1";

        // A4
        private string snString = "";
        private string trimmedsnString = "";

        // A5
        private const string eventTableName = "EventItems";

        // A7
        private const string testTableName = "TestItems";

        // B4
        protected DBauer.Web.UI.WebControls.HierarGrid HG1;

        // B9
        private SqlDataAdapter daEventList;
        private SqlDataAdapter daEvDetailList;
        private DataSet dsEventList;

        // B11
        private SqlDataAdapter daEventEnumID;
        private const string eventEnumTableName = "EventEnumItems";

        public String sortOptCookieValue = "0";
        public String lUserSelectedOrderByRequest = "void";

        #endregion

        #region A2 - Page_Load method
        /// 
        /// A2 - Page_Load method
        ///  
        /////////////////////////////////////////////////////////////////////////////////////
        protected void Page_Load(object sender, EventArgs e)
        {
            // create instance of Master event
            Master.SearchMenuClickEvent += new mst2Delegate(mstMCEClick);

            if (!ClientScript.IsStartupScriptRegistered("diagsortopt"))
            {
                ClientScript.RegisterStartupScript(typeof(Page), "diagsortopt", "dlgopen4();", true);
            }

            GlobalParam.currentPageFileName = new FileInfo(this.Request.Url.LocalPath).Name;

            // determine the current database in use - for this website
            string sessDbType = ConfigurationManager.AppSettings["ThisWebSite"];

            // determine the current database in use - for this website
            GlobalFunct.ServerSelect(sessDbType);

            // if any parameters present in invoke line 
            if (Request.QueryString.Count >= 1)
            {
                // if access to this viewer page is by URL - store the full request query string for checking 
                String cmdStringRaw = Request.QueryString.ToString();
                cmdString = cmdStringRaw.ToLower();

                // if serial number parameter present in invoke line (also allow setting of the orderby cookie)
                if ((Request.QueryString["SN"] != null) || (Request.QueryString["orderby"] != null))
                {
                    // no action required
                }
                else
                {
                    GlobalFunct.WebMsgBox.Show(" Please provide a serial number in the URL (e.g &sn=$$$ ) ");
                    return;
                }
            }

            // if first time through
            if (!IsPostBack)
            {
                if (!String.IsNullOrEmpty(Request.QueryString["sb"]))
                {
                    // store the hide side barflag
                    if (cmdString.Contains("sb"))
                    {
                        String hideSBLower = Request.QueryString["sb"].ToLower().ToString();
                        String trimmedHideSb = hideSBLower.Trim();

                        // hide the left side tool bar, uses passed parameter logic "&sb=hide"
                        if (trimmedHideSb == "hide")
                        {
                            // apply page class to enable side hidebar
                            if (currentSiteAccess == 0)  // mech database access
                            {
                                ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Add("class", "mechsite sp hidesb");
                                leftbar.Visible = false;
                            }
                            else
                            {
                                ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Add("class", "elecsite sp hidesb");
                                leftbar.Visible = false;
                            }
                        }
                        else
                        {
                            leftbar.Visible = true;
                            ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Remove("hidesb");

                            // apply Focus, as the sidebar is in view
                            ClientScript.RegisterStartupScript(typeof(Page), "SetFocus", "");
                        }
                    }
                }
                else
                {
                    // improved method of control focus -- SNEntryTextBox.Focus();
                    ClientScript.RegisterStartupScript(typeof(Page), "SetFocus", "");
                }

                // if serial number parameter present in invoke line 
                if (Request.QueryString["SN"] != null)
                {
                    // store the serial number
                    if (cmdString.Contains("sn"))
                    {
                        remoteSN = Request.QueryString["sn"].ToString();
                        HRemoteSN.Value = remoteSN;
                    }

                    // store the event id
                    if (cmdString.Contains("eventid"))
                    {
                        remoteEID = Request.QueryString["eventid"].ToString();
                    }
                    else if (cmdString.Contains("eid"))
                    {
                        remoteEID = Request.QueryString["eid"].ToString();
                    }
                    else
                    {
                        remoteEID = "";
                    }

                    // store the pass fail status
                    if (cmdString.Contains("pf"))
                    {
                        String lRemotePFStatus = Request.QueryString["pf"].ToString();
                        remotePFStatus = GlobalFunct.UppercaseFirst(lRemotePFStatus);
                    }
                    else
                    {
                        string localPFStatus = "0"; //set PassFailFilter to "None"
                        rblPassFail.Items[Convert.ToInt32(localPFStatus)].Selected = true;
                    }

                    // check for the existence of a cookie
                    if (Request.Cookies["SortPref"] != null)
                    {
                        //requestcode = Convert.ToInt32(Request.Cookies["SortPref"].Value);
                        sortOptCookieValue = Request.Cookies["SortPref"].Value;
                    }
                    else
                    {
                        sortOptCookieValue = "-1";
                    }
                    // Set user selected orderby preference - check and write to cookie if requested
                    SetSortByPreference(sortOptCookieValue);

                    // if serial number string present carryout db search
                    if (remoteSN != "")
                    {
                        SNEntryTextBox.Text = remoteSN;
                        DoSearch(remoteEID);
                    }

                    try
                    {
                        // handle user supplied (url) parameters
                        if ((remoteEID != null) && (remoteEID != ""))
                        {
                            if (remoteEID != "none")
                            {
                                if (remotePFStatus != "empty")
                                {

                                    if (rblPassFail.Items.FindByValue(remotePFStatus) != null)
                                    {
                                        rblPassFail.Items.FindByValue(remotePFStatus).Selected = true;
                                        LoadPassFailSelection(remotePFStatus);
                                    }
                                    else if (rblPassFail.Items.FindByText(remotePFStatus) != null)
                                    {
                                        rblPassFail.Items.FindByText(remotePFStatus).Selected = true;
                                        LoadPassFailSelection(remotePFStatus);
                                    }
                                }

                                ddlEventRecord.ClearSelection();
                                if (ddlEventRecord.Items.FindByValue(remoteEID) != null)
                                {
                                    ddlEventRecord.Items.FindByValue(remoteEID).Selected = true;

                                    // generate hierar grid table
                                    LoadTableData(Convert.ToInt32(ddlEventRecord.SelectedValue));

                                    string EID = remoteEID;

                                    // store EID input string
                                    HEventRecIdentity.Value = EID;
                                }
                                else
                                {
                                    GlobalFunct.WebMsgBox.Show("The Event Identifier has not been found in the lookup table for the current Serial Number. Ref: D351");
                                    return;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (GlobalFunct.IsCriticalException(ex))
                            if (GlobalParam.showXMLerrors) { throw; }
                            else
                            {
                                GlobalFunct.WebMsgBox.Show("A database connection error has occurred. Ref:D353. Detail:" + ex.Message);
                            }
                    }
                }
            }
            else
            {
                /// postback in progress
                // get javascript post back parameter
                String PostBackParameter = Request["__EVENTARGUMENT"];

                // Reading from hidden variables stored from search page
                String stringToCheck = "SortOption";

                if (!String.IsNullOrEmpty(PostBackParameter))
                {
                    if (PostBackParameter.Contains("bHMenu"))
                    {
                        // PostBackParameter will contain 'bHMenu' or point click (numeric) parameters
                        // no processing required
                    }
                    else if (PostBackParameter.Contains(stringToCheck))
                    {

                        String[] splitEventArg = new String[2];

                        splitEventArg = PostBackParameter.Split(',');

                        if ((splitEventArg != null) || (splitEventArg.Length > 1))
                        {
                            // first parameter can be discarded
                            requiredSortOpt = splitEventArg[1];
                        }
                        else
                        {
                            requiredSortOpt = splitEventArg[0];
                        }

                        //SetSortByPreference(requiredSortOpt);
                        SelectSortBy(requiredSortOpt);

                        // reload the page applying new sort option
                        DoSearch("");
                    }
                }
            }
        }
        #endregion

        #region A3 - SearchButton_Click
        /// 
        /// A3 - Serial Number Lookup on button-click
        /// 
        /// //////////////////////////////////////////////////////////////////////////////////
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            DoSearch("");
        }

        #endregion

        #region A4 - DoSearch
        /// 
        /// A4 - Carry out a serial number search
        /// 
        /// //////////////////////////////////////////////////////////////////////////////////
        private void DoSearch(string remoteEID)
        {
            // Table for AssetSN/AssetID 
            DataTable dtSerialNumbers = new DataTable();

            // Reset the SN re-set flag to enable new paging model
            HSerialReset.Value = "true";

            dtSerialNumbers = null;

            // store the user input SN string
            snString = SNEntryTextBox.Text;

            trimmedsnString = snString.Trim();

            //if the string is empty - clean the drop down lists for serial number and event
            if (trimmedsnString == "")
            {
                // clear data from all controls
                ClearGridPage();
                return;
            }

            try
            {
                // create AssetSN/AssetID Table
                dtSerialNumbers = this.CreateAssetSNTable(SNEntryTextBox.Text, cblFilter.Items[0].Selected, cblFilter.Items[1].Selected, cblFilter.Items[2].Selected);

                if (dtSerialNumbers.Rows.Count == 0)
                {
                    GlobalFunct.WebMsgBox.Show(" No serial numbers found which match your criteria.");

                    // clear data from all controls
                    ClearGridPage();
                    return;
                }
                else
                {
                    // populate the Serial Number drop down list
                    this.ddlAssetSN.DataSource = dtSerialNumbers;

                    this.ddlAssetSN.DataBind();
                    if (remoteEID != "")
                    {
                        this.ddlAssetSN.Items.FindByValue(GetAssetIDFromEventID(remoteEID)).Selected = true;
                    }
                }

                LoadEventList(Convert.ToInt32(ddlAssetSN.SelectedValue));
            }

            catch (Exception ex)
            {
                if (GlobalFunct.IsCriticalException(ex))
                    if (GlobalParam.showXMLerrors) { throw; }
                    else
                    {
                        GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D486. Detail:" + ex.Message);
                    }
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }

        }
        #endregion

        #region A5 - CreateAssetSNTable
        /// 
        /// A5 - CreateAssetSNTable - Create the Asset Serial Number Table based on 
        /// current SN entered by the user. Returns an AssetID + AssetSN table
        ///  
        /////////////////////////////////////////////////////////////////////////////////////
        public DataTable CreateAssetSNTable(string currentSN, bool SerialNumberMOFilter, bool SerialNumberMRFilter, bool SerialNumberCROFilter)
        {
            DataSet dsAssetItems = new DataSet();

            // store query string locally
            string SQLSNTable = "";

            // declare return container object
            DataTable dtSerialNumbers = new DataTable();
            dtSerialNumbers = null;

            // define parameters used in command object
            SqlParameter param = new SqlParameter();
            param.ParameterName = "@localCurrSN";

            // handle user input spaces
            string localCurrSN = currentSN.Trim();
            conn = GlobalParam.DBConnect();
            // handle user input string gaps
            if (conn != null)
            {
                localCurrSN.Replace(" ", "%");

                SQLSNTable = "SELECT DISTINCT AssetSN, AssetID FROM AssetItems ";
                SQLSNTable = SQLSNTable + " WHERE AssetSN LIKE ('%" + @localCurrSN + "%') ";
                SQLSNTable = SQLSNTable + " AND exists (Select AssetID from tmpRptAssetEvent)";

                // if the MO filter checkbox in checked state
                if (!SerialNumberMOFilter)
                {
                    SQLSNTable = SQLSNTable + " AND [AssetSN] not like 'MO%'";
                }

                if (!SerialNumberMRFilter)
                {
                    SQLSNTable = SQLSNTable + " AND [AssetSN] not like 'MR%'";
                }

                if (!SerialNumberCROFilter)
                {
                    SQLSNTable = SQLSNTable + " AND [AssetSN] not like 'CRO%'";
                }

                // additional query clause to handle disposed (hidden) data
                SQLSNTable = SQLSNTable + " AND ACTIVE = 1";

                // sort with latest sn at the top of the list
                SQLSNTable = SQLSNTable + " ORDER BY AssetSN DESC";

                // instantiate a new command with a query and connection
                SqlCommand cmd = new SqlCommand(SQLSNTable, conn);

                // initialise SqlDataAdapter with the query/connection command
                SqlDataAdapter daAssetItems = new SqlDataAdapter(cmd);

                // add parameter to the adapter object
                daAssetItems.SelectCommand.Parameters.Add(new SqlParameter("@localCurrSN", localCurrSN));

                // fill in insert, update, and delete commands
                SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daAssetItems);

                try
                {
                    conn.Open();

                    // fill the dataset
                    daAssetItems.Fill(dsAssetItems, eventTableName);

                    int numberOfRows = daAssetItems.Fill(dsAssetItems, "AssetSN");
                    dtSerialNumbers = dsAssetItems.Tables["AssetSN"];
                }
                catch (Exception ex)
                {
                    if (GlobalFunct.IsCriticalException(ex))
                        if (GlobalParam.showXMLerrors) { throw; }
                        else
                        {
                            GlobalFunct.WebMsgBox.Show("A database connection error has occurred. Ref:D582. Detail:" + ex.Message);
                        }
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            } // no available connection!

            // return AssetID + AssetSN table
            return dtSerialNumbers;
        }
        #endregion

        #region A6 - EventDetChangeUpdateGrid
        /// 
        /// A6 - EventDetChangeUpdateGrid - Update the data grid with new event details
        ///  
        /////////////////////////////////////////////////////////////////////////////////////
        private void EventDetChangeUpdateGrid(string EventRecordIdentity)
        {
            // instantiate new Data Sets  
            DataSet dsTestRunDet = new DataSet();
            DataTable dtTestRunDet = new DataTable();
            DataSet dsChartDet = new DataSet();

            try
            {
                int EventId = Convert.ToInt32(EventRecordIdentity);

                // query string
                string SQLquery;

                StringBuilder sbTestRunDet;

                sbTestRunDet = new StringBuilder();
                // build query string
                sbTestRunDet.Append(" SELECT IS_MetaData.MetaName AS MName, IS_MetaData.MetaValue AS MValue");
                sbTestRunDet.Append(" FROM IS_MetaData INNER JOIN IS_MetaEnum ");
                sbTestRunDet.Append(" ON IS_MetaData.MetaEnumID = IS_MetaEnum.MetaEnumID ");
                sbTestRunDet.Append(" WHERE (((IS_MetaData.LocalID) = " + EventId + ") ");
                sbTestRunDet.Append(" AND IS_MetaEnum.MetaEnumName = 'Events')");

                SQLquery = sbTestRunDet.ToString();

                // set up database link
                conn = GlobalParam.DBConnect();

                // init SqlDataAdapter with connection and select command
                daEvDetailList = new SqlDataAdapter(SQLquery, conn);

                conn.Open();

                // fill the dataset
                daEvDetailList.Fill(dsTestRunDet, testTableName);

                // populate the grid when data is available
                if (dsTestRunDet.Tables[0].Rows.Count > 0)
                {
                    // populate a grid view with the data returned
                    dgEventDetail.DataSource = dsTestRunDet;

                    // bind the data to the grid
                    dgEventDetail.DataBind();

                }
                else
                {
                    // bind an empty row
                    dtTestRunDet = dsTestRunDet.Tables[0];
                    dtTestRunDet.Rows.Add();
                    dgEventDetail.DataSource = dtTestRunDet;
                    dgEventDetail.DataBind();
                }
                // end if
            }
            catch (Exception ex)
            {
                if (GlobalFunct.IsCriticalException(ex))
                    if (GlobalParam.showXMLerrors) { throw; }
                    else
                    {
                        GlobalFunct.WebMsgBox.Show("An Error has occurred. Ref:D667. Detail:" + ex.Message);
                    }
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region A7 - CreateEventsTable
        /// 
        /// A7 - CreateEventsTable - Events Table creation of Results Records 
        ///  
        /// //////////////////////////////////////////////////////////////////////////////////    
        private DataTable CreateEventsTable(long assetID)
        {
            // declare DataTable
            DataTable dtEventRecordList = new DataTable();

            if (assetID != -1)
            {
                // query string
                string SQLEventsTable;

                // set up database link
                conn = GlobalParam.DBConnect();

                // instantiate a new DataSet  
                dsEventList = new DataSet();

                // build query string
                SQLEventsTable = "SELECT convert(nvarchar(20),tmpRptAssetEvent.EventTimeStamp,113) + ' - ' + ProcessEnum.Name + ' - ' + EventEnum.Name + ' - ' + ResultEnum.ResultEnumName as [EventRecord],tmpRptAssetEvent.EventID as [EventID],";
                SQLEventsTable = SQLEventsTable + " tmpRptAssetEvent.EventTimeStamp, ProcessEnum.Name AS ProcessName, EventEnum.Name AS EventName, EventEnum.Description, AssetItems.AssetSN, ResultEnum.ResultEnumName,  [ModelEnum].PartNo";
                SQLEventsTable = SQLEventsTable + " FROM (AssetItems INNER JOIN (((ProcessEnum INNER JOIN tmpRptAssetEvent ON ProcessEnum.ProcessEnumID = tmpRptAssetEvent.ProcessEnumID)";
                SQLEventsTable = SQLEventsTable + " INNER JOIN ProductLineEnum ON ProcessEnum.ProductLineEnumID = ProductLineEnum.ProductLineEnumID)";
                SQLEventsTable = SQLEventsTable + " INNER JOIN EventEnum ON tmpRptAssetEvent.EventEnumID = EventEnum.EventEnumID) ON AssetItems.AssetID = tmpRptAssetEvent.AssetID)";
                SQLEventsTable = SQLEventsTable + " INNER JOIN modelEnum ON tmpRptAssetEvent.modelenum = modelenum.modelEnumid";
                SQLEventsTable = SQLEventsTable + " INNER JOIN ResultEnum ON tmpRptAssetEvent.EventResult = ResultEnum.ResultEnumID";
                SQLEventsTable = SQLEventsTable + " WHERE (((tmpRptAssetEvent.AssetID) = " + assetID + ")) ";
                SQLEventsTable = SQLEventsTable + " ORDER BY [EventTimeStamp] DESC";

                // init SqlDataAdapter with connection and select command
                daEventList = new SqlDataAdapter(SQLEventsTable, conn);

                try
                {
                    conn.Open();

                    // fill the dataset
                    daEventList.Fill(dsEventList, eventTableName);

                    int numberOfRows = daEventList.Fill(dsEventList, "EventRecord");
                    dtEventRecordList = dsEventList.Tables["EventRecord"];

                    // get part number information for display to user
                    Object partNo = dtEventRecordList.Rows[0]["PartNo"];
                    String PartNumString = Convert.ToString(partNo);

                    // get process name information for display to user
                    Object procName = dtEventRecordList.Rows[0]["ProcessName"];
                    String lProcNameString = Convert.ToString(procName);

                    // get process name information for display to user
                    Object eventId = dtEventRecordList.Rows[0]["EventID"];
                    String lEventIdString = Convert.ToString(eventId);

                    PartNumLabel.Text = " " + PartNumString + " ";            
                }
                catch (Exception ex)
                {
                    if (GlobalFunct.IsCriticalException(ex))
                        if (GlobalParam.showXMLerrors) { throw; }
                        else
                        {
                            GlobalFunct.WebMsgBox.Show("A database connection error has occurred. Ref:D745. Detail:" + ex.Message);
                        }
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            else
            {
                // AssetID has not been supplied 
                dtEventRecordList = null;
            }

            // return the EventRecord - 9 fields
            return dtEventRecordList;
        }
        #endregion

        #region A8 - GetEventDetails
        /// 
        /// A8 - GetEventDetails - Events detail string build for user screen
        ///  
        /// //////////////////////////////////////////////////////////////////////////////////   
        private string GetEventDetails(long eventID)
        {
            string EventInfo = "";

            if (eventID != -1)
            {
                // query string
                string SQLEventDetails;

                // set up database link
                conn = GlobalParam.DBConnect();

                // instantiate a new DataSet  
                dsEventList = new DataSet();

                SQLEventDetails = "Select '";
                SQLEventDetails = SQLEventDetails + " 
Event Items
Event Detail:' + PE.Name + ' - ' + EE.Name"; SQLEventDetails = SQLEventDetails + "+ 'DateTime:' + convert(nvarchar(20), TMP.EventTimeStamp,113)"; SQLEventDetails = SQLEventDetails + "+ '
Station:' + StationName"; SQLEventDetails = SQLEventDetails + "+ 'Operator:' + case when US.FirstName = 'Unknown' then '' else US.FirstName + ' ' end + US.LastName"; SQLEventDetails = SQLEventDetails + "+ '
Test Duration:'"; SQLEventDetails = SQLEventDetails + "+ right('0' + rtrim(convert(char(2), convert(int,ExecTime) / (60 * 60))), 2)"; SQLEventDetails = SQLEventDetails + "+ ':' + right('0' + rtrim(convert(char(2), (convert(int,ExecTime) / 60) % 60)), 2) + ':'"; SQLEventDetails = SQLEventDetails + "+ right('0' + rtrim(convert(char(2), convert(int,ExecTime) % 60)),2)"; SQLEventDetails = SQLEventDetails + "+ ' Result: '"; SQLEventDetails = SQLEventDetails + "+ upper(RE.ResultEnumName) + '
'"; SQLEventDetails = SQLEventDetails + " AS [EventDetails]"; SQLEventDetails = SQLEventDetails + " FROM tmpRptassetevent TMP INNER JOIN ProcessEnum PE on PE.ProcessEnumID = TMP.ProcessEnumID"; SQLEventDetails = SQLEventDetails + " INNER JOIN EventEnum EE on EE.EventEnumID = TMP.EventEnumID INNER JOIN Events EV on EV.EventID = TMP.EventID"; SQLEventDetails = SQLEventDetails + " INNER JOIN ResultEnum RE on RE.ResultEnumID = TMP.EventResult INNER JOIN Station ST on ST.StationID = TMP.StationID"; SQLEventDetails = SQLEventDetails + " INNER JOIN Users US on US.UserID = TMP.UsersID "; SQLEventDetails = SQLEventDetails + " WHERE (((TMP.EventID) = " + eventID + ")) "; // init SqlDataAdapter with connection and select command daEventList = new SqlDataAdapter(SQLEventDetails, conn); try { conn.Open(); // fill the dataset int numberOfRows = daEventList.Fill(dsEventList, "EventInfo"); if (numberOfRows == 1) { EventInfo = dsEventList.Tables["EventInfo"].Rows[0]["EventDetails"].ToString(); } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("A database connection error has occurred. Ref:D829. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } else { // EventID has not been supplied EventInfo = ""; } // return the EventRecord - 9 fields return EventInfo; } #endregion #region A9 - GetEventEnumIDFromEventID /// /// A9 - GetEventEnumIDFromEventID - Get EventEnum Identity of the selected Event ID /// /// ////////////////////////////////////////////////////////////////////////////////// public long GetEventEnumIDFromEventID(long eventID) { // declare local Event ID variable long lngValEventEnumID = 0; long lngValEventID = 0; DataRow aRow, bRow; // instantiate new DataSets DataSet dsEventEnumID = new DataSet(); DataSet dsEventID = new DataSet(); // query string string SQLEventEnum; // set up database link conn = GlobalParam.DBConnect(); SQLEventEnum = "Select EventEnumID, EventID from Events where Events.EventID = " + eventID; try { conn.Open(); daEventEnumID = new SqlDataAdapter(SQLEventEnum, conn); // initialize the SqlCommandBuilder object SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daEventEnumID); // Populate the DataSet by running the Fill method of the SqlDataAdapter daEventEnumID.Fill(dsEventEnumID, eventEnumTableName); // check the dataset has tables in it if (dsEventEnumID.Tables[0].Rows.Count > 0) { int numberOfRows = daEventEnumID.Fill(dsEventEnumID, "EventEnumID"); DataTable dtEventEnumID = dsEventEnumID.Tables["EventEnumID"]; int numberOfRows2 = daEventEnumID.Fill(dsEventID, "EventID"); DataTable dtEventID = dsEventID.Tables["EventID"]; // Close the database connection. if (conn != null) { conn.Close(); conn.Dispose(); } aRow = dsEventEnumID.Tables["EventEnumID"].Rows[0]; bRow = dsEventID.Tables["EventID"].Rows[0]; // store the event enum id for chart data use lngValEventEnumID = Convert.ToInt32(aRow["EventEnumID"]); // Get the event id to enable first/last tested filtering lngValEventID = Convert.ToInt32(bRow["EventID"]); } else { // Close the database connection if (conn != null) { conn.Close(); conn.Dispose(); } } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D932. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } // Return the Event Enum ID return lngValEventEnumID; } #endregion #region A10 - GetEventMetaDetail /// /// A10 - GetEventMetaDetail - Event detail Serial Number link Lookup -- reload the SN lookup page /// ///////////////////////////////////////////////////////////////////////////////////// public void GetEventMetaDetail(object assetSN, object eventID) { int EventId = int.Parse(eventID.ToString()); string AssetSN = assetSN.ToString(); string LocalEventIdStr = eventID.ToString(); long LocalEventID = GlobalFunct.Convert2Long(LocalEventIdStr); // declare DataTable DataTable dtEventMetaDataList = null; // query string string SQLEMeta; // set up database link conn = GlobalParam.DBConnect(); // instantiate a new DataSet DataSet dsEventMetaDataList = new DataSet(); // build query string SQLEMeta = "SELECT IS_MetaData.MetaName, IS_MetaData.MetaValue"; SQLEMeta = SQLEMeta + " FROM IS_MetaData INNER JOIN IS_MetaEnum "; SQLEMeta = SQLEMeta + " ON IS_MetaData.MetaEnumID = IS_MetaEnum.MetaEnumID "; SQLEMeta = SQLEMeta + " WHERE (((IS_MetaData.LocalID) = " + LocalEventID + ") "; SQLEMeta = SQLEMeta + " AND IS_MetaEnum.MetaEnumName = 'Events')"; // init SqlDataAdapter with connection and select command SqlDataAdapter daEventMetaDataList = new SqlDataAdapter(SQLEMeta, conn); try { conn.Open(); // fill the dataset daEventMetaDataList.Fill(dsEventMetaDataList); int numberOfRows = daEventMetaDataList.Fill(dsEventMetaDataList, "EventRecord"); dtEventMetaDataList = dsEventMetaDataList.Tables["EventRecord"]; } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D1001. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } #endregion #region A11 - ServerSelect /// < summary> /// A11 - ServerSelect -- Select the web server based on the session Database /// ///////////////////////////////////////////////////////////////////////////////////// public String ServerSelect(string sessDbType) { String SpcOn = ""; // selected the specific server defined in web.config GlobalFunct.SelectSiteServerConfig(sessDbType); if (sessDbType == "Mechanical") { currentSiteAccess = GlobalParam.AccessSiteDb.Mech; // sp is the page id (searchpage) ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Add("class", "mechsite sp"); SpcOn = "MechSpcOn"; } else if (sessDbType == "Mechanical_Old") { currentSiteAccess = GlobalParam.AccessSiteDb.Mech_Old; // sp is the page id (searchpage) ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Add("class", "mechsite sp"); SpcOn = "OldMechSpcOn"; } else if (sessDbType == "Electronic") { currentSiteAccess = GlobalParam.AccessSiteDb.Elec; ((HtmlGenericControl)Master.FindControl("PageBody")).Attributes.Add("class", "elecsite sp"); SpcOn = "ElecSpcOn"; } else { SpcOn = "NoSpcOn"; GlobalFunct.WebMsgBox.Show(" Database Not Found. The server may be off-line."); return SpcOn; } return SpcOn; // site access set up is valid } #endregion #region A12 - SelectSortBy() /// < summary> /// A12 - SelectSortBy() - Use user selected (via dialog) option to set up the hgrid sort order /// ///////////////////////////////////////////////////////////////////////////////////// public void SelectSortBy(string SortOpt) { String lUserSelectedOrderByRequest = SortOpt; // if first time through - carry out a check of the sort by value state if (!IsPostBack) { if (Request.QueryString["orderby"] != null) { String lUserSelectedOrderByRequestRaw = Request.QueryString["orderby"].ToString(); lUserSelectedOrderByRequest = lUserSelectedOrderByRequestRaw.Trim(); } } // if not post back then use passed value if ((lUserSelectedOrderByRequest == "name") || (lUserSelectedOrderByRequest == "1")) { rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("1").Selected = true; //rblSortTable.SelectedValue = "1"; } else if ((lUserSelectedOrderByRequest == "test") || (lUserSelectedOrderByRequest == "2")) { rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("2").Selected = true; } else if ((lUserSelectedOrderByRequest == "namepref") || (lUserSelectedOrderByRequest == "3")) // set 'name' as the preferred sort order { rblSortTable.ClearSelection(); // set the radio button rblSortTable.Items.FindByValue("1").Selected = true; // check the cookie exists if (Request.Cookies["SortPref"] != null) { // remove the cookie by setting expires date in the past Response.Cookies["SortPref"].Expires = DateTime.Now.AddDays(-1); } // set new cookie to 1 rblSortTable.Items[0].Selected = true; // Set up a cookie to persist this Response.Cookies.Set(new HttpCookie("SortPref", "1")); Response.Cookies["SortPref"].Expires = DateTime.Now.AddYears(3); } else if ((lUserSelectedOrderByRequest == "testpref") || (lUserSelectedOrderByRequest == "4")) // set 'test' as the preferred sort order { rblSortTable.ClearSelection(); // set the radio button rblSortTable.Items.FindByValue("2").Selected = true; // check the cookie exists if (Request.Cookies["SortPref"] != null) { // remove the cookie by setting expires date in the past Response.Cookies["SortPref"].Expires = DateTime.Now.AddDays(-1); } // set new cookie to 2 rblSortTable.Items[1].Selected = true; Response.Cookies.Set(new HttpCookie("SortPref", "2")); Response.Cookies["SortPref"].Expires = DateTime.Now.AddYears(3); } else if ((lUserSelectedOrderByRequest == "clearpref") || (lUserSelectedOrderByRequest == "5")) // set no preferred sort order { rblSortTable.ClearSelection(); // set the radio button rblSortTable.Items.FindByValue("1").Selected = true; // check the cookie exists if (Request.Cookies["SortPref"] != null) { // remove the cookie by setting expires date in the past Response.Cookies["SortPref"].Expires = DateTime.Now.AddDays(-1); } else { } // no new cookie rerquired } else { GlobalFunct.WebMsgBox.Show(" URL Parameter not recognised. Please use orderby= (one of) namepref | testpref | name | test "); } } #endregion #region A13 - SetSortByPreference /// < summary> /// A13 - SetSortBy - set user sort preferences. /// 1 - check cookie exists /// 2 - check URL state /// ///////////////////////////////////////////////////////////////////////////////////// public void SetSortByPreference(string SortOptCookieVal) { String SortOptString = "-1"; Int32 sortOrderCode = 0; String lUserSelectedOrderByRequest = "void"; /// Handle case with cookie set or not set // SortOpt is equal to -1 if no cookie has been set on the users PC if (SortOptCookieVal == "-1") { // if user has specified a sort order to use, handle this select case here if (cmdString.Contains("orderby")) { lUserSelectedOrderByRequest = Request.QueryString["orderby"].ToString(); } else { // if not specified on the URL we set the order via the cookie value on users PC // no need to specify alternative state here } } else { // convert the cookie value to integer sortOrderCode = Convert.ToInt32(SortOptCookieVal); } /// handle override of cookie // if the user submits a url with 'name' as the preferred sort order (in the URL) // when 'test' is the actual sort order (Specified in the cookie) // the current submission (name) will take precedence switch (sortOrderCode) { case 1: // name is the sort order code shown in the cookie (if cookie exits) if (lUserSelectedOrderByRequest == "name" || lUserSelectedOrderByRequest == "namepref") { rblSortTable.Items[0].Selected = true; // set 'name' as the sortby } else { rblSortTable.Items[1].Selected = true; // set 'test' as the sortby } break; case 2: // test is the sort order code shown in the cookie (if cookie exits) if (lUserSelectedOrderByRequest == "test" || lUserSelectedOrderByRequest == "testpref") { rblSortTable.Items[1].Selected = true; // set 'test' as the sortby } else { rblSortTable.Items[0].Selected = true; // set 'name' as the sortby } break; case 3: rblSortTable.Items[0].Selected = true; // set 'name' as the sortby break; case 4: rblSortTable.Items[1].Selected = true; // set 'test' as the sortby break; default: // use the on page radio supplied value break; } /// handle radio button states (sidebar and dialog) switch (sortOrderCode) { case 1: SortOptString = "name"; rblDiagSort.ClearSelection(); rblDiagSort.Items.FindByValue("1").Selected = true; rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("1").Selected = true; break; case 2: SortOptString = "test"; rblDiagSort.ClearSelection(); rblDiagSort.Items.FindByValue("2").Selected = true; rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("2").Selected = true; break; case 3: SortOptString = "namepref"; /* use cookie */ rblDiagSort.ClearSelection(); rblDiagSort.Items.FindByValue("3").Selected = true; rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("1").Selected = true; break; case 4: SortOptString = "testpref"; rblDiagSort.ClearSelection(); rblDiagSort.Items.FindByValue("4").Selected = true; rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("2").Selected = true; break; default: SortOptString = "name"; rblDiagSort.ClearSelection(); rblDiagSort.Items.FindByValue("1").Selected = true; rblSortTable.ClearSelection(); rblSortTable.Items.FindByValue("1").Selected = true; break; } if (Request.QueryString["orderby"] != null) { SelectSortBy(SortOptString); } else { // no cookie exists } } #endregion #region B1 - ddlAssetSN_SelectedIndexChanged /// /// B1 - ddlAssetSN_SelectedIndexChanged - enables Serial Number Index Changed event /// by calling the LoadEventList function /// /// ////////////////////////////////////////////////////////////////////////////////// protected void ddlAssetSN_SelectedIndexChanged(object sender, EventArgs e) { // Debug: Get the currently selected item in the ListBox. string curItem = ddlAssetSN.SelectedItem.ToString(); LoadEventList(Convert.ToInt32(ddlAssetSN.SelectedValue)); } #endregion #region B2 - LoadEventList /// /// B2 - LoadEventList - Load the events based on the Serial Number ddl selection /// /// ////////////////////////////////////////////////////////////////////////////////// protected void LoadEventList(Int32 selectedID) { // Table for EventID list for a particular AssetID/Serial number DataTable dtEvents = new DataTable(); dtEvents = this.CreateEventsTable(selectedID); // populate event dropdownlist based on selectedId (generated events table) ddlEventRecord.DataSource = dtEvents; ddlEventRecord.DataBind(); if (ddlEventRecord.Items.Count == 0) { return; } else { this.ddlEventRecord.SelectedIndex = 0; // LoadTableData(Convert.ToInt32(ddlEventRecord.SelectedValue)); this.eventCountOutput.Text = ddlEventRecord.Items.Count.ToString(); } foreach (ListItem _listItem in this.ddlEventRecord.Items) { _listItem.Attributes.Add("title", _listItem.Text); } // if in post back //if (IsPostBack) //{ ddlEventRecord.Attributes.Add("onmouseover", "this.title=this.options[this.selectedIndex].title"); LoadTableData(Convert.ToInt32(ddlEventRecord.SelectedValue)); //} } #endregion #region B3 - ddlEventRecord_SelectedIndexChanged /// /// B3 - ddlEventRecord_SelectedIndexChanged - on event record change, calls the LoadTableData function /// /// ////////////////////////////////////////////////////////////////////////////////// protected void ddlEventRecord_SelectedIndexChanged(object sender, EventArgs e) { // Debug: Get the currently selected item in the ListBox. string curItem = ddlEventRecord.SelectedItem.ToString(); // Reset the Event set flag to enable new paging HEventReset.Value = "true"; LoadTableData(Convert.ToInt32(ddlEventRecord.SelectedValue)); } #endregion #region B4 - LoadTableData /// /// B4 - LoadTableData - Binds and prepares the Hierar grid. Re-populates the Meta Data grid /// /// ////////////////////////////////////////////////////////////////////////////////// public void LoadTableData(Int32 SelEventID) { // get/set sort by preference prior to bind // SetSortByPreference("-1"); HGDataBind(SelEventID); // store Selected Event Identity input string HEventRecIdentity.Value = SelEventID.ToString(); HG1.RowExpanded.CollapseAll(); // displays the event details to the user LabelMeta.Text = GetEventDetails(SelEventID); // update the event details data grid EventDetChangeUpdateGrid(SelEventID.ToString()); } #endregion #region B5- rblPassFail_SelectedIndexChanged /// /// B5 - Enable selected range update by calling the LoadTestedRange function /// ///////////////////////////////////////////////////////////////////////////////////// protected void rblPassFail_SelectedIndexChanged(object sender, EventArgs e) { // Debug: Get the currently selected item in the ListBox. string curItem = rblPassFail.SelectedItem.ToString(); LoadPassFailSelection(rblPassFail.SelectedValue); } #endregion #region B6 - LoadPassFailSelection /// /// B6 - Load Pass Fail Selection - Load the pass/fail criteria based on code behind or ddl selection /// ///////////////////////////////////////////////////////////////////////////////////// protected void LoadPassFailSelection(string rblPassFailValue) { // Debug: Get the currently selected item in the ListBox. string curItem = rblPassFail.SelectedItem.ToString(); string curItemVal = rblPassFail.SelectedValue.ToString(); string lPassFailFilterStr = ""; string inputPassFailValue = ""; inputPassFailValue = rblPassFailValue; if (inputPassFailValue != "") { if ((inputPassFailValue == "1") || (inputPassFailValue == "NONE")) { lPassFailFilterStr = "None"; } else if ((inputPassFailValue == "2") || (inputPassFailValue == "PASS")) { lPassFailFilterStr = "Passes Only"; } else if ((inputPassFailValue == "3") || (inputPassFailValue == "FAIL")) { lPassFailFilterStr = "Failures Only"; } else { lPassFailFilterStr = "None"; } } else { lPassFailFilterStr = "None"; rblPassFail.Items[0].Selected = true; } HPassFailFilter.Value = lPassFailFilterStr.ToString(); rblPassFail.DataBind(); // if not first pass if (IsPostBack) { // rebind the hierar grid with changed pass/fail filter status LoadTableData(Convert.ToInt32(HEventRecIdentity.Value)); } } #endregion #region B7- rblSortTable_SelectedIndexChanged /// /// B7 - Enable selected range update by calling the LoadTestedRange function /// ///////////////////////////////////////////////////////////////////////////////////// protected void rblSortTable_SelectedIndexChanged(object sender, EventArgs e) { // Debug: Get the currently selected item in the ListBox. // string curItem = rblSortTable.SelectedItem.ToString(); LoadTableData(Convert.ToInt32(HEventRecIdentity.Value)); } #endregion #region B8 - rblDiagSort_SelectedIndexChanged /// /// B8 - Enable rblDiagSort flag update /// ///////////////////////////////////////////////////////////////////////////////////// protected void rblDiagSort_SelectedIndexChanged(object sender, EventArgs e) { LoadEventDiagSort(rblDiagSort.SelectedValue); } #endregion #region B9 - LoadEventDiagSort /// /// B9 - Load Dialog Sort Option Selection /// ///////////////////////////////////////////////////////////////////////////////////// protected void LoadEventDiagSort(string SelectedValue) { rblDiagSort.ClearSelection(); switch (SelectedValue.ToUpper()) { case "1": rblDiagSort.Items[0].Selected = true; break; case "2": rblDiagSort.Items[1].Selected = true; break; case "3": rblDiagSort.Items[2].Selected = true; break; case "4": rblDiagSort.Items[3].Selected = true; break; case "5": rblDiagSort.Items[4].Selected = true; break; default: rblDiagSort.ClearSelection(); rblDiagSort.Items[0].Selected = true; // "Alphabetical" by default break; } } #endregion #region C1 - HGDataBind /// /// C1 - HGDataBind - Results to Hierarchical Grid /// /// ////////////////////////////////////////////////////////////////////////////////// public void HGDataBind(Int32 eventID) { // holder for returned data DataSet dsTestDetail = new DataSet(); Int32 testsRowCount = 0; DataSet dsResultDetail = new DataSet(); DataSet dsResultDetailCopy = new DataSet(); // clear top panel meta datagrid dgEventDetail.DataSource = null; dgEventDetail.DataBind(); // clear the hierar grid HG1.DataSource = null; HG1.DataBind(); if (eventID >= 0) { try { // register modal dialog if (!ClientScript.IsStartupScriptRegistered("searchloading")) { ClientScript.RegisterStartupScript(typeof(Page), "searchloading", "loadsearch();", true); } // populate datasets for combining in a results DataRelation dsResultDetail = GetResultsDetail(eventID); dsTestDetail = GetTestsDetail(eventID); // check the dataset has tables in it if (dsResultDetail.Tables.Count > 0) { // check the dataset has rows in it if (dsResultDetail.Tables[0].Rows.Count > 0) { testsRowCount = dsTestDetail.Tables["Tests"].Rows.Count; // copy dataset to enable transfer into other dataset dsTestDetail.Tables.Add(dsResultDetail.Tables[0].Copy()); } else { testsRowCount = 0; GlobalFunct.WebMsgBox.Show(" No Data returned for the Selected Event"); return; } } else { GlobalFunct.WebMsgBox.Show(" No Data returned for the Selected Event"); return; } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D1569. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } // create data columns. DataColumn parent_dc = new DataColumn(); DataColumn child_dc = new DataColumn(); try { // select TestID as the common field for data relation parent_dc = dsTestDetail.Tables[0].Columns["TestID"]; child_dc = dsTestDetail.Tables[1].Columns["TestID"]; // create data relation between the results sets DataRelation dr = new DataRelation("LR", parent_dc, child_dc, false); dsTestDetail.Relations.Add(dr); // create dataview int rowCount = dsTestDetail.Tables[1].Rows.Count; // reset the page count for all new sn queries if (GlobalFunct.ConvertToBool(HSerialReset.Value)) { HG1.CurrentPageIndex = 0; HSerialReset.Value = "false"; } if (testsRowCount >= HG1.PageSize) { HG1.AllowPaging = true; HG1.PagerStyle.Visible = true; if (GlobalFunct.ConvertToBool(HEventReset.Value)) { HG1.CurrentPageIndex = 0; } } else { HG1.AllowPaging = false; HG1.PagerStyle.Visible = true; if (GlobalFunct.ConvertToBool(HEventReset.Value)) { HG1.CurrentPageIndex = 0; } } if (rowCount > 0) { HG1.DataSource = dsTestDetail; HG1.DataMember = "Tests"; HG1.DataBind(); } else { HG1.DataSource = dsTestDetail; HG1.DataMember = "Tests"; HG1.DataBind(); return; } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. No data has been found - Please retry the search. Ref:D1645."); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } else { ArrayList ArrList = new ArrayList(); ArrList.Add("No Data Available"); // data not available from the server HG1.DataSource = ArrList; // binds empty Hierar grid HG1.DataBind(); // no event found popup GlobalFunct.WebMsgBox.Show("An error has occurred. Please report the problem to Operations Test Support. Ref:D1669"); return; } } #endregion #region C2 - GetResultsDetail() /// /// C2 - GetResultsDetail() - Query database and return a results (measurement) detail data set /// ///////////////////////////////////////////////////////////////////////////////////// public DataSet GetResultsDetail(Int32 eventID) { // holder for returned data DataSet dsResultDetail = new DataSet(); // flag if data returned Boolean DataAvailable = false; // get the saved state from the hidden page parameter string lDefPassFailFilter = HPassFailFilter.Value; if (eventID >= 0) { // query string string SQLResultDetail; // set up database link conn = GlobalParam.DBConnect(); // assemble query - Results Detail - Measurement Instances SQLResultDetail = "SELECT DISTINCT TestEnum.Name AS [TestName], MeasEnum.TestEnumID, MeasEnum.MeasEnumID, tmpRptEventTestMeas.MeasurementID AS [MeasID],"; SQLResultDetail = SQLResultDetail + " MeasEnum.Name AS [MeasurementName], tmpRptEventTestMeas.LowLimit AS [LowLimit], tmpRptEventTestMeas.MeasurementValue AS [Value],"; SQLResultDetail = SQLResultDetail + " CASE when M.UnitsID = 0 then '' else UE.Abbreviation END AS [Units], UE.FullName AS [UnitsName],"; SQLResultDetail = SQLResultDetail + " tmpRptEventTestMeas.HighLimit AS [HighLimit],tmpRptEventTestMeas.Result AS [intResult], ResultEnum.ResultEnumName AS [Result],"; SQLResultDetail = SQLResultDetail + " TAE.EventEnumID AS [EventEID], TAE.Eventid AS EventID, tmpRptEventTestMeas.TestID AS TestID, '" + rblPassFail.SelectedItem.Text + "' AS [PfVal],"; SQLResultDetail = SQLResultDetail + " CASE WHEN (SELECT count(metavalue) FROM is_metadata MD INNER JOIN is_MetaEnum MetaE ON MetaE.Metaenumid = MD.MetaEnumID WHERE"; SQLResultDetail = SQLResultDetail + " MetaE.MetaEnumName = 'Measurements' AND MD.LocalID = tmpRptEventTestMeas.MeasurementID) > 0 then 1 else 0 END as HasMeasMeta"; SQLResultDetail = SQLResultDetail + " FROM tmpRptEventTestMeas INNER JOIN MeasEnum ON tmpRptEventTestMeas.MeasEnumID = MeasEnum.MeasEnumID"; SQLResultDetail = SQLResultDetail + " INNER JOIN TestEnum ON MeasEnum.TestEnumID = TestEnum.TestEnumID"; SQLResultDetail = SQLResultDetail + " INNER JOIN ResultEnum ON tmpRptEventTestMeas.Result = ResultEnum.ResultEnumID"; SQLResultDetail = SQLResultDetail + " INNER JOIN tmpRptAssetEvent TAE ON TAE.EventID = tmpRptEventTestMeas.EventID "; SQLResultDetail = SQLResultDetail + " INNER JOIN measurements M on M.MeasurementID = tmpRptEventTestMeas.MeasurementID"; SQLResultDetail = SQLResultDetail + " LEFT JOIN UnitsEnum UE ON UE.ID = M.UnitsID "; SQLResultDetail = SQLResultDetail + " WHERE tmpRptEventTestMeas.EventID = " + eventID; if (lDefPassFailFilter == "Passes Only") { SQLResultDetail = SQLResultDetail + " AND (tmpRptEventTestMeas.result = 1)"; } else if (lDefPassFailFilter == "Failures Only") { SQLResultDetail = SQLResultDetail + " AND (tmpRptEventTestMeas.result != 1)"; } if (rblSortTable.SelectedValue == "1") { SQLResultDetail = SQLResultDetail + " ORDER BY MeasEnum.Name "; } else { SQLResultDetail = SQLResultDetail + " ORDER BY MeasID "; } SqlDataAdapter daResultDetail = new SqlDataAdapter(SQLResultDetail, conn); try { conn.Open(); // tables for a Results relation daResultDetail.Fill(dsResultDetail, "ResultsList"); if ((dsResultDetail != null) && (dsResultDetail.Tables.Count > 0)) { DataAvailable = true; } else { DataAvailable = false; } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D1741. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } else { DataAvailable = false; } if (DataAvailable == false) { GlobalFunct.WebMsgBox.Show(" No Data has been found"); } else { } return dsResultDetail; } #endregion #region C3 - GetTestsDetail() /// /// C5 - GetTestsDetail() - Query database and return a results (Tests detail) data set /// ///////////////////////////////////////////////////////////////////////////////////// public DataSet GetTestsDetail(Int32 eventID) { // holder for returned data DataSet dsTestDetail = new DataSet(); DataTable dtTestDetail = new DataTable(); // flag if data returned Boolean DataAvailable = false; if (eventID >= 0) { // set up database link conn = GlobalParam.DBConnect(); // query strings string SQLTestDetail; // get the saved state from the hidden page parameter string lDefPassFailFilter = HPassFailFilter.Value; // assemble query - Test Names SQLTestDetail = "SELECT DISTINCT TestEnum.Name AS [TestName], Tests.TestEnumID, Tests.Result,ResultEnum.ResultEnumName as [strTestResult],"; SQLTestDetail = SQLTestDetail + " Tests.TestID AS TestID ,Tests.EventID AS [eventid], "; SQLTestDetail = SQLTestDetail + " CASE when (select count (metavalue) from is_metadata MD INNER JOIN is_MetaEnum MetaE ON MetaE.Metaenumid = MD.MetaEnumID"; SQLTestDetail = SQLTestDetail + " WHERE MetaE.MetaEnumName = 'Tests' and MD.LocalID = Tests.TestID) > 0 then 1 else 0 end as HasTestMeta "; SQLTestDetail = SQLTestDetail + " FROM Tests INNER JOIN TestEnum ON Tests.TestEnumID = TestEnum.TestEnumID "; SQLTestDetail = SQLTestDetail + " INNER JOIN ResultEnum ON ResultEnum.ResultEnumID = Tests.Result "; SQLTestDetail = SQLTestDetail + " WHERE (Tests.EventID = " + eventID + ")"; if (lDefPassFailFilter == "Passes Only") { SQLTestDetail = SQLTestDetail + " AND (result = 1)"; } else if (lDefPassFailFilter == "Failures Only") { SQLTestDetail = SQLTestDetail + " AND (result != 1)"; } // SQLTestDetail = SQLTestDetail + " ORDER BY [TestName] "; if (rblSortTable.SelectedValue == "1") { SQLTestDetail = SQLTestDetail + " ORDER BY [TestName] "; } else { SQLTestDetail = SQLTestDetail + " ORDER BY [TestID] "; } SqlDataAdapter daTestDetail = new SqlDataAdapter(SQLTestDetail, conn); try { conn.Open(); // tables for a Results relation daTestDetail.Fill(dsTestDetail, "Tests"); if ((dsTestDetail != null) && (dsTestDetail.Tables.Count > 0)) { DataAvailable = true; // Convert DataSet to DataTable dtTestDetail = dsTestDetail.Tables[0]; //HSortTestsExpression.Value = "ASC"; } else { DataAvailable = false; } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D1870. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } else { DataAvailable = false; } return dsTestDetail; } #endregion #region C4 - HG1_TemplateSelection /// /// C2 - HG1_TemplateSelection - Select Hierar Grid Template /// ///////////////////////////////////////////////////////////////////////////////////// private void HG1_TemplateSelection(object sender, HierarGridTemplateSelectionEventArgs e) { e.TemplateFilename = "Templates\\" + e.Row.Table.TableName + ".ascx"; } #endregion #region C5 - HG1_PageIndexChanged /// /// C5 - HG1_PageIndexChanged - On select of TestName ([+] symbol) the underlying measurement table is shown /// /// ////////////////////////////////////////////////////////////////////////////////// private void HG1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) { HEventReset.Value = "false"; HG1.CurrentPageIndex = e.NewPageIndex; HGDataBind(Convert.ToInt32(ddlEventRecord.SelectedValue)); HG1.RowExpanded.CollapseAll(); } #endregion #region C6 - HG1_ItemDataBound /// /// C6 - HG1_ItemDataBound /// /// ////////////////////////////////////////////////////////////////////////////////// private void HG1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { HyperLink hyperLnk = new HyperLink(); if (e.Item.ItemType == ListItemType.Header) { e.Item.Cells[0].Attributes.Add("Class", "icon"); e.Item.Cells[1].Attributes.Add("Class", "tname"); e.Item.Cells[2].Attributes.Add("Class", "tres"); e.Item.Cells[3].Attributes.Add("Class", "tmet lnk"); } if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { System.Data.DataRowView drv = (System.Data.DataRowView)(e.Item.DataItem); int resultOutcome = Int32.Parse(drv.Row["Result"].ToString()); String resultValue = drv.Row["strTestResult"].ToString().ToUpper(); String sessDbType = ConfigurationManager.AppSettings["ThisWebSite"]; hyperLnk = (HyperLink)e.Item.FindControl("HyperLinkMeas"); // Gets the Test Name HyperLink if (drv.Row["HasTestMeta"].ToString() == "0") { hyperLnk.Visible = false; //hyperLnk.ToolTip = ""; } if (sessDbType == "Electronic") { //hyperLnk.NavigateUrl = ""; //hyperLnk.ToolTip = ""; } if (resultOutcome == 1) { // a pass or passed test has been found - no action required } else { if (resultOutcome == 2) { e.Item.Attributes.Remove("Class"); e.Item.Attributes.Add("Class", "failrow"); } else { e.Item.Attributes.Remove("Class"); e.Item.Attributes.Add("Class", "notfoundrow"); } } } } #endregion #region C7 - ClearGridPage /// /// C7 - Clears all dropdown lists and text box controls as required /// when the user enters no serial number on the search /// /// ////////////////////////////////////////////////////////////////////////////////// protected void ClearGridPage() { // clear and reset the serial number list ddlAssetSN.Items.Clear(); this.ddlAssetSN.SelectedIndex = -1; // clear and reset the event items list ddlEventRecord.Items.Clear(); this.ddlEventRecord.SelectedIndex = -1; // reset the None/Pass/Fail list this.rblPassFail.ClearSelection(); this.rblPassFail.Items[0].Selected = true; // reset the label for the event LabelMeta.Text = ""; // reset the label for count eventCountOutput.Text = ""; PartNumLabel.Text = ""; // clear top panel meta datagrid dgEventDetail.DataSource = null; dgEventDetail.DataBind(); // clear the hierar grid HG1.DataSource = null; HG1.DataBind(); } #endregion #region C8 - ExportGrid() /// < summary> /// C8 - Export data from the hierar grid /// ///////////////////////////////////////////////////////////////////////////////////// protected void ExportGrid() { bool bFlag = false; DataSet dsCsv = new DataSet(); try { // generate the dataset using the current eventRecIdentity dsCsv = GetResultsDetail(Convert.ToInt32(HEventRecIdentity.Value)); if ((dsCsv != null) && (dsCsv.Tables[0].Rows.Count > 0)) { /// call the processing code ExportDataSetToExcel(dsCsv, "tabledata"); bFlag = true; } else { GlobalFunct.WebMsgBox.Show(" No data found. Please populate the data grid."); return; } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("An error has occurred. Ref:D2047. Detail:" + ex.Message); } } finally { if (bFlag) Response.End(); } } #endregion #region C9 - ExportDataSetToExcel /// < summary> /// C9 ExportDataSetToExcel /// /// /////////////////////////////////////////////////////////////////////////////////// public static void ExportDataSetToExcel(DataSet ds, string filename) { HttpResponse response = HttpContext.Current.Response; // clean up the response.object response.Clear(); response.Charset = ""; //// create an instance of ExportDataset ExportDataSet objDs = new ExportDataSet(ds); objDs.CreateCsvFromDataSet(); string csvToExport = objDs.CsvToExport; //// get the string to be exported from instance csvToExport = objDs.CsvToExport; if (string.IsNullOrEmpty(csvToExport)) throw new NullReferenceException("Nothing to export"); // set the response mime type for excel // response.ContentType = "application/octet-stream"; // response.ContentType = "text/plain"; response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + DateTime.Now.Millisecond.ToString() + ".csv"); // response.AppendHeader("Cache-Control", "no-cache"); response.AppendHeader("Cache-Control", "private"); //// write the string to output response.Write(csvToExport); response.Flush(); //response.End(); } #endregion #region C10 - mstMCE2Click /// < summary> /// C10 mstMCE2Click - Method for catching of Master Page menu click event /// a delegate event handler to fire menus /// /////////////////////////////////////////////////////////////////////////////////// void mstMCEClick(object sender, EventArgs e) { String selected = Master.SelectedValue; if (selected == "HSave") { } else if (selected == "HGExpo") { ExportGrid(); } else if (selected == "HPrefs") { // fill drop down list with event names names // ~~~ carry out some processing - // register the dialog open script - required in order to use the top page menu ScriptManager.RegisterStartupScript(this, typeof(string), "open", "$('#dialog4').dialog('open');", true); } selected = ""; } #endregion #region C11 - GetAssetIDFromEventID /// < summary> /// C11 GetAssetIDFromEventID - Method to retrieve the Asset Id when supplying event id /// from the URL command line /// /////////////////////////////////////////////////////////////////////////////////// public string GetAssetIDFromEventID(string remoteEID) { string assetId = "0"; if (remoteEID != "") { // query string string SQLEventDetails; // set up database link conn = GlobalParam.DBConnect(); // instantiate a new DataSet dsEventList = new DataSet(); // build query string SQLEventDetails = "Select AssetID from AssetEventJoin where EventID = " + remoteEID; // init SqlDataAdapter with connection and select command daEventList = new SqlDataAdapter(SQLEventDetails, conn); try { conn.Open(); // fill the dataset int numberOfRows = daEventList.Fill(dsEventList, "EventInfo"); if (numberOfRows == 1) { assetId = dsEventList.Tables["EventInfo"].Rows[0]["AssetID"].ToString(); } } catch (Exception ex) { if (GlobalFunct.IsCriticalException(ex)) if (GlobalParam.showXMLerrors) { throw; } else { GlobalFunct.WebMsgBox.Show("A database connection error has occurred. Ref:D2178. Detail:" + ex.Message); } } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } else { // AssetID has not been supplied assetId = ""; } return assetId; } #endregion #region C12 - cbShowEventMain_CheckedChanged /// /// C12 - cbShowEventMain_Checked Changed /// Toggles the display of the Main Event data table above the chart /// /// ////////////////////////////////////////////////////////////////////////////////// protected void cbShowEventMain_CheckedChanged(object sender, EventArgs e) { cbShowEventMainLabel.Text = ""; if (cbShowEventMain.Checked) { cbShowEventMainLabel.Text = "Hide Event Details"; EventDetChangeUpdateGrid(HEventRecIdentity.Value); } else { cbShowEventMainLabel.Text = "Show Event Details"; } cbShowEventMain.DataBind(); } #endregion #region C13 - cbShowEventMeta_CheckedChanged /// /// C13 - cbShowEventMeta_Checked Changed /// Toggles the display of the Event Meta data table - above the chart /// /// ////////////////////////////////////////////////////////////////////////////////// //protected void cbShowEventMeta_CheckedChanged(object sender, EventArgs e) //{ // cbShowEventMetaLabel.Text = ""; // if (cbShowEventMeta.Checked) // { // cbShowEventMetaLabel.Text = "Show Event Meta"; // //HShowSecondaryChart.Value = "TRUE"; // dgEventDetail.Visible = true; // } // else // { // cbShowEventMetaLabel.Text = "Show Event Meta"; // dgEventDetail.Visible = false; // } // // cbShowEventMeta.DataBind(); //} #endregion #region C14 - Page_Error -- Disabled /// < summary> /// C14 - Page_Error -- handle page error on live site -- not currently used /// /////////////////////////////////////////////////////////////////////////////////////// //protected void Page_Error(object sender, EventArgs e) //{ // // Capture the error // Exception ex = Server.GetLastError(); // // Boolean errStatus = GlobalFunct.IsCriticalException(ex); // // if (errStatus) // Server.Transfer("~/ErrorPages/CriticalError.aspx"); // else if (ex is NotImplementedException) // Server.Transfer("~/ErrorPages/NotImplementedException.aspx"); // else // Server.Transfer("~/ErrorPages/AppError.aspx"); // // Clear the error // Server.ClearError(); //} #endregion #region Web Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// /////////////////////////////////////////////////////////////////////////////////////// override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.HG1.TemplateSelection += new DBauer.Web.UI.WebControls.HierarGridTemplateSelectionEventHandler(this.HG1_TemplateSelection); this.HG1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.HG1_PageIndexChanged); this.HG1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.HG1_ItemDataBound); } #endregion } // end of 'Search' class }