Webform1.MyRtnFromServiceParms is inaccessible due to its protection level

pclarke7
pclarke7 used Ask the Experts™
on
I have a WCF Service which is hosted in IIS on my Windows 7 PC and  it has the following data contract defined:

 
  [DataContract]
    public class RtnFromServiceParms
    {
        [DataMember]
        public string passedUserId { get; set; }
        [DataMember]
        public string passedBadgeId { get; set; }
        [DataMember]
        public string passedUserName { get; set; }
        [DataMember]
        public string passedEnv { get; set; }
        [DataMember]
        public string passedSecLvl { get; set; }

        ..
 ..

        public RtnFromServiceParms()
        {
            passedUserId = " ";
            passedBadgeId = " ";
            passedUserName = " ";
            passedEnv = " ";
     passedSecLvl = " ";

        ..
 ..

        }
    }

Open in new window


//
// In the server application MyRtnFromServiceParms is a new instance of RtnFromServiceParms()
//
MyRtnFromServiceParms = new RtnFromServicParms();


From the client application the service is called as follows:

//
// Call to Service      
//
MyRtnFromServiceParms = client.NextTransactionSeq(MyPassToServiceParms);

However in my client WebForm1.aspx I am getting an error "Webform1.MyRtnFromServiceParms is inaccessible due to its protection level"  In WebForm1.aspx.cs references to MyRtnFromServiceParms are not showing any error.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TiosClient.WebForm1" EnableSessionState="True" EnableEventValidation="false" Async="true"%>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<!DOCTYPE html>

<html>
<head runat="server">
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-datepicker.css" rel="stylesheet" />
    <link href="Content/general.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/app/menu/menu.css" rel="stylesheet" />

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
 
    <script type="text/javascript" src="Scripts/app/dymo-printing.js"></script>
    <script type="text/javascript" src="Scripts/app/utils.js"></script>

    <title>TransactionName</title>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-113314448-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-113314448-1');
</script>

</head>
<body>
    
    <div id="modalWIP">
        <img src="images/_generic/wip.gif" />
    </div>

    <link href="<%= GetThemeDirectoryUrl %>/theme.css" rel="stylesheet" />

    <div class="centered">
        <form id="form1" runat="server" defaultbutton="NextBtn" onsubmit="showWorkInProgress(); return true;">
            <div class="header">
                <div class="hidden">
                    <asp:HiddenField ID="loggedOnUserEnterpriseId" runat="server" />
                    <asp:HiddenField ID="loggedOnUserId" runat="server" />
                    <asp:HiddenField ID="mobileOrNonMobile" runat="server" />
             
                 </div>
                <div class="logo">
                    <img runat="server" id="logo" />
                    <asp:TextBox ID="TextBox2" runat="server" style="display: none;" Width="226px">TextBox2 default value</asp:TextBox>
                </div>
                <div class="tios-logo">
                    <img src="images/tios/tios.png" alt="Tios Logo"/>
                </div>

                <div class="gridview-menu">
                    <div class="menu-button">
                        <img src="Scripts/app/menu/menu-icon.png" alt="Tios Logo"/>
                    </div>

                    <ul class="menu-items">
                        <% if (MyRtnFromServiceParms.passedSecLvl == "9") { %>
                        <li>
                            <asp:Button ID="Button1" runat="server" OnClick="Show_Transaction" Text="Transaction" ToolTip="Press to display transaction" Width="144px" />
                        </li>
                        <li>
                            <asp:Button ID="Button2" runat="server" OnClick="Show_Variables" Text="Display Variables " ToolTip="Press to display variables" Width="144px" />
                        </li>
                        <% } %>
                        <li>

Open in new window


<% if (MyRtnFromServiceParms.passedSecLvl == "9") { %> is the line with the protection level error


As you can see RtnFromServiceParms is defined as public and therefore I dont understand why I am getting this message. Oddly I have the same code loaded on a remote server and I am not getting this error which make me think that i is related to settings rather than code. Appreciate any help in identifying the issue.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,

It is probably the control's instance itself that's protected i.e., the variable that is holding the control.

Cheers
ste5anSenior Developer

Commented:
Well, where and how is MyRtnFromServiceParms declared in your code behind?

The error message it self means, that the MyRtnFromServiceParms is visible where you try to invoke it, but either itself or its parent is not accessible. Thus not public.

Author

Commented:
Below is the full webform1.aspx and the code behind file. MtRtnFromServiceParms is defined here. As I mentioned before , I have the exact same code on a remote server which does not display any errors.


WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TiosClient.WebForm1" EnableSessionState="True" EnableEventValidation="false" Async="true"%>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<!DOCTYPE html>

<html>
<head runat="server">
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-datepicker.css" rel="stylesheet" />
    <link href="Content/general.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/app/menu/menu.css" rel="stylesheet" />

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
 
    <script type="text/javascript" src="Scripts/app/dymo-printing.js"></script>
    <script type="text/javascript" src="Scripts/app/utils.js"></script>

    <title>TransactionName</title>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-113314448-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-113314448-1');
</script>

</head>
<body>
    
    <div id="modalWIP">
        <img src="images/_generic/wip.gif" />
    </div>

    <link href="<%= GetThemeDirectoryUrl %>/theme.css" rel="stylesheet" />

    <div class="centered">
        <form id="form1" runat="server" defaultbutton="NextBtn" onsubmit="showWorkInProgress(); return true;">
            <div class="header">
                <div class="hidden">
                    <asp:HiddenField ID="loggedOnUserEnterpriseId" runat="server" />
                    <asp:HiddenField ID="loggedOnUserId" runat="server" />
                    <asp:HiddenField ID="mobileOrNonMobile" runat="server" />
             
                 </div>
                <div class="logo">
                    <img runat="server" id="logo" />
                    <asp:TextBox ID="TextBox2" runat="server" style="display: none;" Width="226px">TextBox2 default value</asp:TextBox>
                </div>
                <div class="tios-logo">
                    <img src="images/tios/tios.png" alt="Tios Logo"/>
                </div>

                <div class="gridview-menu">
                    <div class="menu-button">
                        <img src="Scripts/app/menu/menu-icon.png" alt="Tios Logo"/>
                    </div>

                    <ul class="menu-items">
                        <% if (MyRtnFromServiceParms.passedSecLvl == "9") { %>
                        <li>
                            <asp:Button ID="Button1" runat="server" OnClick="Show_Transaction" Text="Transaction" ToolTip="Press to display transaction" Width="144px" />
                        </li>
                        <li>
                            <asp:Button ID="Button2" runat="server" OnClick="Show_Variables" Text="Display Variables " ToolTip="Press to display variables" Width="144px" />
                        </li>
                        <% } %>
                        <li>
                            <asp:Button ID="btnMobileAppRegistration" runat="server" OnClick="btnMobileAppRegistration_Click" Text="Mobile App" ToolTip="Press to manage your mobile app" Width="144px" />
                        </li>
                        <li id="timeoutCountdown"></li>
                    </ul>
                </div>
                

                <div class="gridview-menu" style="display: none;">

                </div>
                
            </div>
            <div class="hidden2">
               <asp:HiddenField ID="scanPrefix" runat="server" />
               <asp:HiddenField ID="scanSuffix" runat="server" />
               <asp:HiddenField ID="scanSetting" runat="server" />
               <asp:HiddenField ID="scanPfxSfxRequired" runat="server" />
               <asp:HiddenField ID="hiddenScannedValue" runat="server" />
               
            </div>
            <asp:Label ID="Label2" runat="server" Text="Transaction Name"></asp:Label>

            <div id="ContextPanel" runat="server" class="user-info">
                <asp:Label ID="lblTransaction" runat="server" CssClass="transaction"></asp:Label>
                <asp:Label ID="lblUserName" runat="server" CssClass="username"></asp:Label>
                <asp:Label ID="lblEnvironment" runat="server" Text="Label" CssClass="environment"></asp:Label>
                <asp:Label ID="lblTime" runat="server" CssClass="time"></asp:Label>
            </div>

            <div class="gridContainer <%= TextBox1.Visible ? "" : "gridContainer-FullHeight" %>">
                <div class="gridHead"></div>
                <div class="gridBody">
                    <asp:GridView ID="GridView1" runat="server" Width="318px" AllowPaging="False" CellPadding="4" 
                            OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" 
                            ShowFooter="false" ShowHeaderWhenEmpty="True" ForeColor="#333333" OnDataBound="GridView1_SelectedIndexChanged" 
                            GridLines="Both" AutoGenerateColumns="True" HorizontalAlign="Left">
                        <AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField />
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle ForeColor="White" HorizontalAlign="Center" BackColor="#284775" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                        <HeaderStyle HorizontalAlign="Left" />
                    </asp:GridView>
                    <asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
                </div>
            </div>

            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>

            <div class="footer">
                <div class="textarea">
                    <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged1" TextMode="MultiLine"></asp:TextBox>
                    <!--<asp:HiddenField ID="hiddenTextBox" runat="server" /> -->
                </div>
                <div class="prev-next">
                    <asp:Button ID="PrevBtn" CssClass="transaction_btnPrevious" runat="server" OnClick="Button1_Click" Text="Prev" />

                    <div class="footerComboInfo">
                        <asp:Label runat="server" ID="lblComboInfo" Text="Do something with this"> </asp:Label>
                    </div>

                    <div class="transaction_input">
                        <cc1:ComboBox ID="ComboBox1" runat="server" OnClientBlur="OnComboBoxBlur" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged4">
                        </cc1:ComboBox>
                        
                        <% var btnScanBarcode_Action = MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfmtxt") ? "confirm" : "end"; %>
                        <a id="btnScanBarcode" style="display: none;" href="tiosapplication://;scheme=tios;<%= btnScanBarcode_Action %>"  >
                            <img style="height: 42px" src="images/_generic/scan.png"  alt="Tios Logo" />
                        </a>

                        <asp:FileUpload ID="FileUpload1" runat="server"  Visible="False" CssClass="transaction_FileUpload" />
                    </div>

                    <asp:Button ID="NextBtn" CssClass="transaction_btnNext" runat="server" OnClientClick="getScreenHeight()" OnClick="Button2_Click" Text="Next" />
                </div>
            </div>
        </form>
    </div>
 
    <script  type="text/javascript">
        function OnComboBoxBlur(sender, args) {
            alert("Blur");
     args.set_cancel(true);  
 }
        </script>

   <!-- AutoClickNext:  AutoClickNextVal.ToLower().Split(',').Contains(textBoxValue),-->
    <script>
    
        var globals2 = {
            myComboText: ' ',
            autoClickNext: ' '};
        
        Sys.Application.add_load(initializePage);
        function initializePage() {
            $find('<%= ComboBox1.ClientID%>').add_propertyChanged(function (sender, event) {
                if (event.get_propertyName() == 'selectedIndex') {
                    globals2.myComboText = sender.get_textBoxControl().value;
                    $('#TextBox2').val(globals2.myComboText);
                    if(globals.autoClickNextVal !=null && globals2.myComboText !=null && globals2.myComboText !=" "); // && globals.autoClickNext!=true)
              
                    {
                        var arr = globals.autoClickNextVal.toLowerCase().split(',');
                        if (arr.indexOf(globals2.myComboText.toLowerCase()) !== -1) 
                        {
                            globals2.autoClickNext=true;
                            if(globals2.autoClickNext ){
                                setTimeout(function(){
                                    $("#NextBtn").focus().click();
                                }, 300);
                            }
                        }
                    }
                }
            })
        }
     
        var globals = {
            gridviewId: '<%=GridView1.ClientID%>',
            whoAmI: '<%=MySessionLvlValues.whatAmI %>',
            gridviewKeywords: <%= GetJSONGridKeywords %>,
            passedClientKeywords : <%= GetJSONPassedClientKeywords %>,
            innactivityLogoutUrl : '<%= ResolveUrl("~/Account/TimeoutTrigger.ashx") %>',
            inactivityAllowedSeconds : <%=MyRtnFromServiceParms.passedUserInactivityAllowedSeconds > 0 ? MyRtnFromServiceParms.passedUserInactivityAllowedSeconds.ToString() : ConfigurationManager.AppSettings["inactivityAllowedSeconds"] %>,

            autoClickNextVal:  '<%= MyRtnFromServiceParms.passedAtoClkNxtVal.ToString().ToLower().Replace("'","^") %>',  // replace any exist quotes in text
            mobileSessionId: '<%= GetMobileSessionID %>',   // tios mobile session id
                
            showCalendar: <%= MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspcal").ToString().ToLower() %>,  // show calendar
            calendarAutoNext: <%= (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-calnortn")).ToString().ToLower() %>,  // auto click next when date is selected from calendar
            autoClickNext: <%= MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt").ToString().ToLower()  %> }; // auto click next when page loads
        
    </script>

   <script src="<%= ResolveUrl("~/Scripts/json2.js")%>"></script>  
   <script src="<%= ResolveUrl("~/Scripts/jquery-1.10.2.min.js")%>"></script>

   <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
    <!--<script src="/signalr/hubs"></script> -->
    
    <script src="http://80.93.26.243/TiosServiceAlias/signalr/hubs"></script>
    <script src="Scripts/app/app.bundle.js"></script>
    <script src="Scripts/app/bowser.js"></script>
    <script src="Scripts/bootstrap-datepicker.js"></script>
    <script src="Scripts/bootstrap.js"></script>

    <script>
        // show the barcode scanning icon if on a mobile device
        if(bowser.android || bowser.ios) $('#btnScanBarcode').css({ 'display': 'inline-block' });
        if(bowser.android || bowser.ios)
        {$('#mobileOrNonMobile').val("mobile")}; 
        if(!bowser.android & !bowser.ios)
        {$('#mobileOrNonMobile').val("non-Mobile")};
        // Auto click next whenever required (clt-AtoClkNxt)
        if(globals.autoClickNext ){
            setTimeout(function(){
                $("#NextBtn").focus().click();
            }, 300);
      }

        // editor should be a calendar picker when required
        setTimeout(function(){
            //the initialization of the datepicker needs to be delayed otherwise it won't get the correct selected value
            if(globals.showCalendar){
                var $txtDate = $('.transaction_input input[type=text]');
                // remove the focus from the 
                $('.transaction_input input[type=text]').click(function(){
                    $txtDate.datepicker('show');
                });

                $txtDate.datepicker({
                    format: "dd/mm/yyyy"
                })
                .on('changeDate', function(){
                    // when date changes, simulate click next
                    $('.transaction_input input[type=text]').blur();
                    if(globals.calendarAutoNext){
                        setTimeout(function(){
                            // delay needed so that the combobox control can do it's magic
                            // if this is not here, the value sent to the server will be the previously selected, not the current
                            $("#NextBtn").focus().click();
                        }, 100);                
                    }
                });
            }        
        }, 500);

        // auto click next if item selected from combobox
        $('.footer').on('click', '#ComboBox1_ComboBox1_OptionList li', function(){
            alert('test');
        });

        // The following code is catering for changes to the ComboBox1 DropDownList values (client side)
        // The selected value will be written to TextBox2 which will be invisible.

     </script>

 </body>
</html>

Open in new window


Webform1.aspx.cs
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Text;
using System.Drawing;
using System.Data.OleDb;
using Serilog;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Reflection;
using System.Net;
using System.Text.RegularExpressions;
//NEWSTART
using Dymo;
using DYMO;
using DYMO.Label.Framework;

using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Web;
using System.Web.UI.HtmlControls;
//NEWEND


namespace TiosClient
{

    public static class MyGlobals
    {

        public static bool loggerStarted { get; set; }
        public static ILogger logger2 { get; set; }
        public static bool loggingRequired;
    }
    public partial class WebForm1 : System.Web.UI.Page
    {
        // WebForm1 MyWebForm1 = new WebForm1();
        BGWorker MyBGWorker = new BGWorker();
        BGJobParms MyBGJobParms = new BGJobParms();


        public TiosServiceReference1.RtnFromServiceParms MyRtnFromServiceParms; 
        public TiosServiceReference1.SessionLvlValues MySessionLvlValues;
  
        TiosServiceReference1.PassToServiceParms MyPassToServiceParms;
        TiosServiceReference1.TransactionClient client;
        TiosServiceReference1.DisplaySeq MyDisplaySeq = new TiosServiceReference1.DisplaySeq();
        //List<TiosServiceReference1.DisplaySeq> MyDisplaySeqList = new List<TiosServiceReference1.DisplaySeq>();
        TiosServiceReference1.ErrorsEncountered MyErrorsEncountered = new TiosServiceReference1.ErrorsEncountered();
        List<TiosServiceReference1.ErrorsEncountered> MyErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>();
        List<TiosServiceReference1.ErrorsEncountered> MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>();
        List<TiosServiceReference1.DisplaySeq>MyDispSeqList = new List<TiosServiceReference1.DisplaySeq>();
        TiosServiceReference1.RtnFromServiceParms MyVarValuesDict;

        DataTable dt;
        DataRow dtRow;
        DataSet rtnDataSet;
        bool testDropdown = false;
        bool forwardDirection = true;
        bool clientSideError = false;
        bool serverSideError = false;
        bool dispIsAMenu = false;
        bool prevClicked = false;
        bool nextClicked = false;
        bool only1TransLineExists = false;
        int minRowsRqd = 15;
        int cCnt = 0; // column count
        int rCnt = 0; // row count
        int idxCol = 0;
        int kwdCol = 0;
        int gVRowCnt;
        int gVColCnt;
        int tblRowCnt;
        int tblColCnt;
        string comboBoxValue;
        string prevType = " ";
        string prevTran = " ";
        int prevSeq = 0;
        string[] prevSeqArr = new string[200];
        string[] dropDown;   // 1st column
        string[] dropDown2;  // last column (for alternative display to return value)
        string[] delimitedList1;
        string errText = " ";
        string promptText = " ";
        int[] colWidthArray;
        int[] rowHeightArray;
        int[] maxColWidthArray;
        int dftColWidth = 300;
        int dftRowHeight = 40;
        int widestData = 0;
        int rtnDataSetRowCnt = 0;
        int rtnDataSetColCnt = 0;
        string dsTxtString = "";
        OleDbConnection oledbConn;
        private IdentityReference logonName;
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        string logSourceFile = "WebForm1.aspx.cs";
        string logSourceMethod = "";
        string logText = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            string logSourceMethod = "Page_Load";
            //logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
            //WriteLogDetails("Verbose", logText);

            restoreSessionParms();  // restore parameters from previous call
            ComboBox1.Focus();

            //TEMP CHECKS
            if (MyRtnFromServiceParms == null)
            {
                string msg = "";

                if (MyRtnFromServiceParms == null)
                {
                    msg = msg + "MyRtnFromServiceParms is null ";
                }
                if (MyRtnFromServiceParms != null)
                {
                    logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Session Timeout cause: {msg} - " + msg;
                    WriteLogDetails("Information", logText);
                }
                if (msg == "ok")
                {
                    //Response.Redirect("~/Account/Login.aspx", false);
                    Page.Response.Redirect("~/Account/Login.aspx");
                }
            }
            //TEMP CHECKS END

            // If Time out then return to logon page.
            if (MyRtnFromServiceParms == null)
            {
                Response.Redirect("~/Default.aspx", false);
            }
            //
            // Retrieve Enterprise Logo & Enterprise Skin from Service
            // 
            if (MyRtnFromServiceParms != null)
            {
                logo.Src = MyRtnFromServiceParms.passedEnterpriseLogo;          // LOGO
            }

            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;
            if (MySessionLvlValues == null)
            {
                MySessionLvlValues = new TiosServiceReference1.SessionLvlValues();
            }

            //lblEnvironment.Text = "<span>[ Trans: " + MyRtnFromServiceParms.passedCurrentTransId + " /"+ MyRtnFromServiceParms.passedCurSeq + "  ]</span><span>         "+ MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " </span> <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span><span>00/00/00 00:00</span>";
            lblEnvironment.Text = MyRtnFromServiceParms.passedEnvDesc;
            lblEnvironment.Style.Add(HtmlTextWriterStyle.BackgroundColor, MyRtnFromServiceParms.passedEnvColour);
            lblTransaction.Text = String.Format("[ Trans: {0}/{1} ]", MyRtnFromServiceParms.passedCurrentTransId, MyRtnFromServiceParms.passedCurSeq);
            lblUserName.Text = MyRtnFromServiceParms.passedUserName;
            lblTime.Text = "00/00/00 00:00";

            //If Keywords such as *LIST, *RANGE etc.. selected from dropdown list
            //Then automatically click NEXT rather than display and ask user to click NEXT
            //if (MyRtnFromServiceParms != null && !MyRtnFromServiceParms.passedUserName.ToLower().Contains("pat clarke"))
            //{
            //    TextBox2.Visible=false;
            //}

                if (hiddenTextBox.Value.Contains("*"))
            {

                Button2_Click(null, new EventArgs());  // Click Next
            }

            if (!IsPostBack)
            {
                // First time through initialize previous sequence array
                //
                prevSeqArr = new string[200];
                int i = 0;
                for (i = 0; i < 200; i++) // Loop through array
                {
                    prevSeqArr[i] = " ";
                }

                // Initialize seq to zero when returning from main menu
                MyPassToServiceParms.passedCurSeq = 0;
                MyRtnFromServiceParms.passedCurSeq = 0;

                // Return parameters from last call to service
                MyPassToServiceParms.passedUserId = MyRtnFromServiceParms.passedUserId;
                MyPassToServiceParms.passedEnterpriseId = MyRtnFromServiceParms.passedEnterpriseId;
                MyPassToServiceParms.passedCurrentTransId = MyRtnFromServiceParms.passedCurrentTransId;

                //
                // Create Enterprise directory if not existing
                //
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedEnterpriseId))
                {
                    string uploadPath1 = MapPath("~/" + MyRtnFromServiceParms.passedEnterpriseId);
                    if (!Directory.Exists(uploadPath1))
                    {
                        Directory.CreateDirectory(uploadPath1);
                        DirectorySecurity sec = Directory.GetAccessControl(uploadPath1);
                        // Using this instead of the "Everyone" string means we work on non-English systems.
                        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        Directory.SetAccessControl(uploadPath1, sec);

                    }
                }

                if (MyRtnFromServiceParms.passedCurSeq == 0)
                {
                    MyPassToServiceParms.passedCurSeq = 0;
                }
                else
                    MyPassToServiceParms.passedCurSeq = MyRtnFromServiceParms.passedCurSeq;

         //       HtmlAnchor MyAnchor =this.FindControl('btnScanBarcode');
         //       if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfm"))
         //       {
         //           MyAnchor.HRef = "tiosapplication://;scheme=tios;end";
         //       }
         //       else
         //           MyAnchor.HRef = "tiosapplication://;scheme=tios;confirm";

                widestData = 0;
                processTransaction();  // Load initial transaction
            }

        }



        public void callService()
        {
            string logSourceMethod = "callService()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "CALLING SERVICE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }

                // If Previous key selected
                if (forwardDirection == false)
                {
                    MyPassToServiceParms.passedCurrentTransId = prevTran;
                }

                MyPassToServiceParms.passedForwardDirection = forwardDirection;   //indicates to Servers where NEXT or PREVIOUS buttons pressed
                MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();      // pass input value to the service for processing

                //-----------------------------------------------------------------------------------------------------------------
                // Check if value in ComboBox is from DropdownList and whether it need to be swapped with value from another column
                //-----------------------------------------------------------------------------------------------------------------
                //
                //
                // if more than one column passed in the drop down list then set the selected value to
                // to the value passed in the last column of the dropdown list
                // (eg.  Sales team, 01
                //       Manufacturing team, 02
                //       Finance team, 03
                //
                // If "Sales team" displayed and selected in dropdown then '01' will be returned to the input field
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-sndmsg"))
                {
                    //DateTime curDateTime = DateTime.Now;
                    //var svc = new TiosServiceReference1.TransactionClient();
                    //svc.AnnounceAll("Hello World on " + curDateTime.ToString());

                    // Pat's Note
                    // This was used for testing only - no longer relevant. The message will come from TiosService method ScannedTransactions2 in TransactionService.cs 
                    //
                    //string broadcastMessageFromService="THis should be overridden by broadcastMessage from service";
                    //var hub = new TiosHub();
                    //hub.AnnounceAll(broadcastMessageFromService);
                }

                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst") && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtnlstcol"))
                {
                    int resultIndex = -1;
                    if (dropDown != null)
                    {
                        resultIndex = Array.IndexOf(dropDown, ComboBox1.SelectedValue.Trim());
                    }
                    if (resultIndex != -1)
                    {
                        if (dropDown2 != null)
                        {
                            MyPassToServiceParms.passedInpVal = dropDown2[resultIndex];
                        }

                    }

                }

                //
                //-----------------------------------------------------------------------------------------------------------------
                //

                string Username1 = User.Identity.Name;
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ABOUT TO CALL SERVICE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }

                //
                // Prior to Call to Service delete MyDispSeq2.txt if existing      
                //
                string myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                if (File.Exists(myPath))
                {
                    try {
                        File.Delete(myPath);
                    }
                    catch (Exception ex) { }
                }
                //
                // Call to Service      
                //
                MyRtnFromServiceParms = client.NextTransactionSeq(MyPassToServiceParms);
                MyPassToServiceParms.passedDs3XmlString = " "; // Clear any previous XML string sent to service
                //
                // Return from service
                //
                MyPassToServiceParms.passedUserId = MyRtnFromServiceParms.passedUserId;
                // 
                // Display FileUpload Control on Client
                //
                //if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // Switch on display of file upload control
                //{
                //    MySessionLvlValues.dspFileUploadCtl = true;
                //}

                // If client keyword clt-logout specified then do so now.
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-logout"))
                {
                     Response.Redirect("~/Default.aspx", true);
                }


                if (MyRtnFromServiceParms != null)
                {
                    logText = "BACK IN THE CLIENT - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }
                // Set the transaction and enterprise Id for next call to service
                MyPassToServiceParms.passedEnterpriseId = MyRtnFromServiceParms.passedEnterpriseId;
                MyPassToServiceParms.passedCurrentTransId = MyRtnFromServiceParms.passedCurrentTransId;
                loggedOnUserEnterpriseId.Value = MyRtnFromServiceParms.passedEnterpriseId; // Used to verify scan
                loggedOnUserId.Value = MyRtnFromServiceParms.passedUserId; // used to verify scan
                scanPrefix.Value = MyRtnFromServiceParms.passedBarcodePrefix.Trim();
                scanSuffix.Value = MyRtnFromServiceParms.passedBarcodeSuffix.Trim();
                scanSetting.Value = MyRtnFromServiceParms.passedBarcodeSetting;
                scanPfxSfxRequired.Value = MyRtnFromServiceParms.passedScanPfxSfxRequired.ToLower();

                //
                // Read the display from file wwwroot/EnterpriseId/UserId_MyDispSeq into list MyDispSeqList
                //

                // First clear the returned List
 
                    MyDispSeqList.Clear();
                    string myFilename = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq.txt";
                    dsTxtString = "";
                    try
                    {

                        string line;
                        int counter = 0;

                        using (StreamReader sr = new StreamReader(File.Open(myFilename, FileMode.Open, FileAccess.Read, FileShare.Read)))
                        {
                            while ((line = sr.ReadLine()) != null)
                            {
                                TiosServiceReference1.DisplaySeq MyDisplaySeq = new TiosServiceReference1.DisplaySeq(); // Declare new instance for each line

                                string Value = line;
                                delimitedList1 = RtnDelimitedValues(line);

                                MyDisplaySeq.type = delimitedList1[0];
                                MyDisplaySeq.enterpriseId = delimitedList1[1];
                                MyDisplaySeq.transId = delimitedList1[2];
                                MyDisplaySeq.transToCall = delimitedList1[3];
                                int intVal = 0;
                                bool result = int.TryParse(delimitedList1[4].ToString(), out intVal);
                                MyDisplaySeq.transIdx = intVal;
                                intVal = 0;
                                result = int.TryParse(delimitedList1[5].ToString(), out intVal);
                                MyDisplaySeq.seqNo = intVal;
                                MyDisplaySeq.dispTxt1 = delimitedList1[6];
                                MyDisplaySeq.dispTxt2 = delimitedList1[7];
                                MyDisplaySeq.dispTxt3 = delimitedList1[8];
                                MyDisplaySeq.dispFldName = delimitedList1[9];
                                MyDisplaySeq.dispKeyWord = delimitedList1[10];
                                MyDisplaySeq.dispIdx = delimitedList1[11];
                                intVal = 0;
                                result = int.TryParse(delimitedList1[12].ToString(), out intVal);
                                MyDisplaySeq.secLvl = intVal;

                                // Restore  any  special characters back to commas
                                MyDisplaySeq.dispTxt1 = MyDisplaySeq.dispTxt1.Replace("$~", ",");
                                MyDisplaySeq.dispTxt2 = MyDisplaySeq.dispTxt2.Replace("$~", ",");
                                MyDisplaySeq.dispTxt3 = MyDisplaySeq.dispTxt3.Replace("$~", ",");
                                MyDisplaySeq.dispFldName = MyDisplaySeq.dispFldName.Replace("$~", ",");
                                MyDisplaySeq.dispKeyWord = MyDisplaySeq.dispKeyWord.Replace("$~", ",");
                                MyDisplaySeq.dispIdx = MyDisplaySeq.dispIdx.Replace("$~", ",");

                                MyDispSeqList.Add(MyDisplaySeq);
                                counter++;
                            }
                            // Copy back to list it was originally being passed to service in.
                            MyRtnFromServiceParms.MyDispSeqList = MyDispSeqList.ToArray();

                        }
                    }
                    catch (Exception ex)
                    {
                        logText = "Error Reading _MyDispSeq file - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords + "error: " + ex.ToString();
                        WriteLogDetails("Error", logText);
                    }

                //
                // Here we have just returned from the service after encountering an Input statement. Below we will process the input and then return to the Service at the statement 
                // after the input. However if when back in the Service we detect an error then we will return to process the prior input statement whilst displaying the error message
                // encountered. To facilitate this we must save the previously encountered error message. This is what we are doing below.

 
                MyErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                // Save errors encountered after last input as they will need to be re-displayed when we go back to previous input

                MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                if (MyRtnFromServiceParms.MyErrorsEncounteredList.Count() > 0)
                {
                    MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                }
                else
                {
                    if (MyPrevErrorsEncounteredList != null);
                    {
                        if (MyPrevErrorsEncounteredList.Count() > 0)
                        {
                            for (int cnt = 0; cnt < MyPrevErrorsEncounteredList.Count(); cnt++) // Loop through List with for loop
                            {
                                MyErrorsEncountered = MyPrevErrorsEncounteredList[cnt];
                                MyErrorsEncounteredList.Add(MyErrorsEncountered);
                            }
                            MyPrevErrorsEncounteredList.Clear();  // Clear Prev errors to prevent looping
                        }
                    }
                }

                // Set some of our session parameters based on returned values from Service
                //

                // Errors exist
                if (MyErrorsEncounteredList.Count() > 0)
                {
                    MySessionLvlValues.errorExists = true;
                }
                // Prompt exists
                if (MyRtnFromServiceParms.passedPromptDescription != "" && MyRtnFromServiceParms.passedPromptDescription != " ")
                {
                    MySessionLvlValues.promptExists = true;
                }
                // Display is empty 
                //if (MyRtnFromServiceParms.MyDispSeqList != null && MyRtnFromServiceParms.MyDispSeqList.Count() == 0)
                if (MyRtnFromServiceParms.MyDispSeqList != null && MyRtnFromServiceParms.MyDispSeqList.Count() == 0)
                {
                    MySessionLvlValues.dispIsEmpty = true;
                }
 

                // Display FileUpload Control on Client
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // Switch on display of file upload control
                {
                    MySessionLvlValues.dspFileUploadCtl = true;
                }
                // Hide FileUpload Control on Client
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-hidfilupl")) // Switch off display of file upload control
                {
                    MySessionLvlValues.dspFileUploadCtl = false;
                }

                FileUpload1.Visible = false;
                ComboBox1.Visible = true;
                if (MySessionLvlValues.dspFileUploadCtl == true)
                {
                    FileUpload fileUpload1 = new FileUpload();
                    FileUpload1.Visible = true;
                }
                else if (MySessionLvlValues.dspFileUploadCtl == false)
                {
                    FileUpload1.Dispose();
                    ComboBox1.Visible = true;
                }


                // Restore Gridview Column Widths and Row Heights on change of transaction 
                if (MyRtnFromServiceParms.passedCurrentTransId != MySessionLvlValues.thisTransName)
                {
                    MySessionLvlValues.thisTransName = MyRtnFromServiceParms.passedCurrentTransId;
                    MySessionLvlValues.GVColRowOveridesExistForTrans = false;
                }
                // Dont allow current sequence to go below Zero
                if (MyRtnFromServiceParms.passedCurSeq <= 0)
                {
                    MyPassToServiceParms.passedCurSeq = 0;
                }
                else
                    MyPassToServiceParms.passedCurSeq = MyRtnFromServiceParms.passedCurSeq;

                Label2.Text = MyRtnFromServiceParms.passedCurrentTransId + " : " + MyRtnFromServiceParms.passedCurSeq;
                //
                // =====================================================
                // returned dataset 2 (Dropdown values or Display List)
                // Dataset2 can contain either dropdown values or a display list
                // =====================================================
                //
                rtnDataSetRowCnt = 0;
                rtnDataSetColCnt = 0;
                MySessionLvlValues.displayList = false;
                MySessionLvlValues.prtDymoLabelViaApi = false;

                // If MyDisySeq2 exists then copy file details to DS
                myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                if (File.Exists(myPath))
                {
                    rtnDataSet = new DataSet();
                    //rtnDataSet = (DataSet)Deserialize(MyRtnFromServiceParms.passedDs2XmlString, typeof(DataSet));
                    rtnDataSet = CopyFileToDS(myPath);
                    rtnDataSetRowCnt = rtnDataSet.Tables[0].Rows.Count;
                    rtnDataSetColCnt = rtnDataSet.Tables[0].Columns.Count;

                    // TODO: ContainsClientKeyword was removed from the service?
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dsplst") && rtnDataSetRowCnt > 0)
                    {
                        MySessionLvlValues.displayList = true;
                    }

                }

                // If dropdown list is populated and clt-drpdwnlst specified then set dropDownValuesExist=true
                MySessionLvlValues.dropDownValuesExist = false;

                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst"))
                {
                    MySessionLvlValues.dropDownValuesExist = true;
                }

                // If users security level >=9 then allow user to view transaction variables
                MySessionLvlValues.dispVarRqd = false;
                if (MyRtnFromServiceParms.passedSecLvl == "9")
                {
                    MySessionLvlValues.dispVarRqd = true;
                }


                //=======================================================================
                // Determine what type of display I am (a Menu, a Transaction, a List )
                //=======================================================================

                dispIsAMenu = false;
                MySessionLvlValues.whatAmI = " ";
                if (MyRtnFromServiceParms.MyDispSeqList.Count() > 0)
                {
                    MyDisplaySeq = MyRtnFromServiceParms.MyDispSeqList[0];
                }
                if (MyRtnFromServiceParms.MyDispSeqList.Count() > 0 && MyDisplaySeq.type.ToLower() == "m")
                {
                    dispIsAMenu = true;
                    MySessionLvlValues.whatAmI = "Menu";
                    FileUpload1.Visible = false;
                }
                else
                    MySessionLvlValues.whatAmI = "Transaction";

                if (MySessionLvlValues.displayList == true)
                {
                    MySessionLvlValues.whatAmI = "List";
                }
                if (MySessionLvlValues.displayVariables == true)
                {
                    MySessionLvlValues.whatAmI = "Variables";
                }


                ComboBox1.ClearSelection();
                ComboBox1.Dispose(); // required to clear previous values
                ComboBox1.Items.Clear();
                ComboBox1.Text = " ";
                string defaultValue = MyRtnFromServiceParms.passedInpFldVal;

                if (String.IsNullOrEmpty(defaultValue) && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspcal"))
                {
                    defaultValue = DateTime.Today.ToString("dd/MM/yyyy");
                    ComboBox1.Items.Add(defaultValue);
                    ComboBox1.SelectedIndex = 0;
                }

                // If dropdown list is populated
                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst"))
                {
                    dropDown = new string[rtnDataSet.Tables[0].Rows.Count + 1];
                    dropDown2 = new string[rtnDataSet.Tables[0].Rows.Count + 1];
                    int idx = 0;
                    foreach (DataTable table in rtnDataSet.Tables)
                        foreach (DataRow row in table.Rows)
                        {
                            string ComboValue = row.ItemArray[0].ToString().Trim();
                            string ComboValue2 = row.ItemArray[rtnDataSetColCnt - 1].ToString().Trim();
                            dropDown[idx] = ComboValue;
                            dropDown2[idx] = ComboValue2;


                            ComboBox1.Items.Add(ComboValue);
                            if (idx == 0) //|| ComboValue == MyRtnFromServiceParms.passedUserCompanyName)
                            {
                                ComboBox1.SelectedIndex = idx;
                            }


                            // If a default value was passed in via FieldValue then set to this value if encountered.
                            if (defaultValue == ComboValue)
                            {
                                ComboBox1.SelectedIndex = idx;
                                defaultValue = " ";
                            }

                            idx = idx + 1;
                        }

                    // If default value was passed but it does not exist in the ComboBox Value then set it into values
                    if (defaultValue != "" && defaultValue != " " && defaultValue != null)
                    {
                        string ComboValue = defaultValue.Trim();
                        dropDown[idx] = ComboValue;
                        //string dsUserId = row.ItemArray[1].ToString();
                        ComboBox1.Items.Add(ComboValue);
                        ComboBox1.SelectedIndex = idx;
                    }
                }

                // If in a Transaction and ComboBox does not have a selected value then check if  a scanned transaction exists for this user 
                if (MyRtnFromServiceParms.passedCurrentTransType == "t" && ComboBox1.SelectedIndex == -1)
                {
                    //
                    // CANNOT DO THIS HERE AS PAGE HAS NOT LOADED AT THIS TIME
                    // looking at using SIGNALR as an alternative.  BGWorker wil still be useful for other jobs and so will retain logic
                    //
                    //CheckforSacnnedTransactions will run in background and populate any scanned value to ComboBox if ComboBox is empty 
                    //CheckForScannedTransactions();

                }


                //NEWSTART/////////////////////////////
                // If dropdown list is populated with a file sent from the servicee (not for dropdown list)
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-filfrmsrv") && MyPrevErrorsEncounteredList.Count() == 0)
                {

                    bool displayFile = false;
                    if (MyRtnFromServiceParms.passedToFileAction.ToLower() == "open")
                    {
                        displayFile = true;
                    }
                    string filename = MyRtnFromServiceParms.passedFromFileName;
                    string download_folder = MyRtnFromServiceParms.passedFromFileLoc;
                    string fileType = MyRtnFromServiceParms.passedFromFileType;
                    string path1 = String.Format("~/{0}/{1}/{2}", download_folder, MyRtnFromServiceParms.passedEnterpriseId, filename);
                    string path1url = ResolveUrl(path1);
                    //Check for existance 
                    //if (!File.Exists(path1))
                    //{
                    //    return;
                    //}
                    try
                    {
                        if (!displayFile)
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "myId5", string.Format("downloadFile('{0}');", path1url), true); // Closed
                        }
                        else
                        {
                            // browsers are able to open xml files with no issues
                            // to be sure that this works everywhere, the easiest way is to simply clone the file changing its file extension
                            string physicalPath = MapPath(path1url);
                            string physicalPathXml = physicalPath + ".xml";
                            File.Copy(physicalPath, physicalPathXml, true);
                            string path1urlxml = ResolveUrl(String.Format("~/{0}/{1}/{2}", download_folder, MyRtnFromServiceParms.passedEnterpriseId, new FileInfo(physicalPathXml).Name));
                            //ClientScript.RegisterStartupScript(this.GetType(), "myId6", string.Format("displayFile('{0}');", path1urlxml), true);      // Open 
                            ClientScript.RegisterStartupScript(this.GetType(), "myId6", string.Format("displayFile('{0}');", path1url), true);      // Open 

                        }
                    }
                    catch (Exception ex)
                    {
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Error:" + ex;
                            WriteLogDetails("Error", logText);
                        }

                    }
                }


                // If client keyword clt-RedFilToDs specified and file specified in MyRtnFromServiceParms.passedToFileName then read this file into Data Structure

                dsTxtString = "";
                MySessionLvlValues.prtDymoLabelViaApi = false;
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-redfiltods") && MyPrevErrorsEncounteredList.Count() == 0 && (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedToFileName)))
                {

                    string filename = MyRtnFromServiceParms.passedToFileName;
                    dsTxtString = "";
                    try
                    {
                        // 
                        // read special text file
                        // 
                        DataTable dt = new DataTable();
                        DataSet ds = new DataSet();
                        dt.Columns.Add("detail", typeof(String));
                        string line;
                        int counter = 0;

                        System.IO.StreamReader file = new System.IO.StreamReader(File.Open(MyRtnFromServiceParms.passedToFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));

                        while ((line = file.ReadLine()) != null)
                        {
                            string Value = line;
                            dsTxtString = dsTxtString + line;
                            MySessionLvlValues.prtDymoLabelViaApi = true;
                            dt.Rows.Add(Value);
                            counter++;
                        }

                        ds.Tables.Add(dt);
                    }
                    catch (Exception ex)
                    {
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                            WriteLogDetails("Error", logText);

                        }
                    }
                }

                //
                // If keyword contains clt-prtviaapi then call Dymo print API from javascript function to do so.
                // Because Javascript run on the browser it will have access to local label printer
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-prtviaapi") && MySessionLvlValues.prtDymoLabelViaApi == true && dsTxtString != "") // non blank entry required
                {
                    if (forwardDirection == true)
                    {
                        try
                        {
                            //ClientScript.RegisterStartupScript(GetType(), "myId992", "printDymoLabel();", true);
                            // ClientScript.RegisterStartupScript(GetType(), "myId992", string.Format("dymoframeworkInit('{0}');", dsTxtString), true);
                            ClientScript.RegisterStartupScript(GetType(), "myId992", string.Format("printDymoLabel2('{0}');", dsTxtString), true);
                        }

                        catch (Exception ex)
                        {
                            if (MyRtnFromServiceParms != null)
                            {
                                logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                                WriteLogDetails("Error", logText);
                            }
                        }
                    }
                }

                //NEWEND///////////////////////////////

                //
                // If list is to be displayed for selection rather than a standard Input
                //

                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dsplst"))
                {

                    int idx = 0;
                    foreach (DataTable table in rtnDataSet.Tables)
                        foreach (DataRow row in table.Rows)
                        {
                            // come back to this. At moment going to copy trnDataSet to dt
                            idx = idx + 1;
                        }
                }


                saveSessionParms();  // save Session parameters from this call

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        public String GetThemeDirectoryUrl
        {
            get
            {
                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedEnterpriseSkin))
                    return "Themes/" + MyRtnFromServiceParms.passedEnterpriseSkin;
                else
                    return "Themes/default";
            }
        }

        /// <summary>
        /// Get the display keywords in JSON format
        /// </summary>
        public String GetJSONGridKeywords
        {

            get
            {
                List<dynamic> rows = new List<dynamic>();

                /*
                When you are displaying a List you should ignore any keywords in MyDispSeqList (even though it may have values and keywords).
                This is because the list being displayed is not built from MyDispSeqList.
                */
                if (MySessionLvlValues.whatAmI != "List")
                {
                    foreach (var row in MyRtnFromServiceParms.MyDispSeqList)
                    {
                        rows.Add(new { keyword = row.dispKeyWord, field = row.dispIdx });
                    }
                }

                JavaScriptSerializer json = new JavaScriptSerializer();

                return json.Serialize(rows);
            }
        }

        public String GetJSONPassedClientKeywords
        {
            get
            {
                List<String> rows = new List<String>();

                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedClientKeywords))
                    rows = MyRtnFromServiceParms.passedClientKeywords.Replace(" ", "").Split(',').ToList();

                JavaScriptSerializer json = new JavaScriptSerializer();

                return json.Serialize(rows);
            }
        }



        public void processTransaction()
        {
            string logSourceMethod = "processTransaction()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            //Update previous transactions
            UpdatePreviousTransactions();

            // Update selected option to Passed Input Value
            MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();


            callService();  // call the Service 

            //if (MyRtnFromServiceParms.MyErrorsEncounteredList.Count()>0)
            only1TransLineExists = false;

            if (MyErrorsEncounteredList.Count() > 0)
            {
                serverSideError = true;
                retrieveErrors();  // retrieve returned errors

            }
            else
                if (clientSideError == false && serverSideError == false)
            {
                TextBox1.Visible = false;
            }

            if (TextBox1.Visible == false)
            {
                retrievePromptMsgs(); // retrieve prompt message if no error message
            }

            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;

            if (MySessionLvlValues != null)
            {
                //Label3.Text = MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " - <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span>";
                //Label3.Text = "[ Trans: " + MyRtnFromServiceParms.passedCurrentTransId + " /" + MyRtnFromServiceParms.passedCurSeq + "  ]         " + MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " - <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span>";

                lblEnvironment.Text = MyRtnFromServiceParms.passedEnvDesc;
                ContextPanel.Style.Add(HtmlTextWriterStyle.BackgroundColor, MyRtnFromServiceParms.passedEnvColour);
                lblTransaction.Text = String.Format("[ Trans: {0}/{1} ]", MyRtnFromServiceParms.passedCurrentTransId, MyRtnFromServiceParms.passedCurSeq);
                lblUserName.Text = MyRtnFromServiceParms.passedUserName;
                lblTime.Text = "00/00/00 00:00";
            }
            if (MyRtnFromServiceParms.passedInpFldVal != "" && MyRtnFromServiceParms.passedInpFldVal != null)
            {
                // Re-instate this by adding passed field to comboBox
                //ComboBox1.SelectedValue = MyRtnFromServiceParms.passedInpFldVal;
            }
            processRtnDisp();  // Process the display sequence returned from Service


            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            if (MySessionLvlValues.whatAmI != "List")
            {
                dt.Columns.Remove("Idx");
                dt.Columns.Remove("Keyword");
            }

            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            //SetColWidthRowHeight();
            GridView1.DataBind();



        }

        public void processRtnDisp()
        {
            string logSourceMethod = "processRtnDisp()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                //Convert the returned Display seq into a table which can be bounded to GridView1
                //The display may be alternated via the whatAmI MySessionLvlValue variable 

                dt = new DataTable("Flex DataTable");
                dtRow = dt.NewRow();
                rmvDspRecords();   // remove the display records which have a lower instance than Current instance
                setDspHeadings();  // retrieve the headings for this display


                // For Menus & transactions Read through Display sequence list and output the rows

                cCnt = 0;
                if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "Transaction")
                {
                    for (int cnt = 0; cnt < MyRtnFromServiceParms.MyDispSeqList.Count(); cnt++) // Loop through Display Seq List with for loop
                    {
                        MyDisplaySeq = MyRtnFromServiceParms.MyDispSeqList[cnt];

                        // 1st Column = dispTxt1
                        dtRow[cCnt] = MyDisplaySeq.dispTxt1;
                        cCnt = cCnt + 1;
                        //
                        // * * * T E M P  D I S P L A Y * * *
                        //

                        // 2nd Column = dispTxt2 if processing a menu 
                        if (MyDisplaySeq.type.ToLower() == "m") // Menu
                        {
                            dtRow[cCnt] = " ";
                            if (MyDisplaySeq.dispTxt2 != null)
                            {
                                dtRow[cCnt] = MyDisplaySeq.dispTxt2;
                            }
                            cCnt = cCnt + 1;
                        }
                        else
                        // 2nd Column = dispFldName if processing a transaction 
                        {
                            dtRow[cCnt] = " ";
                            if (MyDisplaySeq.dispFldName != null)
                            {
                                dtRow[cCnt] = MyDisplaySeq.dispFldName;
                            }
                            cCnt = cCnt + 1;
                        }

                        // 3rd Column = dispIdx (Non display Column)                             
                        dtRow[cCnt] = " ";
                        if (MyDisplaySeq.dispIdx != null && MyDisplaySeq.dispIdx != "" && MyDisplaySeq.dispIdx != " ")
                        {
                            dtRow[cCnt] = MyDisplaySeq.dispIdx;
                        }
                        cCnt = cCnt + 1;

                        // 4th Column = dispKeyWord (Non display Column)    
                        dtRow[cCnt] = " ";
                        if (MyDisplaySeq.dispKeyWord != null && MyDisplaySeq.dispKeyWord != "" && MyDisplaySeq.dispKeyWord != " ")
                        {
                            dtRow[cCnt] = MyDisplaySeq.dispKeyWord;
                        }
                        cCnt = cCnt + 1;

                        // Add this row
                        dt.Rows.Add(dtRow);
                        cCnt = 0;           // Reset column count
                        rCnt = rCnt + 1;    // Increment row count
                        dtRow = dt.NewRow();

                    }
                }

                //
                // for Lists take the Gridview content from the returned dataset
                //

                if (MySessionLvlValues.whatAmI == "List")
                {
                    string myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                        rtnDataSet = CopyFileToDS(myPath);
                        rtnDataSetRowCnt = rtnDataSet.Tables[0].Rows.Count;
                        dt = rtnDataSet.Tables[0];
                }




                //
                // Display Transaction Variable values 
                //
                if (MySessionLvlValues.whatAmI == "Variables")
                {

                    // Acquire keys and sort them.
                    var sortedList = MyRtnFromServiceParms.MyVarValuesDict.Keys.ToList();
                    sortedList.Sort();

                    for (int cnt = 0; cnt < sortedList.Count(); cnt++) // Loop through Variable values Dictionary with for loop
                    {
                        var itemKey = sortedList.ElementAt(cnt);
                        var itemValue = " ";
                        if (MyRtnFromServiceParms.MyVarValuesDict.ContainsKey(itemKey))
                        {
                            itemValue = MyRtnFromServiceParms.MyVarValuesDict[itemKey];
                        }
                        // 1st Column = dictionary key
                        dtRow[cCnt] = itemKey;
                        cCnt = cCnt + 1;


                        // 2nd Column = dictionary Value
                        dtRow[cCnt] = itemValue;
                        cCnt = cCnt + 1;

                        // Add this row
                        dt.Rows.Add(dtRow);
                        cCnt = 0;           // Reset column count
                        rCnt = rCnt + 1;    // Increment row count
                        dtRow = dt.NewRow();
                    }
                }


                // Fill remainder of gridview with blanks of record < mininum required
                //for (int cnt = rCnt; cnt < minRowsRqd; cnt++) // Loop through Display Seq List with for loop
                //{
                //    dtRow[0] = " ";
                //    dtRow[1] = " ";
                //    dtRow[2] = " ";
                //    dtRow[3] = " ";
                //    dt.Rows.Add(dtRow);
                //    dtRow = dt.NewRow();
                //}

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        //
        // Set the display Headings for the Gridview
        //
        public void setDspHeadings()
        {
            string logSourceMethod = "setDspHeadings()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                //
                // if no heading records check if this is a menu (type="m")
                //

                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    //dt.Columns.Add("Opt");
                    dt.Columns.Add("Option");
                    dt.Columns.Add("Description");
                }
                else

                    if (MySessionLvlValues.whatAmI == "Transaction")
                {
                    dt.Columns.Add(MyRtnFromServiceParms.passedCurrentTransDesc);
                    dt.Columns.Add("Col2");
                }

                else
                        if (MySessionLvlValues.whatAmI == "Variables")
                {
                    dt.Columns.Add("Variable");
                    dt.Columns.Add("Current Value");

                }

                if (MySessionLvlValues.whatAmI != "List")
                {
                    dt.Columns.Add("Idx");          // Hidden index (left or Right)
                    dt.Columns.Add("Keyword");      // Hidden Keyword
                }
            }


            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        public void rmvDspRecords()
        {
            string logSourceMethod = "rmvDspRecords()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {

                //
                // This is being done in the Service at the processInput routine
                // (future - cater for subroutines by setting the display seq = line number subr called from) ***
                //

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void retrieveErrors()
        {
            string logSourceMethod = "retrieveErrors()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                errText = " ";
                TextBox1.Text = " ";
                TextBox1.BackColor = System.Drawing.Color.Green;
                TextBox1.Visible = false;

                for (int cnt = 0; cnt < MyErrorsEncounteredList.Count(); cnt++) // Loop through Error List with for loop
                {
                    //MyErrorsEncountered = MyRtnFromServiceParms.MyErrorsEncounteredList[cnt];
                    MyErrorsEncountered = MyErrorsEncounteredList[cnt];
                    if (string.IsNullOrWhiteSpace(MyErrorsEncountered.errorDescr))
                    {
                        MyErrorsEncountered.errorDescr = MyErrorsEncountered.errorDescr + " / " + MyErrorsEncountered.errorData;
                    }
                    errText = errText + MyErrorsEncountered.errorDescr + "\r\n";
                    TextBox1.Visible = true;
                    TextBox1.Text = errText;
                    TextBox1.BackColor = System.Drawing.Color.Red;
                    if (GridView1.FooterRow != null)
                    {
                        GridView1.FooterRow.BackColor = System.Drawing.Color.Red;
                    }
                    // If error encountered then go to previous input but retain error messages
                    if (MyPrevErrorsEncounteredList != null)
                    {
                        if (MyPrevErrorsEncounteredList.Count() > 0)
                        {
                            MyPassToServiceParms.passedCurSeq = prevSeq;
                            forwardDirection = false;  // Previous is going backwards
                            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;

                            // return previous transaction and transaction seq
                            //
                            // Get the number of transactions recorded in Prev array
                            //
                            int i = 0;
                            int num = 0;
                            for (i = 0; i < prevSeqArr.Count(); i++) // Loop through array
                            {
                                if (prevSeqArr[i] != " " ) //&& !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp2"))
                                {
                                    string type = prevSeqArr[i].Substring(0, 1);
                                    if (type == "t")
                                    {
                                        num++;
                                    }

                                }
                                else
                                    i = 201;
                            }
                            // Only go back to previous transaction line when one exists
                            only1TransLineExists = false;
                            if (num == 1)
                            {
                                only1TransLineExists = true;
                            }
                            RtnPrevTranAndSeq();

                            MyPassToServiceParms.passedCurrentTransId = prevTran;
                            MyPassToServiceParms.MyErrorsEncounteredList = MyRtnFromServiceParms.MyErrorsEncounteredList;
                            //
                            // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                            //
                            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                            {
                                MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                            }
                            processTransaction();

                        }
                    }
                }

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void retrievePromptMsgs()
        {
            string logSourceMethod = "retrievePromptMsgs()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                promptText = " ";

                // Only if nor errors (clientside or serverside) should we display prompts
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedPromptDescription) && clientSideError == false && serverSideError == false) // returned from service
                {
                    TextBox1.Visible = true;
                    TextBox1.Text = MyRtnFromServiceParms.passedPromptDescription;
                    promptText = MyRtnFromServiceParms.passedPromptDescription;
                    TextBox1.BackColor = System.Drawing.Color.Green;
                }

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void saveSessionParms()
        {
            string logSourceMethod = "saveSessionParms()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                // Save session parameters
                Session["returnParms"] = MyRtnFromServiceParms;
                Session["toParms"] = MyPassToServiceParms;
                Session["client"] = client;
                Session["dropDownList"] = dropDown;
                Session["dropDownList2"] = dropDown2;
                Session["previousSeqArray"] = prevSeqArr;
                Session["prevErrorsEncountered"] = MyPrevErrorsEncounteredList;
                Session["sessionLvlValues"] = MySessionLvlValues;

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void restoreSessionParms()
        {
            string logSourceMethod = "restoreSessionParms()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                // Restore Session parameters from previous screen 
                MyRtnFromServiceParms = (TiosServiceReference1.RtnFromServiceParms)Session["returnParms"];
                MyPassToServiceParms = (TiosServiceReference1.PassToServiceParms)Session["toParms"];
                client = (TiosServiceReference1.TransactionClient)Session["client"];
                dropDown = (string[])Session["dropDownList"];
                dropDown2 = (string[])Session["dropDownList2"];
                prevSeqArr = (string[])Session["previousSeqArray"];
                MyPrevErrorsEncounteredList = (List<TiosServiceReference1.ErrorsEncountered>)Session["prevErrorsEncountered"];
                MySessionLvlValues = (TiosServiceReference1.SessionLvlValues)Session["sessionLvlValues"];

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        //
        // Convert dataset to xml string
        public static string Serialize(object obj)
        {
            string logSourceMethod = "callService()";
            using (MemoryStream memoryStream = new MemoryStream())
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
                serializer.WriteObject(memoryStream, obj);
                memoryStream.Position = 0;
                return reader.ReadToEnd();
            }
        }

        // Convert xml string back to obj
        public static object Deserialize(string xml, Type toType)
        {
            using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
                DataContractSerializer serializer = new DataContractSerializer(toType);
                return serializer.ReadObject(reader);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            string logSourceMethod = "OnPreRender()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            // 1. code put here will be executed first

            // now we call the base class' version, which will then raise the
            // PreRender event
            base.OnPreRender(e);

            // 3. code put here will be executed last
        }


        // Called when page has finished - cleanup here
        protected void Page_Unload(object sender, EventArgs e)
        {
            string logSourceMethod = "page_Unload()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
        }

        // DropDownList Changed
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string logSourceMethod = "DropDownList1_SelectedIndexChanged()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();

            ////
            //// If a value has been selected from the Dropdown List other than the defaulted one (index 0) then force Next
            ////
            //if (ComboBox1.SelectedIndex > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt")) 
            //{
            //    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
            //    {
            //        MyRtnFromServiceParms.passedClientKeywords = "clt-atoclknxt";
            //    } 
            //    else
            //        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";
            //}
        }


        //
        // Previous Button pressed
        //
        protected void Button1_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "Button1_Click(Previous)";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            //
            // If previously selected on a transaction which is the only transaction record in prevSeqArr 
            // Then remove this record from prevSeqArr to avoid the screen being re-displayed when previous selected.
            //
            int i = 0;
            int j = 0;
            int num = 0;
            for (i = 0; i < prevSeqArr.Count(); i++) // Loop through array
            {
                if (prevSeqArr[i] != " ")
                {
                    string type = prevSeqArr[i].Substring(0, 1);
                    if (type == "t")
                    {
                        num++;
                        j = i;

                    }

                }
                else
                    i = 201;
            }

            // Remove record when its the only existing transaction record && Overriding keyword "Clt-KepPrvArrVal" not present

            if (num == 1 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval"))
            {
                prevSeqArr[j] = " ";
            }

            ComboBox1.Visible = true;
            FileUpload1.Visible = false;
            forwardDirection = false;  // Previous is going backwards
            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;
            prevClicked = true;

            // return previous transaction and transaction seq
            RtnPrevTranAndSeq();
            MyPassToServiceParms.passedCurrentTransId = prevTran;

            processTransaction();
        }

        //
        // Next Button pressed
        //
        protected void Button2_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "Button2_Click(Next)";
            //MySessionLvlValues.dispVarRqd = false;
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            cancellationTokenSource.Cancel();  // Cancel any existing Pooling for barcoded transactions
            clientSideError = false;
            serverSideError = false;
            forwardDirection = true;
            nextClicked = true;

            // Test reflection
            string tempa = " ";
            if (tempa == "Y")
            {
                GetObjProperties(GridView1);
            }

            if (this.FileUpload1.HasFile)
                //{
                //    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
                //}

                //
                // If mandatory dropdown entry requireed then error if not in list
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-cpylsttoexl")) // copy contents of gridview List to Excel
                {

                    if (ComboBox1.SelectedValue.ToLower().Trim() == "y")
                    {
                        ExportToExcel(); // Export contents to Excel
                    }

                }

            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // upload file from client to Server
            {

                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrv"))  // Return DS from client to Service
                {
                    ImportFile(); // Import file from client to Server
                }

            }


            // Validate Prefix/ Suffix if specified on input

            int pfxLen = MyRtnFromServiceParms.passedBarcodePrefix.Length;
            int sfxLen = MyRtnFromServiceParms.passedBarcodeSuffix.Length;
            bool prefixSuffixRqd = true;
            if (MyRtnFromServiceParms.passedScanPfxSfxRequired.ToLower() != "y")
            {
                prefixSuffixRqd = false;
            }
            string barcodeSetting = MyRtnFromServiceParms.passedBarcodeSetting;

            MyPassToServiceParms.passedBarcodeScannedInput = false;

            //
            // Check for the existance of a scanned value in hiudden scan field
            //
            if (!String.IsNullOrWhiteSpace(hiddenScannedValue.Value))
            {
                string scannedValue = hiddenScannedValue.Value;
                int totLen = scannedValue.Length;
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodePrefix))
                {
                    //
                    // Validate & Remove Prefix from value if existing
                    //
                    var pos = scannedValue.IndexOf(MyRtnFromServiceParms.passedBarcodePrefix);
                    if (pos == 0 && totLen > pfxLen)
                    {
                        scannedValue = scannedValue.Substring(pfxLen, (totLen - pfxLen)).Trim();
                    }
                    if (prefixSuffixRqd && pos != 0)
                    {

                        // If from mobile device 
                        string message = "This input field has a pre-defined Prefix which does not match the value entered. Please check that you have scanned the correct label ?";
                        if (mobileOrNonMobile.Value == "mobile")
                        {
                            ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                            clientSideError = true;
                        }
                        // non - mobile device
                        else
                        {
                            ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                            clientSideError = true;
                        }

                    }

                }


                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodeSuffix))
                {
                    //
                    // Validate & Remove Suffix from value if existing
                    //
                    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodeSuffix) && clientSideError != true && serverSideError != true)
                    {
                        totLen = scannedValue.Length;
                        var pos = scannedValue.LastIndexOf(MyRtnFromServiceParms.passedBarcodeSuffix);
                        if (pos > 0 && totLen > sfxLen)
                        {
                            scannedValue = scannedValue.Substring(0, (totLen - sfxLen));
                        }
                        if (prefixSuffixRqd && pos < 0 || (pos + sfxLen) != totLen)
                        {

                            // If from mobile device 
                            string message = "This input field has a pre-defined Suffix which does not match the value entered. Please check that you have scanned the correct label ?!";
                            if (mobileOrNonMobile.Value == "mobile")
                            {
                                ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                                clientSideError = true;
                            }
                            // non-mobile device 
                            else
                            {
                                ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                                clientSideError = true;
                            }

                        }
                    }
                }
                string returnedScannedValue = "";
                // Insert scanned value into ComboBox1
                ComboBox1.ClearSelection();
                ComboBox1.Dispose(); // required to clear previous values
                ComboBox1.Items.Clear();
                ComboBox1.Text = " ";
                MyPassToServiceParms.passedBiometricConfirmationSuccessful = false;
                MyPassToServiceParms.passedBarcodeScannedInput = false;

                // Biometric confirmation
                if (scannedValue.ToLower().Contains("[tiosbiometricconfirmation]"))
                {
                    MyPassToServiceParms.passedBiometricConfirmationSuccessful = true;
                    MyPassToServiceParms.passedBarcodeScannedInput = true;
                    // if clt-BioCfmTxt keyword exists then substitute text for "[TiosBiometricConfirmation]" 
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfmtxt"))
                    {
                        returnedScannedValue = "Y";  // Change to be the character(s) after the keyword
                    }
                }

                // scanned barcode value
                if (scannedValue.ToLower().Contains("scannedtransaction2"))
                {
                    delimitedList1 = RtnDelimitedValues(scannedValue);
                    // Should be 5 values passed scannedtransaction2, enterpriseId, UserId, deviceId, scannedValue
                    if (delimitedList1.Count() == 5 && MyRtnFromServiceParms.passedEnterpriseId==delimitedList1[1] && MyRtnFromServiceParms.passedUserId == delimitedList1[2])
                    {
                        MyPassToServiceParms.passedBarcodeScannedInput = true;


                            returnedScannedValue = delimitedList1[4];  // element 4 is the value scanned
                    }
                }

                ComboBox1.Items.Add(returnedScannedValue);
                ComboBox1.Text = returnedScannedValue;
                ComboBox1.SelectedIndex = 0;
                
 
                if (MyRtnFromServiceParms != null)
                {
                    logText = "SCAN:: - scannedValue: " + scannedValue + "   returnedScannedValue: " + returnedScannedValue;
                    WriteLogDetails("Information", logText);
                }
                hiddenScannedValue.Value = "";  // Reset scanned value to blanks

            }




            //
            // If mandatory dropdown entry requireed then error if not in list
            //
            // TODO: ContainsClientKeyword was removed from the service?
            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnman")) // Mandatory dropdown list selection required
            {
 
                bool AutoClickNext = MyRtnFromServiceParms.passedAtoClkNxtVal.ToLower().Split(',').Contains(TextBox2.Text.ToLower());
                logText = "****AUTOCLICKNEXT**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Trus/false: "+  AutoClickNext.ToString() +  "  passedAtoClkNxtVal: " + MyRtnFromServiceParms.passedAtoClkNxtVal.ToLower() + " TextBox2: " +TextBox2.Text.ToLower()+" *****";
                WriteLogDetails("Information", logText);
                if (AutoClickNext  && clientSideError==false && MySessionLvlValues.errorExists==false && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                {
                    if (string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + "clt-atoclknxt";
                    }
                    else
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";

                    logText = "****AUTOCLICKNEXT2**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Keywords: " + MyRtnFromServiceParms.passedClientKeywords +" *****";
                    WriteLogDetails("Information", logText);
                }

                int resultIndex = -1;
                if (dropDown != null)
                {
                    resultIndex = Array.IndexOf(dropDown, ComboBox1.SelectedValue.Trim());
                }
                if (resultIndex == -1)
                {
                    logText = "****AUTOCLICKNEXT3**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Dropdown: " + dropDown + "Selected Value: "+ ComboBox1.SelectedValue.Trim()+" * ****";
                    WriteLogDetails("Information", logText);
                    ClientScript.RegisterStartupScript(GetType(), "myId1", "chkAgainstDropdownList();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }

            //
            // TEST Look for changes in ComboBox1 dropdownlist
            //
            if (testDropdown == true)
            {
                ClientScript.RegisterStartupScript(GetType(), "myId7", "ComboBox1_Check();", true);
            }

            //
            // If mandatory entry (ie Non Blank) then validate via Javascript
            //

            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-manent")) // non blank entry required
            {

                if (ComboBox1.SelectedValue == "" || ComboBox1.SelectedValue == " ")
                {
                    ClientScript.RegisterStartupScript(GetType(), "myId2", "mandatoryEntry();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }


            //
            // If email format required then check for existance of '@' via Javascript
            //
            // TODO: ContainsClientKeyword was removed from the service?
            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-emlfmt")) // email address format required
            {

                if (!ComboBox1.SelectedValue.Contains("@") && ComboBox1.SelectedValue != "" && ComboBox1.SelectedValue != " ")
                {

                    ClientScript.RegisterStartupScript(GetType(), "myId3", "emailFormatRqd();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }



            //
            // If input value is numeric then validate that value is numeric via Javascript
            //
            if (MyRtnFromServiceParms.passedInpFldTyp.ToLower() == "n") // Numeric
            {
                string myValue = ComboBox1.SelectedValue.Trim();
                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    myValue = myValue.Replace(".", "");         // Remove '.' from menu option
                }


                bool isNumeric = myValue.All(char.IsDigit);
                if (!isNumeric)
                {
                    var type = GetType();
                    ClientScript.RegisterStartupScript(GetType(), "myId4", "numericRqd();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }
            // If no client side errors then return input and process next transaction via Javascript
            if (!clientSideError)
            {
                processTransaction();
            }


            if (MySessionLvlValues.dspFileUploadCtl == true)
            {
                FileUpload fileUpload1 = new FileUpload();
                FileUpload1.Visible = true;
                ComboBox1.Visible = false;
                MySessionLvlValues.dspFileUploadCtl = false;
                FileUpload1.Dispose();
            }
        }

        protected void TextBox1_TextChanged1(object sender, EventArgs e)
        {

        }

        //*************************************************************************
        //                  BUILDING THE GRIDVIEW
        // This will trigger for each row that is bound to the gridview
        //*************************************************************************
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string logSourceMethod = "GridView1_RowDataBound()";

            // This will highlist the gridview rows when cursor on positioned on them
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
            e.Row.ToolTip = "<Click> to select this row.";

            // e.Row.Attributes["onmouseover"] = "onMouseOver('" + (e.Row.RowIndex + 1) + "')";
            // e.Row.Attributes["onmouseout"] = "onMouseOut('" + (e.Row.RowIndex + 1) + "')";


            gVRowCnt = e.Row.Cells.Count;
            string gVRowName = " ";
            gVColCnt = dt.Columns.Count;
            int dtColCnt = dt.Columns.Count;
            int dispSeqCnt = MyRtnFromServiceParms.MyDispSeqList.Count();
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.Footer)
            {
                //
                // Format how menu's should appear
                //
                if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "Variables")
                {
                    e.Row.Cells[1].Width = 50;
                    e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                    e.Row.Cells[2].Width = 300;
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
                    e.Row.Height = 40;
                    GridView1.GridLines = GridLines.None;
                }



                if (MySessionLvlValues.whatAmI == "List")
                {

                    GridView1.GridLines = GridLines.Both;

                }
                if (MySessionLvlValues.whatAmI != "List")
                {

                    GridView1.GridLines = GridLines.None;

                }
                //if (MySessionLvlValues.whatAmI == "List" || MySessionLvlValues.whatAmI == "Transaction")
                //{
                //    GridView1.GridLines = GridLines.None;
                //    try
                //    {


                //        for (int i = 0; i < gVColCnt; i++)
                //        {
                //            // Set the column widths based on maxColWidth array
                //            //

                //            if (i > 0)
                //            {
                //                // Colomn width
                //                e.Row.Cells[i].Width = maxColWidthArray[i - 1] * 30;
                //                e.Row.Cells[i].Wrap = false;

                //                // Row Height
                //                e.Row.Height = rowHeightArray[i - 1];
                //            }
                //        }
                //    }

                //    catch (Exception ex)
                //    {

                //    }
                //}


                //
                // START OF HEADER ============================================================================
                //
                if (e.Row.RowType == DataControlRowType.Header)  // Header record
                {

                    for (int i = 0; i < gVRowCnt; i++)
                    {

                        gVRowName = e.Row.Cells[i].Text;
                        switch (gVRowName)
                        {
                            case "Idx": // Index
                                idxCol = i;
                                break;
                            case "Keyword": // Index
                                kwdCol = i;
                                break;

                        }

                        // Remove all headings except 1st one for Transactions
                        if (MySessionLvlValues.whatAmI == "Transaction" && i > 1)
                        {
                            e.Row.Cells[i].Text = "";
                        }

                        //GrdVieiw1.Rows[i].Height = rowHeightArray[i + 1];

                    }

                    //
                    // Merge columns 1 & 2 in Header for Transactions 
                    //

                    //if (MySessionLvlValues.whatAmI == "Transaction")
                    //{
                    //    e.Row.Cells[1].RowSpan = 1;  // Unable to Merge using =2 !!!!
                    //}
                }

                //
                // END OF HEADER ==============================================================================
                //


                // HEADER/FOOTER/DETAIL

                // For unknown reason when table datasource contains n fields, the Gridview is created with n+1 
                // columns with the extra BLANK column in 1st position. Below we are making this row non visible

                e.Row.Cells[0].Visible = false; // Extra 1st column set to non display

                // Make rows 3 & 4 invisable (keyword index & Keyword) when not displaying a LIST
                if (gVRowCnt >= idxCol && MySessionLvlValues.whatAmI != "List")
                {
                    e.Row.Cells[idxCol].Visible = false;
                    e.Row.Cells[kwdCol].Visible = false;
                }
            }

            //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.Cells[kwdCol].Text != " ")
            //{

            //    ProcessGVKeywords(e.Row.Cells[kwdCol].Text.ToLower(), e.Row.Cells[idxCol].Text.ToLower(), e);  // Process ClientSide Keywords
            //}



            //
            // START OF FOOTER ==============================================================================
            //

            if (e.Row.RowType == DataControlRowType.Footer)   // Footer record
            {

                e.Row.Cells.Clear();
                TableCell tableCell = new TableCell();
                tableCell.Font.Bold = true;
                tableCell.HorizontalAlign = HorizontalAlign.Left;
                if (errText != " ")
                {
                    tableCell.Text = errText;
                    tableCell.BackColor = System.Drawing.Color.Red;
                }
                else
                    if (promptText != " ")
                {
                    tableCell.Text = promptText;
                    tableCell.BackColor = System.Drawing.Color.Green;
                }
            }
            //
            // END OF FOOTER ================================================================================
            //

        }

        //**************************************************************************************
        //                       GRIDVIEW BUILD  ABOVE /\
        //**************************************************************************************



        //
        // Fires when Gridview row is clicked
        //

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string logSourceMethod = "GridView1_SelectedIndexChanged()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            if (GridView1.SelectedIndex >= 0)
            {
                foreach (GridViewRow row in GridView1.Rows)
                {

                    if (row.RowIndex == GridView1.SelectedIndex)
                    {
                        if (GridView1.SelectedIndex < 0)
                        //if (GridView1.SelectedIndex < 0)
                        {
                            return;
                        }

                        //row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
                        row.ToolTip = string.Empty;
                        string ComboValue = GridView1.SelectedRow.Cells[1].Text;
                        if (MySessionLvlValues.whatAmI == "Menu")
                        {
                            ComboValue = ComboValue.Replace(".", "");         // Remove '.' from menu option
                        }
                        ComboValue = ComboValue.Trim();                       // Trim leading and trailing spaces
                        ComboBox1.Items.Add(ComboValue);
                        ComboBox1.SelectedValue = ComboValue.Trim();
                        ComboBox1.Text = ComboValue.Trim();
                        GridView1.SelectedIndex = -1;
                        //
                        // Only act as though Next Clicked when user clicks on a menu or a list
                        //
                        if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "List")
                        {
                            Button2_Click(null, new EventArgs());  // Click Next
                        }
                    }

                    else
                    {
                        //row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
                        row.ToolTip = "Click to select this row.";
                    }
                }
            }
        }

        protected void ComboBox1_SelectedIndexChanged4(object sender, EventArgs e)
        {
            string logSourceMethod = "ComboBox1_SelectedIndexChanged4()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            ////
            //// If a value has been selected from the Dropdown List other than the defaulted one (index 0) then force Next
            ////
            //if (ComboBox1.SelectedIndex > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
            //{
            //    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
            //    {
            //        MyRtnFromServiceParms.passedClientKeywords = "clt-atoclknxt";
            //    }
            //    else
            //        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";
            //}
        }


        //
        // It is critical for the client to know exactly where in the transaction you are currently positioned. Selection of "Prev" can result in
        // moving to the previous input field or back to previous transaction or menu. The 'prevSeqArr' array will keep track of where we are.
        //
        public void UpdatePreviousTransactions()
        {
            string logSourceMethod = "UpdatePreviousTransactions()";
            MySessionLvlValues.dispVarRqd = false;
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            int i = 0;
            int j = 0;
            string blankValu = " ";
            string arrValue = MyRtnFromServiceParms.passedCurrentTransType + "," + MyPassToServiceParms.passedCurrentTransId + "," + MyPassToServiceParms.passedCurSeq;
            string arrValue2 = MyRtnFromServiceParms.passedCurrentTransType + "," + MyPassToServiceParms.passedCurrentTransId;

            //
            // If not going forward (ie Previous selected) then back out last transaction
            //
            if (forwardDirection == false)
            {
                // Find the next available Blank array element        
                j = 0;
                blankValu = " ";
                j = Array.IndexOf(prevSeqArr, arrValue);
                if (j != -1 && only1TransLineExists == false && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                {
                    // clt-kepprvarrval is used where the same input line is used in a loop and you dont want to remove it on PREV
                    if (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval"))
                    {
                        prevSeqArr[j] = " ";
                    }
                }

                //
                // If transactions and Current Seq < last entry in prevSeqArr then remove entries in
                // prevSeqArr that are either ahead or equal the current sequence.
                //
                if (MySessionLvlValues.whatAmI == "Transaction")
                {
                    string curTransName = "t," + MyRtnFromServiceParms.passedCurrentTransId;
                    int curTranSeq = MyRtnFromServiceParms.passedCurSeq;
                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        if (prevSeqArr[i].Contains(curTransName))
                        {
                            delimitedList1 = RtnDelimitedValues(prevSeqArr[i]);
                            prevSeq = 0;
                            bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                            if (prevSeq >= curTranSeq)
                            {
                                    // clt-kepprvarrval is used where the same input line is used in a loop and you dont want to remove it on PREV
                                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval") && prevSeq==curTranSeq )
                                    {
                                       // Do nothing
                                    }
                                    else
                                        prevSeqArr[i] = " ";
                                }
                        }

                    }

                }

            }
            else
            {
                //Update previous transactions
                //

                // If this transaction is a menu then clear down all previous transactions details
                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    string lastMenuEntry = " ";
                    string lastMenuName = " ";
                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        // Save the last Menu entry in the array
                        if (prevSeqArr[i].Contains("m,"))
                        {
                            lastMenuEntry = prevSeqArr[i];
                        }

                        // If this transaction is a Menu then remove all transactions from array
                        if (prevSeqArr[i].Contains("t,"))
                        {
                            prevSeqArr[i] = " ";
                        }
                        else
                        if (prevSeqArr[i] == " ")
                        {
                            i = 200; ;
                        }
                    }
                    // Store name of Last menu entry if existing
                    if (!string.IsNullOrWhiteSpace(lastMenuEntry))
                    {
                        delimitedList1 = RtnDelimitedValues(lastMenuEntry);
                        lastMenuName = delimitedList1[1];
                    }

                    // Find the next available Blank array element        
                    j = 0;
                    blankValu = " ";
                    j = Array.IndexOf(prevSeqArr, blankValu);
                    if (j != -1)
                    {
                        // If already exists then do not write again
                        int k = j - 1;

                        if (k < 0)
                        {
                            k = 0;
                        }


                        if (!prevSeqArr[k].Contains(arrValue2))
                        {
                            prevSeqArr[j] = arrValue;
                        }
                    }

                }
                // If this transaction is a Transaction 
                if (MySessionLvlValues.whatAmI == "Transaction")
                {

                    // Only proceed if this transactions sequence has not already been recorded
                    j = 0;
                    j = Array.IndexOf(prevSeqArr, arrValue);


                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        if (prevSeqArr[i].Contains("t,") && !prevSeqArr[i].Contains(arrValue2) || i >= j && j != -1)  // If array holds a different transaction then remove
                        {                                                                                         // If entry alreay exists then remove all below this  
                            prevSeqArr[i] = " ";
                        }
                        else
                            if (prevSeqArr[i] == " ")
                        {
                            i = 200; ;
                        }
                    }

                    //
                    // set up the current seq in prev seq array                    
                    //
                    if (forwardDirection == true)
                    {
                        j = 0;
                        j = Array.IndexOf(prevSeqArr, blankValu);
                        if (j != -1 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp"))
                        {
                            prevSeqArr[j] = arrValue;
                        }
                    }

                }

                //
                // Set the previous transactions and seq
                //
                // Find the next available Blank array element        
                j = 0;
                j = Array.IndexOf(prevSeqArr, blankValu);
                if (j > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp"))
                {
                    arrValue = prevSeqArr[j - 1];
                }
                delimitedList1 = RtnDelimitedValues(arrValue);
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                if (prevType != "m")
                {
                    bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                }
            }
        }

        // Return delimited values
        public String[] RtnDelimitedValues(string inValue)
        {
            string logSourceMethod = "RtnDelimitedValues()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            string[] dList = new string[100];
            try
            {
                if (inValue == null)
                {
                    inValue = " ";
                }
                dList = inValue.Split(',');
                // check if value is a field     
            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

            //return delimitedList;
            return dList;
        }

        //
        // Return previous transaction & ssequence
        //
        public void RtnPrevTranAndSeq()
        {
            string logSourceMethod = "RtnPrevTranAndSeq()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            // default exist transaction
            bool gotoHomePage = false;
            prevTran = MyRtnFromServiceParms.passedCurrentTransId;
            prevSeq = MyPassToServiceParms.passedCurSeq;
            //
            // Determine what the previous transaction and seq No was
            //
            string blankValu = " ";
            string arrValue = " ";
            int j = 0;
            j = Array.IndexOf(prevSeqArr, blankValu);
            if (j > 0)
            {
                arrValue = prevSeqArr[j - 1];
            }
            else
                arrValue = prevSeqArr[0];

            delimitedList1 = RtnDelimitedValues(arrValue);

            // 
            // If j=0 then previous will take us back to home page
            // 
            if (j == 0)
            {
                gotoHomePage = true;
            }

            if (delimitedList1.Count() > 0 && (!string.IsNullOrWhiteSpace(delimitedList1[0])))
            {
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                // If menu then jump back 1
                if (prevType == "m" && j > 0)
                {

                    arrValue = prevSeqArr[j - 1];
                    prevSeqArr[j - 1] = " ";
                }

                delimitedList1 = RtnDelimitedValues(arrValue);
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                if (prevType != "m")
                {
                    bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                }
            }
            MyPassToServiceParms.passedCurrentTransId = prevTran;
            MyPassToServiceParms.passedCurSeq = prevSeq;

            // 
            // If prevSeqArr[0] is blanks then take us back to home page
            // 
            if (string.IsNullOrWhiteSpace(prevSeqArr[0]) && string.IsNullOrWhiteSpace(prevTran))
            {
                gotoHomePage = true;
            }


            if (gotoHomePage || MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-logout"))
            {
                gotoHomePage = false;
                Response.Redirect("~/Default.aspx", true);
            }

        }

        //
        // Load the Transaction view 
        //

        protected void Show_Transaction(object sender, EventArgs e)
        {
            string logSourceMethod = "Show_Transaction()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            if (MySessionLvlValues.displayVariables == true)
            {
                MySessionLvlValues.displayVariables = false;
                if (dispIsAMenu)
                {
                    MySessionLvlValues.whatAmI = "Menu";
                }
                else
                    MySessionLvlValues.whatAmI = "Transaction";


                if (MySessionLvlValues.displayList == true)
                {
                    MySessionLvlValues.whatAmI = "List";
                }
            }

            processRtnDisp();
            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            SetColWidthRowHeight();
            GridView1.DataBind();


            saveSessionParms();  // save Session parameters from this call
        }

        // Show the Variables view

        protected void Show_Variables(object sender, EventArgs e)
        {
            string logSourceMethod = "Show_Variables()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            MySessionLvlValues.displayVariables = true;
            MySessionLvlValues.whatAmI = "Variables";

            processRtnDisp();
            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            //SetColWidthRowHeight();
            GridView1.DataBind();


            if (dispIsAMenu)
            {
                //string colWidth = GridView1.Columns[0].ItemStyle.Width.Value.ToString();
                //GridView1.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Left;

            }
            saveSessionParms();  // save Session parameters from this call
        }


        //
        // Set default Column width & Row Height for Gridview
        //
        public void SetColWidthRowHeight()
        {
            string logSourceMethod = "SetColWidthRowHeight()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            maxColWidthArray = new int[tblColCnt]; // based on field lengths in each column
            colWidthArray = new int[tblColCnt]; // based on user override
            rowHeightArray = new int[tblColCnt];// based on user override
            for (int x = 0; x < tblColCnt; x++)
            {
                colWidthArray[x] = dftColWidth;
                maxColWidthArray[x] = 0;
            }

            //
            // get with actual size of longest text in each column
            //

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    String cellText = row[i].ToString();
                    int maxColLen = cellText.Length;
                    // Replace Max Col Length with widest
                    if (maxColLen > maxColWidthArray[i])
                    {
                        maxColWidthArray[i] = maxColLen;

                    }
                }
            }

            //
            // Now default the Row Heights
            //
            for (int x = 0; x < tblColCnt; x++)
            {
                rowHeightArray[x] = dftRowHeight;
            }
        }

        //
        // Export transaction to excel
        //
        protected void ExportToExcel()
        {
            string logSourceMethod = "ExportToExcel()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                //To Export all pages
                GridView1.AllowPaging = false;

                GridView1.RenderControl(hw);
                //style to format numbers to string
                string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }
        //
        // Export transaction to excel
        //
        protected void ImportFile()
        {
            string logSourceMethod = "ImportFle()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            string Username1 = User.Identity.Name;

 
            if (this.FileUpload1.HasFile)
            {
                try
                {
                    string logonName2 = Environment.UserName;

                    string uploadPath1 = MapPath("~/" + MyRtnFromServiceParms.passedEnterpriseId); // Default

                    // If you want to upload the file to somewhere other than root directory + enterprise then use "MyRtnFromServiceParms.passedToFileLoc"
                    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedToFileLoc))
                    {
                        uploadPath1 = MyRtnFromServiceParms.passedToFileLoc;
                    }

                    if (!Directory.Exists(uploadPath1))
                    {
                        Directory.CreateDirectory(uploadPath1);
                        DirectorySecurity sec = Directory.GetAccessControl(uploadPath1);
                        // Using this instead of the "Everyone" string means we work on non-English systems.
                        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        Directory.SetAccessControl(uploadPath1, sec);

                    }


                    //determine if file exist
                    //string uploadPath1 = Server.MapPath(Path.Combine("~/" + MyRtnFromServiceParms.passedEnterpriseId + "/", FileUpload1.FileName));
                    if (MyRtnFromServiceParms != null)
                    {
                        logText = "IMPORT - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   importing file:" + uploadPath1 + "/" + FileUpload1.FileName;
                        WriteLogDetails("Information", logText);
                    }

                    if (File.Exists(uploadPath1 + "\\" + FileUpload1.FileName))
                    {
                        try
                        {
                            //delete existing file
                            File.Delete(uploadPath1 + "\\" + FileUpload1.FileName);
                            logText = "DELETE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   importing file:" + uploadPath1 + "/" + FileUpload1.FileName;
                            WriteLogDetails("Information", logText);
                        }
                        catch (Exception ex)
                        {
                            if (MyRtnFromServiceParms != null)
                            {
                                logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                                WriteLogDetails("Error", logText);
                            }
                        }
                    }
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsdtetim"))  // Return DS plus datetime appended from client to Service
                    {
                        var curdatetime = System.DateTime.Now.ToString("yyMMdd HHmmss");
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");             // Remove extension from filename
                        saveAsName = saveAsName+ "_"+curdatetime;                   // append current datetime
                        saveAsName = saveAsName + Extension;                        // re-append extension
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsdte"))  // Return DS plus datetime appended from client to Service
                    {
                        var curdate = System.DateTime.Now.Date.ToString("yyMMdd");
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");             // Remove extension from filename
                        saveAsName = saveAsName + "_"+ curdate;                     // append current datetime
                        saveAsName = saveAsName + Extension;                        // re-append extension
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsusr"))  // Return DS plus userId appended from client to Service
                    {
                        
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");                      // Remove extension from filename
                        saveAsName = saveAsName + "_"+ MyRtnFromServiceParms.passedUserId;   // append current datetime
                        saveAsName = saveAsName + Extension;                                 // re-append extension
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    {
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + FileUpload1.FileName);
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + FileUpload1.FileName);
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        ComboBox1.SelectedValue = FileName.Trim();
                    }


                    //FileName = Path.GetFileName(FileUpload1.FileName);
                    //Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                    //FilePath = uploadPath1;
                    //ComboBox1.SelectedValue = FileName.Trim();



                    try
                    {
                        //FileUpload1.PostedFile.SaveAs(FilePath);
                    }
                    catch (Exception ex)
                    {
                        //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                            WriteLogDetails("Error", logText);
                        }


                    }
                    // Test1 - read through uploaded file
                    //string line = " ";
                    //var csvData = Encoding.UTF8.GetString(FileUpload1.FileBytes);

                    //using (var reader = new StringReader(csvData))
                    //{
                    //    var headers = reader.ReadLine().Split(',');
                    //    while ((line = reader.ReadLine()) != null)
                    //    {
                    //        var fields = line.Split(',');
                    //    }
                    //}

                    // Test1 end

                    // Test2  Serialize contents of uploaded data table
                    //dt = ConvertCSVtoDataTable(FilePath);
                    //dt.TableName = "myTable";
                    //DataSet ds = new DataSet();
                    //ds.Merge(dt);
                    //MyPassToServiceParms.passedDs3XmlString = Serialize(ds);
                    //MyGlobals.logger2.Information("ds3XmlString: {ds3xmlstring} ", MyPassToServiceParms.passedDs3XmlString);
                    // Test2



                }
                catch (Exception ex)
                {
                    //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                    if (MyRtnFromServiceParms != null)
                    {
                        logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                        WriteLogDetails("Error", logText);
                    }

                }
                finally
                {
                    FileUpload1.PostedFile.InputStream.Dispose();
                    FileUpload1.PostedFile.InputStream.Flush();
                    FileUpload1.PostedFile.InputStream.Close();
                    FileUpload1.FileContent.Dispose();
                    FileUpload1.PostedFile.InputStream.Dispose();
                    FileUpload1.Dispose();              // This is required to remove IIS lock on uploaded file
                    //GC.Collect();
                    //GC.WaitForPendingFinalizers(); CAUSING APPLICATION TO HANG!!!!

                    //Release File from Memory after uploading
                }
            }

        }


        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        public static DataTable ConvertCSVtoDataTable(string strFilePath)
        {

            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }


            return dt;
        }


        public void GetObjProperties(object MyObj)
        {
            string logSourceMethod = "GetObjProperties()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Type MyType = GridView1.GetType();
            PropertyInfo[] properties = MyType.GetProperties();
            FieldInfo[] fields = MyType.GetFields();
            foreach (PropertyInfo property in properties)
            {
                var type = " Type: " + property.PropertyType.Name + " Name: " + property.Name + " Value: " + property.GetValue(GridView1, null);
                var valu = " Value: " + property.GetValue(GridView1, null);
            }
            foreach (FieldInfo field in fields)
            {
                var type = " Type: " + field.FieldType.Name + " Name: " + field.Name + " Value: " + field.GetValue(GridView1);
                var valu = " Value: " + field.GetValue(GridView1);
            }
        }

        protected void btnMobileAppRegistration_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "btnMobileAppRegistration()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Response.Redirect("~/MobileRegister.aspx");
        }

        public String GetMobileSessionID
        {
            get
            {
                return String.Format(
                    "{0}/{1}/{2}",
                    MyRtnFromServiceParms.passedUserCompanyName,
                    MyRtnFromServiceParms.passedUserName,
                    MyRtnFromServiceParms.passedUserId);
            }
        }


        public void CheckForScannedTransactions()
        {
            string logSourceMethod = "CheckForScannedTransactions()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            BGJobParms MyBGJobParms = new BGJobParms();
            MyBGJobParms.BGJobName = "BGJOB01";
            MyBGJobParms.BGJobDescription = "Check for Barcode Scanned Transactions";
            MyBGJobParms.BGJobThreadName = "TiosClientBackgroundWorkerThread";
            MyBGJobParms.BGJobAction = "loop";
            MyBGJobParms.BGJobMaxRunSeconds = 20; // Max Time nn seconds
            MyBGJobParms.BGJobDelaySeconds = 2;   // 2 second
            MyBGJobParms.BGJobReportProgress = false;
            MyBGJobParms.BGJobParm1 = MyRtnFromServiceParms.passedEnterpriseId;
            MyBGJobParms.BGJobParm2 = MyRtnFromServiceParms.passedUserId;
            MyBGJobParms.BGJobTransName = MyRtnFromServiceParms.passedCurrentTransId;
            MyBGJobParms.BGJobTransSeq = MyRtnFromServiceParms.passedCurSeq;
            BGWorker MyBGWorker = new BGWorker();

            //Pass BGWorker & BGWorker Parameters to Background job 
            MyBGWorker.ReceiveMyBGWorker(MyBGWorker);
            MyBGWorker.ReceiveMyBGJobParms(MyBGJobParms);

            // Pass MyWebForm1 to Background job to enable call back with results 
            WebForm1 MyWebForm1 = HttpContext.Current.Handler as WebForm1;
            MyBGWorker.ReceiveMyWebForm1(MyWebForm1);

            // Call Background Job
            Debug.WriteLine("INT - Prior to call to StartBackgroundProcess: " + DateTime.Now);

            MyBGWorker.StartBackgroundProcess(MyBGJobParms);
            Debug.WriteLine("INT - Returned from call to StartBackgroundProcess: " + DateTime.Now);
        }


        public void UpdateComboBoxWithScannedValue(string scanValue)
        {
            string logSourceMethod = "UpdateComboBoxWithScannedValue()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Debug.WriteLine("INT - In UpdateComboBoxWithScannedValue: " + DateTime.Now);
            ComboBox1.Items.Add(scanValue.Trim());
            if (!String.IsNullOrEmpty(scanValue))
            {
                ComboBox1.Items.Add(scanValue.Trim());
                ComboBox1.SelectedIndex = 0;
                Debug.WriteLine("INT - In UpdateComboBox Value with: " + scanValue + "  " + DateTime.Now);
            }
            if (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt")) // Auto Click Next after successful scan
            {
                Debug.WriteLine("INT - Adding clt-AtoClkNxt keyword: " + DateTime.Now);
                // HOLD OFF UNTIL TESTED MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + "clt-atoclknxt";
            }

            // ClientScript.RegisterStartupScript(GetType(), "myId996", "RefreshPage();", true);   

        }

        public void CheckForScannedTransactions2()
        {
            string logSourceMethod = "CheckForScannedTransactions2()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            int delay = 2000;
            cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;
            var listener = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    CheckForScannedTransactions();
                    Thread.Sleep(delay);
                    if (token.IsCancellationRequested)
                        break;
                }

                //cleanup
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith((prevTask) =>
            {

            });
        }

        public void CheckForScannedTransactionsOrig(string passedEnterpriseId, string passedUserId)
        {
            string logSourceMethod = "CheckForScannedTransactionsOrig()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            bool found = false;
            string bcReturnedValue = "";
            TiosServiceReference1.TransactionClient client2 = new TiosServiceReference1.TransactionClient();
            DateTime curDateTime = DateTime.Now;
            int delay = 1;
            cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;
            var listener = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    // Do polling here
                    if (!String.IsNullOrEmpty(ComboBox1.SelectedValue) && ComboBox1.SelectedValue != " " || forwardDirection == false)
                    {
                        cancellationTokenSource.Cancel();
                    }
                    else
                    {

                        bcReturnedValue = client2.RetrieveLastScannedValue(passedEnterpriseId, passedUserId, curDateTime);
                        if (!String.IsNullOrEmpty(bcReturnedValue) && bcReturnedValue != "[EMPTY]")
                        {
                            //ComboBox1.Items.Add(bcReturnedValue.Trim());
                            // ComboBox1.Text = "SCANNED VALUE";
                            //ComboBox1.SelectedIndex = 0;
                            found = true;

                            // ClientScript.RegisterStartupScript(GetType(), "myId995", string.Format("SetComboBoxValue('{0}');", bcReturnedValue.Trim()), true);
                            cancellationTokenSource.Cancel();  // Value found - Cancel polling for value
                        }
                    }

                    Thread.Sleep(delay);
                    if (token.IsCancellationRequested)
                        break;
                }

                //cleanup
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith((prevTask) =>
            {
                if (found == true)
                {
                    ClientScript.RegisterStartupScript(GetType(), "myId995", string.Format("SetComboBoxValue('{0}');", bcReturnedValue.Trim()), true);
                }
            });
        }

        // Test SignalR
        public void AnnounceAll(string message)
        {
            string logSourceMethod = "AnnounceAll()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "SCANNED DATA EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Scanned Data: " + message;
                WriteLogDetails("Information", logText);
            }
            else
            {
                logText = "SCANNED DATA: " + message;
                WriteLogDetails("Information", logText);
            }
            string msg = message;
        }
        public void AnnounceUser(string message)
        {
            string logSourceMethod = "AnnounceUser()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            string msg = message;
        }
        
        
        // Copy file to DataSet 
        public DataSet CopyFileToDS(string filePath)
        {
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            // 
            // read text file into DS
            // 
            try
            {
                string line;
                int counter = 0;
                using (StreamReader sr = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string Value = line;
                        delimitedList1 = RtnDelimitedValues(Value);
                        if (counter == 0)
                        {
                            for(int i=0;i<delimitedList1.Count();i++)
                            {
                                dt.Columns.Add(delimitedList1[i], typeof(String));
                            }
                        }
                        else
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < delimitedList1.Count(); i++)
                            {
                                dr[i] = delimitedList1[i];
                            }
                            dt.Rows.Add(dr);
                        }
                        counter++;
                    }
                }
                ds.Tables.Add(dt);
                return ds;
            }
         
            catch (Exception ex)
            {
                logText = "Error Reading _MyDispSeq2 file - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords + "error: " + ex.ToString();
                WriteLogDetails("Error", logText);
                return ds;
            }
        }


        //Write to Serilog Logger
        public void WriteLogDetails(string logtype, string logText)
        {
            logSourceMethod = "WriteLogDetails";

            bool activateLoggingForUser = false;
            try
            {
                if (MyGlobals.logger2 == null)
                {
                    MyGlobals.logger2 = new LoggerConfiguration()
                   .ReadFrom.AppSettings()
                   .CreateLogger();
                    Log.Logger = MyGlobals.logger2;
                }

                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedUserId))
                {
                    if (MyRtnFromServiceParms.passedActivateLoggingForUser.ToLower() == "y")
                    {
                        activateLoggingForUser = true;
                    }
                }
                // Check if logging required globally or for user
                string globalLogging = ConfigurationManager.AppSettings.Get("switch on global logging");

                if (activateLoggingForUser == true || globalLogging.ToLower() == "true")
                {
                    MyGlobals.loggingRequired = true;
                }


                if (MyGlobals.loggingRequired)
                {
                    // substitute field names for actual values


                    switch (logtype.ToLower())
                    {
                        case ("verbose"):
                            MyGlobals.logger2.Verbose(logText);
                            break;
                        case ("debug"):
                            MyGlobals.logger2.Debug(logText);
                            break;
                        case ("information"):
                            MyGlobals.logger2.Information(logText);
                            break;
                        case ("warning"):
                            MyGlobals.logger2.Warning(logText);
                            break;
                        case ("error"):
                            MyGlobals.logger2.Error(logText);
                            break;
                        default:
                            MyGlobals.logger2.Fatal(logText);
                            break;

                    }
                }
            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Error Desc:" + ex;
                    MyGlobals.logger2.Error(logText);
                }

            }
        }

    }

}

Open in new window



Errors

Error	CS0234	The type or namespace name 'Optimization' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	64	Active
Error	CS0234	The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	64	Active
Error	CS0052	Inconsistent accessibility: field type 'RtnFromServiceParms' is less accessible than field 'WebForm1.MyRtnFromServiceParms'	TiosClient	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx.cs	53	Active
Error	CS0052	Inconsistent accessibility: field type 'SessionLvlValues' is less accessible than field 'WebForm1.MySessionLvlValues'	TiosClient	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx.cs	54	Active
Error	CS0103	The name 'GetThemeDirectoryUrl' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	39	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	64	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	148	Active
Error	CS0103	The name 'ComboBox1' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	178	Active
Error	CS0103	The name 'MySessionLvlValues' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	202	Active
Error	CS0103	The name 'GetJSONGridKeywords' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	203	Active
Error	CS0103	The name 'GetJSONPassedClientKeywords' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	204	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	206	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	206	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	208	Active
Error	CS0103	The name 'GetMobileSessionID' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	209	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	211	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	212	Active
Error	CS0103	The name 'MyRtnFromServiceParms' does not exist in the current context	1_WebForm1.aspx	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx	213	Active
Warning	CS0105	The using directive for 'System.Web' appeared previously in this namespace	TiosClient	C:\Users\User\source\repos\TiosClient\TiosClient\WebForm1.aspx.cs	31	Active

Open in new window

ste5anSenior Developer

Commented:
You need to repair those errors first. The actual error mentioned above is imho by using an outdated binary.

Start by checking the used libraries, whether the correct verions are installed. Also check whether the references are listed correctly under the references node in VS.

Author

Commented:
Sorry for the delay in responding. I have spent days trying to fix this without success. I even moved it off windows 7 to windows 10 but I have similar results. None of the references are showing up in error. On windows 10 the application is now giving the error "The name MyRtnFromServiceParms does not exist in the current context."   However it is defined in the code behind WebForm1.aspx.cs. I don't understand why WebForm1.aspx does not recognise MyRtnFromServiceParms  Below is the Webform1.aspx and the code behind. Really appreciate any help I can get to get past this error as I am new to C# and WCF.

See line 64 of Webform1.aspx and line 52 of the code behind.
 


WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Src="WebForm1.aspx.cs" Inherits="TiosClient.WebForm1" EnableSessionState="True" EnableEventValidation="false" Async="true"%>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<!DOCTYPE html>

<html>
<head runat="server">
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-datepicker.css" rel="stylesheet" />
    <link href="Content/general.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/app/menu/menu.css" rel="stylesheet" />

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
 
    <script type="text/javascript" src="Scripts/app/dymo-printing.js"></script>
    <script type="text/javascript" src="Scripts/app/utils.js"></script>

    <title>TransactionName</title>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-113314448-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-113314448-1');
</script>

</head>
<body>
    
    <div id="modalWIP">
        <img src="images/_generic/wip.gif" />
    </div>

    <link href="<%=GetThemeDirectoryUrl %>/theme.css" rel="stylesheet" />

    <div class="centered">
        <form id="form1" runat="server" defaultbutton="NextBtn" onsubmit="showWorkInProgress(); return true;">
            <div class="header">
                <div class="hidden">
                    <asp:HiddenField ID="loggedOnUserEnterpriseId" runat="server" />
                    <asp:HiddenField ID="loggedOnUserId" runat="server" />
                    <asp:HiddenField ID="mobileOrNonMobile" runat="server" />
             
                 </div>
                <div class="logo">
                    <img runat="server" id="logo" />
                    <asp:TextBox ID="TextBox2" runat="server" style="display: none;" Width="226px">TextBox2 default value</asp:TextBox>
                </div>
                <div class="tios-logo">
                    <img src="images/tios/tios.png" alt="Tios Logo"/>
                </div>

                <div class="gridview-menu">
                    <div class="menu-button">
                        <img src="Scripts/app/menu/menu-icon.png" alt="Tios Logo"/>
                    </div>

                    <ul class="menu-items">
                        <% if (MyRtnFromServiceParms.passedSecLvl == "9") { %>     [b]// THIS IS WHERE THE ERROR APPEARS[/b]
                        <li>
                            <asp:Button ID="Button1" runat="server" OnClick="Show_Transaction" Text="Transaction" ToolTip="Press to display transaction" Width="144px" />
                        </li>
                        <li>
                            <asp:Button ID="Button2" runat="server" OnClick="Show_Variables" Text="Display Variables " ToolTip="Press to display variables" Width="144px" />
                        </li>
                        <% } %>
                        <li>
                            <asp:Button ID="btnMobileAppRegistration" runat="server" OnClick="btnMobileAppRegistration_Click" Text="Mobile App" ToolTip="Press to manage your mobile app" Width="144px" />
                        </li>
                        <li id="timeoutCountdown"></li>
                    </ul>
                </div>
                

                <div class="gridview-menu" style="display: none;">

                </div>
                
            </div>
            <div class="hidden2">
               <asp:HiddenField ID="scanPrefix" runat="server" />
               <asp:HiddenField ID="scanSuffix" runat="server" />
               <asp:HiddenField ID="scanSetting" runat="server" />
               <asp:HiddenField ID="scanPfxSfxRequired" runat="server" />
               <asp:HiddenField ID="hiddenScannedValue" runat="server" />
               
            </div>
            <asp:Label ID="Label2" runat="server" Text="Transaction Name"></asp:Label>

            <div id="ContextPanel" runat="server" class="user-info">
                <asp:Label ID="lblTransaction" runat="server" CssClass="transaction"></asp:Label>
                <asp:Label ID="lblUserName" runat="server" CssClass="username"></asp:Label>
                <asp:Label ID="lblEnvironment" runat="server" Text="Label" CssClass="environment"></asp:Label>
                <asp:Label ID="lblTime" runat="server" CssClass="time"></asp:Label>
            </div>

            <div class="gridContainer <%= TextBox1.Visible ? "" : "gridContainer-FullHeight" %>">
                <div class="gridHead"></div>
                <div class="gridBody">
                    <asp:GridView ID="GridView1" runat="server" Width="318px" AllowPaging="False" CellPadding="4" 
                            OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" 
                            ShowFooter="false" ShowHeaderWhenEmpty="True" ForeColor="#333333" OnDataBound="GridView1_SelectedIndexChanged" 
                            GridLines="Both" AutoGenerateColumns="True" HorizontalAlign="Left">
                        <AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField />
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle ForeColor="White" HorizontalAlign="Center" BackColor="#284775" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                        <HeaderStyle HorizontalAlign="Left" />
                    </asp:GridView>
                    <asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
                </div>
            </div>

            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>

            <div class="footer">
                <div class="textarea">
                    <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged1" TextMode="MultiLine"></asp:TextBox>
                    <!--<asp:HiddenField ID="hiddenTextBox" runat="server" /> -->
                </div>
                <div class="prev-next">
                    <asp:Button ID="PrevBtn" CssClass="transaction_btnPrevious" runat="server" OnClick="Button1_Click" Text="Prev" />

                    <div class="footerComboInfo">
                        <asp:Label runat="server" ID="lblComboInfo" Text="Do something with this"> </asp:Label>
                    </div>

                    <div class="transaction_input">
                        <cc1:ComboBox ID="ComboBox1" runat="server" OnClientBlur="OnComboBoxBlur" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged4">
                        </cc1:ComboBox>
                        
                        <% var btnScanBarcode_Action = MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfmtxt") ? "confirm" : "end"; %>
                        <a id="btnScanBarcode" style="display: none;" href="tiosapplication://;scheme=tios;<%= btnScanBarcode_Action %>"  >
                            <img style="height: 42px" src="images/_generic/scan.png"  alt="Tios Logo" />
                        </a>

                        <asp:FileUpload ID="FileUpload1" runat="server"  Visible="False" CssClass="transaction_FileUpload" />
                    </div>

                    <asp:Button ID="NextBtn" CssClass="transaction_btnNext" runat="server" OnClientClick="getScreenHeight()" OnClick="Button2_Click" Text="Next" />
                </div>
            </div>
        </form>
    </div>
 
    <script  type="text/javascript">
        function OnComboBoxBlur(sender, args) {
            alert("Blur");
     args.set_cancel(true);  
 }
        </script>

   <!-- AutoClickNext:  AutoClickNextVal.ToLower().Split(',').Contains(textBoxValue),-->
    <script>
    
        var globals2 = {
            myComboText: ' ',
            autoClickNext: ' '};
        
        Sys.Application.add_load(initializePage);
        function initializePage() {
            $find('<%= ComboBox1.ClientID%>').add_propertyChanged(function (sender, event) {
                if (event.get_propertyName() == 'selectedIndex') {
                    globals2.myComboText = sender.get_textBoxControl().value;
                    $('#TextBox2').val(globals2.myComboText);
                    if(globals.autoClickNextVal !=null && globals2.myComboText !=null && globals2.myComboText !=" "); // && globals.autoClickNext!=true)
              
                    {
                        var arr = globals.autoClickNextVal.toLowerCase().split(',');
                        if (arr.indexOf(globals2.myComboText.toLowerCase()) !== -1) 
                        {
                            globals2.autoClickNext=true;
                            if(globals2.autoClickNext ){
                                setTimeout(function(){
                                    $("#NextBtn").focus().click();
                                }, 300);
                            }
                        }
                    }
                }
            })
        }
     
        var globals = {
            gridviewId: '<%=GridView1.ClientID%>',
            whoAmI: '<%=MySessionLvlValues.whatAmI %>',
            gridviewKeywords: <%= GetJSONGridKeywords %>,
            passedClientKeywords : <%= GetJSONPassedClientKeywords %>,
            innactivityLogoutUrl : '<%= ResolveUrl("~/Account/TimeoutTrigger.ashx") %>',
            inactivityAllowedSeconds : <%=MyRtnFromServiceParms.passedUserInactivityAllowedSeconds > 0 ? MyRtnFromServiceParms.passedUserInactivityAllowedSeconds.ToString() : ConfigurationManager.AppSettings["inactivityAllowedSeconds"] %>,

            autoClickNextVal:  '<%= MyRtnFromServiceParms.passedAtoClkNxtVal.ToString().ToLower().Replace("'","^") %>',  // replace any exist quotes in text
            mobileSessionId: '<%= GetMobileSessionID %>',   // tios mobile session id
                
            showCalendar: <%= MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspcal").ToString().ToLower() %>,  // show calendar
            calendarAutoNext: <%= (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-calnortn")).ToString().ToLower() %>,  // auto click next when date is selected from calendar
            autoClickNext: <%= MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt").ToString().ToLower()  %> }; // auto click next when page loads
        
    </script>

   <script src="<%= ResolveUrl("~/Scripts/json2.js")%>"></script>  
   <script src="<%= ResolveUrl("~/Scripts/jquery-1.10.2.min.js")%>"></script>

   <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
    <!--<script src="/signalr/hubs"></script> -->
    
    <script src="http://80.93.26.243/TiosServiceAlias/signalr/hubs"></script>
    <script src="Scripts/app/app.bundle.js"></script>
    <script src="Scripts/app/bowser.js"></script>
    <script src="Scripts/bootstrap-datepicker.js"></script>
    <script src="Scripts/bootstrap.js"></script>

    <script>
        // show the barcode scanning icon if on a mobile device
        if(bowser.android || bowser.ios) $('#btnScanBarcode').css({ 'display': 'inline-block' });
        if(bowser.android || bowser.ios)
        {$('#mobileOrNonMobile').val("mobile")}; 
        if(!bowser.android & !bowser.ios)
        {$('#mobileOrNonMobile').val("non-Mobile")};
        // Auto click next whenever required (clt-AtoClkNxt)
        if(globals.autoClickNext ){
            setTimeout(function(){
                $("#NextBtn").focus().click();
            }, 300);
      }

        // editor should be a calendar picker when required
        setTimeout(function(){
            //the initialization of the datepicker needs to be delayed otherwise it won't get the correct selected value
            if(globals.showCalendar){
                var $txtDate = $('.transaction_input input[type=text]');
                // remove the focus from the 
                $('.transaction_input input[type=text]').click(function(){
                    $txtDate.datepicker('show');
                });

                $txtDate.datepicker({
                    format: "dd/mm/yyyy"
                })
                .on('changeDate', function(){
                    // when date changes, simulate click next
                    $('.transaction_input input[type=text]').blur();
                    if(globals.calendarAutoNext){
                        setTimeout(function(){
                            // delay needed so that the combobox control can do it's magic
                            // if this is not here, the value sent to the server will be the previously selected, not the current
                            $("#NextBtn").focus().click();
                        }, 100);                
                    }
                });
            }        
        }, 500);

        // auto click next if item selected from combobox
        $('.footer').on('click', '#ComboBox1_ComboBox1_OptionList li', function(){
            alert('test');
        });

        // The following code is catering for changes to the ComboBox1 DropDownList values (client side)
        // The selected value will be written to TextBox2 which will be invisible.

     </script>

 </body>
</html>

Open in new window


WebForm1.aspx.cs (Code behind)
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Text;
using System.Drawing;
using System.Data.OleDb;
using Serilog;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Reflection;
using System.Net;
using System.Text.RegularExpressions;
//NEWSTART
//using Dymo;
using DYMO;
using DYMO.Label.Framework;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
//Using System.Web;
using System.Web.UI.HtmlControls;
//NEWEND


namespace  TiosClient
{

    public static class MyGlobals
    {

        public static bool loggerStarted { get; set; }
        public static ILogger logger2 { get; set; }
        public static bool loggingRequired;
    }
    public partial class WebForm1 : System.Web.UI.Page
    {
        public WebForm1 MyWebForm1 = new WebForm1();
        public BGWorker MyBGWorker = new BGWorker();
        public BGJobParms MyBGJobParms = new BGJobParms();


      public TiosServiceReference1.RtnFromServiceParms MyRtnFromServiceParms;   
        public TiosServiceReference1.SessionLvlValues MySessionLvlValues;
  
        public TiosServiceReference1.PassToServiceParms MyPassToServiceParms;
        public TiosServiceReference1.TransactionClient client;
        public TiosServiceReference1.DisplaySeq MyDisplaySeq = new TiosServiceReference1.DisplaySeq();
        //List<TiosServiceReference1.DisplaySeq> MyDisplaySeqList = new List<TiosServiceReference1.DisplaySeq>();
        public TiosServiceReference1.ErrorsEncountered MyErrorsEncountered = new TiosServiceReference1.ErrorsEncountered();
        public List<TiosServiceReference1.ErrorsEncountered> MyErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>();
        public List<TiosServiceReference1.ErrorsEncountered> MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>();
        public List<TiosServiceReference1.DisplaySeq>MyDispSeqList = new List<TiosServiceReference1.DisplaySeq>();
        public TiosServiceReference1.RtnFromServiceParms MyVarValuesDict;

        DataTable dt;
        DataRow dtRow;
        DataSet rtnDataSet;
        bool testDropdown = false;
        bool forwardDirection = true;
        bool clientSideError = false;
        bool serverSideError = false;
        bool dispIsAMenu = false;
        bool prevClicked = false;
        bool nextClicked = false;
        bool only1TransLineExists = false;
        int minRowsRqd = 15;
        int cCnt = 0; // column count
        int rCnt = 0; // row count
        int idxCol = 0;
        int kwdCol = 0;
        int gVRowCnt;
        int gVColCnt;
        int tblRowCnt;
        int tblColCnt;
        string comboBoxValue;
        string prevType = " ";
        string prevTran = " ";
        int prevSeq = 0;
        string[] prevSeqArr = new string[200];
        string[] dropDown;   // 1st column
        string[] dropDown2;  // last column (for alternative display to return value)
        string[] delimitedList1;
        string errText = " ";
        string promptText = " ";
        int[] colWidthArray;
        int[] rowHeightArray;
        int[] maxColWidthArray;
        int dftColWidth = 300;
        int dftRowHeight = 40;
        int widestData = 0;
        int rtnDataSetRowCnt = 0;
        int rtnDataSetColCnt = 0;
        string dsTxtString = "";
        OleDbConnection oledbConn;
        private IdentityReference logonName;
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        string logSourceFile = "WebForm1.aspx.cs";
        string logSourceMethod = "";
        string logText = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            string logSourceMethod = "Page_Load";
            //logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
            //WriteLogDetails("Verbose", logText);

            restoreSessionParms();  // restore parameters from previous call
            ComboBox1.Focus();

            //TEMP CHECKS
            if (MyRtnFromServiceParms == null)
            {
                string msg = "";

                if (MyRtnFromServiceParms == null)
                {
                    msg = msg + "MyRtnFromServiceParms is null ";
                }
                if (MyRtnFromServiceParms != null)
                {
                    logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Session Timeout cause: {msg} - " + msg;
                    WriteLogDetails("Information", logText);
                }
                if (msg == "ok")
                {
                    //Response.Redirect("~/Account/Login.aspx", false);
                    Page.Response.Redirect("~/Account/Login.aspx");
                }
            }
            //TEMP CHECKS END

            // If Time out then return to logon page.
            if (MyRtnFromServiceParms == null)
            {
                Response.Redirect("~/Default.aspx", false);
            }
            //
            // Retrieve Enterprise Logo & Enterprise Skin from Service
            // 
            if (MyRtnFromServiceParms != null)
            {
                logo.Src = MyRtnFromServiceParms.passedEnterpriseLogo;          // LOGO
            }

            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;
            if (MySessionLvlValues == null)
            {
                MySessionLvlValues = new TiosServiceReference1.SessionLvlValues();
            }

            //lblEnvironment.Text = "<span>[ Trans: " + MyRtnFromServiceParms.passedCurrentTransId + " /"+ MyRtnFromServiceParms.passedCurSeq + "  ]</span><span>         "+ MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " </span> <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span><span>00/00/00 00:00</span>";
            lblEnvironment.Text = MyRtnFromServiceParms.passedEnvDesc;
            lblEnvironment.Style.Add(HtmlTextWriterStyle.BackgroundColor, MyRtnFromServiceParms.passedEnvColour);
            lblTransaction.Text = String.Format("[ Trans: {0}/{1} ]", MyRtnFromServiceParms.passedCurrentTransId, MyRtnFromServiceParms.passedCurSeq);
            lblUserName.Text = MyRtnFromServiceParms.passedUserName;
            lblTime.Text = "00/00/00 00:00";

            //If Keywords such as *LIST, *RANGE etc.. selected from dropdown list
            //Then automatically click NEXT rather than display and ask user to click NEXT
            //if (MyRtnFromServiceParms != null && !MyRtnFromServiceParms.passedUserName.ToLower().Contains("pat clarke"))
            //{
            //    TextBox2.Visible=false;
            //}

                if (hiddenTextBox.Value.Contains("*"))
            {

                Button2_Click(null, new EventArgs());  // Click Next
            }

            if (!IsPostBack)
            {
                // First time through initialize previous sequence array
                //
                prevSeqArr = new string[200];
                int i = 0;
                for (i = 0; i < 200; i++) // Loop through array
                {
                    prevSeqArr[i] = " ";
                }

                // Initialize seq to zero when returning from main menu
                MyPassToServiceParms.passedCurSeq = 0;
                MyRtnFromServiceParms.passedCurSeq = 0;

                // Return parameters from last call to service
                MyPassToServiceParms.passedUserId = MyRtnFromServiceParms.passedUserId;
                MyPassToServiceParms.passedEnterpriseId = MyRtnFromServiceParms.passedEnterpriseId;
                MyPassToServiceParms.passedCurrentTransId = MyRtnFromServiceParms.passedCurrentTransId;

                //
                // Create Enterprise directory if not existing
                //
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedEnterpriseId))
                {
                    string uploadPath1 = MapPath("~/" + MyRtnFromServiceParms.passedEnterpriseId);
                    if (!Directory.Exists(uploadPath1))
                    {
                        Directory.CreateDirectory(uploadPath1);
                        DirectorySecurity sec = Directory.GetAccessControl(uploadPath1);
                        // Using this instead of the "Everyone" string means we work on non-English systems.
                        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        Directory.SetAccessControl(uploadPath1, sec);

                    }
                }

                if (MyRtnFromServiceParms.passedCurSeq == 0)
                {
                    MyPassToServiceParms.passedCurSeq = 0;
                }
                else
                    MyPassToServiceParms.passedCurSeq = MyRtnFromServiceParms.passedCurSeq;

         //       HtmlAnchor MyAnchor =this.FindControl('btnScanBarcode');
         //       if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfm"))
         //       {
         //           MyAnchor.HRef = "tiosapplication://;scheme=tios;end";
         //       }
         //       else
         //           MyAnchor.HRef = "tiosapplication://;scheme=tios;confirm";

                widestData = 0;
                processTransaction();  // Load initial transaction
            }

        }



        public void callService()
        {
            string logSourceMethod = "callService()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "CALLING SERVICE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }

                // If Previous key selected
                if (forwardDirection == false)
                {
                    MyPassToServiceParms.passedCurrentTransId = prevTran;
                }

                MyPassToServiceParms.passedForwardDirection = forwardDirection;   //indicates to Servers where NEXT or PREVIOUS buttons pressed
                MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();      // pass input value to the service for processing

                //-----------------------------------------------------------------------------------------------------------------
                // Check if value in ComboBox is from DropdownList and whether it need to be swapped with value from another column
                //-----------------------------------------------------------------------------------------------------------------
                //
                //
                // if more than one column passed in the drop down list then set the selected value to
                // to the value passed in the last column of the dropdown list
                // (eg.  Sales team, 01
                //       Manufacturing team, 02
                //       Finance team, 03
                //
                // If "Sales team" displayed and selected in dropdown then '01' will be returned to the input field
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-sndmsg"))
                {
                    //DateTime curDateTime = DateTime.Now;
                    //var svc = new TiosServiceReference1.TransactionClient();
                    //svc.AnnounceAll("Hello World on " + curDateTime.ToString());

                    // Pat's Note
                    // This was used for testing only - no longer relevant. The message will come from TiosService method ScannedTransactions2 in TransactionService.cs 
                    //
                    //string broadcastMessageFromService="THis should be overridden by broadcastMessage from service";
                    //var hub = new TiosHub();
                    //hub.AnnounceAll(broadcastMessageFromService);
                }

                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst") && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtnlstcol"))
                {
                    int resultIndex = -1;
                    if (dropDown != null)
                    {
                        resultIndex = Array.IndexOf(dropDown, ComboBox1.SelectedValue.Trim());
                    }
                    if (resultIndex != -1)
                    {
                        if (dropDown2 != null)
                        {
                            MyPassToServiceParms.passedInpVal = dropDown2[resultIndex];
                        }

                    }

                }

                //
                //-----------------------------------------------------------------------------------------------------------------
                //

                string Username1 = User.Identity.Name;
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ABOUT TO CALL SERVICE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }

                //
                // Prior to Call to Service delete MyDispSeq2.txt if existing      
                //
                string myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                if (File.Exists(myPath))
                {
                    try {
                        File.Delete(myPath);
                    }
                    catch (Exception ex) { }
                }
                //
                // Call to Service      
                //
                MyRtnFromServiceParms = client.NextTransactionSeq(MyPassToServiceParms);
                MyPassToServiceParms.passedDs3XmlString = " "; // Clear any previous XML string sent to service
                //
                // Return from service
                //
                MyPassToServiceParms.passedUserId = MyRtnFromServiceParms.passedUserId;
                // 
                // Display FileUpload Control on Client
                //
                //if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // Switch on display of file upload control
                //{
                //    MySessionLvlValues.dspFileUploadCtl = true;
                //}

                // If client keyword clt-logout specified then do so now.
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-logout"))
                {
                     Response.Redirect("~/Default.aspx", true);
                }


                if (MyRtnFromServiceParms != null)
                {
                    logText = "BACK IN THE CLIENT - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords;
                    WriteLogDetails("Information", logText);
                }
                // Set the transaction and enterprise Id for next call to service
                MyPassToServiceParms.passedEnterpriseId = MyRtnFromServiceParms.passedEnterpriseId;
                MyPassToServiceParms.passedCurrentTransId = MyRtnFromServiceParms.passedCurrentTransId;
                loggedOnUserEnterpriseId.Value = MyRtnFromServiceParms.passedEnterpriseId; // Used to verify scan
                loggedOnUserId.Value = MyRtnFromServiceParms.passedUserId; // used to verify scan
                scanPrefix.Value = MyRtnFromServiceParms.passedBarcodePrefix.Trim();
                scanSuffix.Value = MyRtnFromServiceParms.passedBarcodeSuffix.Trim();
                scanSetting.Value = MyRtnFromServiceParms.passedBarcodeSetting;
                scanPfxSfxRequired.Value = MyRtnFromServiceParms.passedScanPfxSfxRequired.ToLower();

                //
                // Read the display from file wwwroot/EnterpriseId/UserId_MyDispSeq into list MyDispSeqList
                //

                // First clear the returned List
 
                    MyDispSeqList.Clear();
                    string myFilename = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq.txt";
                    dsTxtString = "";
                    try
                    {

                        string line;
                        int counter = 0;

                        using (StreamReader sr = new StreamReader(File.Open(myFilename, FileMode.Open, FileAccess.Read, FileShare.Read)))
                        {
                            while ((line = sr.ReadLine()) != null)
                            {
                                TiosServiceReference1.DisplaySeq MyDisplaySeq = new TiosServiceReference1.DisplaySeq(); // Declare new instance for each line

                                string Value = line;
                                delimitedList1 = RtnDelimitedValues(line);

                                MyDisplaySeq.type = delimitedList1[0];
                                MyDisplaySeq.enterpriseId = delimitedList1[1];
                                MyDisplaySeq.transId = delimitedList1[2];
                                MyDisplaySeq.transToCall = delimitedList1[3];
                                int intVal = 0;
                                bool result = int.TryParse(delimitedList1[4].ToString(), out intVal);
                                MyDisplaySeq.transIdx = intVal;
                                intVal = 0;
                                result = int.TryParse(delimitedList1[5].ToString(), out intVal);
                                MyDisplaySeq.seqNo = intVal;
                                MyDisplaySeq.dispTxt1 = delimitedList1[6];
                                MyDisplaySeq.dispTxt2 = delimitedList1[7];
                                MyDisplaySeq.dispTxt3 = delimitedList1[8];
                                MyDisplaySeq.dispFldName = delimitedList1[9];
                                MyDisplaySeq.dispKeyWord = delimitedList1[10];
                                MyDisplaySeq.dispIdx = delimitedList1[11];
                                intVal = 0;
                                result = int.TryParse(delimitedList1[12].ToString(), out intVal);
                                MyDisplaySeq.secLvl = intVal;

                                // Restore  any  special characters back to commas
                                MyDisplaySeq.dispTxt1 = MyDisplaySeq.dispTxt1.Replace("$~", ",");
                                MyDisplaySeq.dispTxt2 = MyDisplaySeq.dispTxt2.Replace("$~", ",");
                                MyDisplaySeq.dispTxt3 = MyDisplaySeq.dispTxt3.Replace("$~", ",");
                                MyDisplaySeq.dispFldName = MyDisplaySeq.dispFldName.Replace("$~", ",");
                                MyDisplaySeq.dispKeyWord = MyDisplaySeq.dispKeyWord.Replace("$~", ",");
                                MyDisplaySeq.dispIdx = MyDisplaySeq.dispIdx.Replace("$~", ",");

                                MyDispSeqList.Add(MyDisplaySeq);
                                counter++;
                            }
                            // Copy back to list it was originally being passed to service in.
                            MyRtnFromServiceParms.MyDispSeqList = MyDispSeqList.ToArray();

                        }
                    }
                    catch (Exception ex)
                    {
                        logText = "Error Reading _MyDispSeq file - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords + "error: " + ex.ToString();
                        WriteLogDetails("Error", logText);
                    }

                //
                // Here we have just returned from the service after encountering an Input statement. Below we will process the input and then return to the Service at the statement 
                // after the input. However if when back in the Service we detect an error then we will return to process the prior input statement whilst displaying the error message
                // encountered. To facilitate this we must save the previously encountered error message. This is what we are doing below.

 
                MyErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                // Save errors encountered after last input as they will need to be re-displayed when we go back to previous input

                MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                if (MyRtnFromServiceParms.MyErrorsEncounteredList.Count() > 0)
                {
                    MyPrevErrorsEncounteredList = new List<TiosServiceReference1.ErrorsEncountered>(MyRtnFromServiceParms.MyErrorsEncounteredList);
                }
                else
                {
                    if (MyPrevErrorsEncounteredList != null);
                    {
                        if (MyPrevErrorsEncounteredList.Count() > 0)
                        {
                            for (int cnt = 0; cnt < MyPrevErrorsEncounteredList.Count(); cnt++) // Loop through List with for loop
                            {
                                MyErrorsEncountered = MyPrevErrorsEncounteredList[cnt];
                                MyErrorsEncounteredList.Add(MyErrorsEncountered);
                            }
                            MyPrevErrorsEncounteredList.Clear();  // Clear Prev errors to prevent looping
                        }
                    }
                }

                // Set some of our session parameters based on returned values from Service
                //

                // Errors exist
                if (MyErrorsEncounteredList.Count() > 0)
                {
                    MySessionLvlValues.errorExists = true;
                }
                // Prompt exists
                if (MyRtnFromServiceParms.passedPromptDescription != "" && MyRtnFromServiceParms.passedPromptDescription != " ")
                {
                    MySessionLvlValues.promptExists = true;
                }
                // Display is empty 
                //if (MyRtnFromServiceParms.MyDispSeqList != null && MyRtnFromServiceParms.MyDispSeqList.Count() == 0)
                if (MyRtnFromServiceParms.MyDispSeqList != null && MyRtnFromServiceParms.MyDispSeqList.Count() == 0)
                {
                    MySessionLvlValues.dispIsEmpty = true;
                }
 

                // Display FileUpload Control on Client
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // Switch on display of file upload control
                {
                    MySessionLvlValues.dspFileUploadCtl = true;
                }
                // Hide FileUpload Control on Client
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-hidfilupl")) // Switch off display of file upload control
                {
                    MySessionLvlValues.dspFileUploadCtl = false;
                }

                FileUpload1.Visible = false;
                ComboBox1.Visible = true;
                if (MySessionLvlValues.dspFileUploadCtl == true)
                {
                    FileUpload fileUpload1 = new FileUpload();
                    FileUpload1.Visible = true;
                }
                else if (MySessionLvlValues.dspFileUploadCtl == false)
                {
                    FileUpload1.Dispose();
                    ComboBox1.Visible = true;
                }


                // Restore Gridview Column Widths and Row Heights on change of transaction 
                if (MyRtnFromServiceParms.passedCurrentTransId != MySessionLvlValues.thisTransName)
                {
                    MySessionLvlValues.thisTransName = MyRtnFromServiceParms.passedCurrentTransId;
                    MySessionLvlValues.GVColRowOveridesExistForTrans = false;
                }
                // Dont allow current sequence to go below Zero
                if (MyRtnFromServiceParms.passedCurSeq <= 0)
                {
                    MyPassToServiceParms.passedCurSeq = 0;
                }
                else
                    MyPassToServiceParms.passedCurSeq = MyRtnFromServiceParms.passedCurSeq;

                Label2.Text = MyRtnFromServiceParms.passedCurrentTransId + " : " + MyRtnFromServiceParms.passedCurSeq;
                //
                // =====================================================
                // returned dataset 2 (Dropdown values or Display List)
                // Dataset2 can contain either dropdown values or a display list
                // =====================================================
                //
                rtnDataSetRowCnt = 0;
                rtnDataSetColCnt = 0;
                MySessionLvlValues.displayList = false;
                MySessionLvlValues.prtDymoLabelViaApi = false;

                // If MyDisySeq2 exists then copy file details to DS
                myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                if (File.Exists(myPath))
                {
                    rtnDataSet = new DataSet();
                    //rtnDataSet = (DataSet)Deserialize(MyRtnFromServiceParms.passedDs2XmlString, typeof(DataSet));
                    rtnDataSet = CopyFileToDS(myPath);
                    rtnDataSetRowCnt = rtnDataSet.Tables[0].Rows.Count;
                    rtnDataSetColCnt = rtnDataSet.Tables[0].Columns.Count;

                    // TODO: ContainsClientKeyword was removed from the service?
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dsplst") && rtnDataSetRowCnt > 0)
                    {
                        MySessionLvlValues.displayList = true;
                    }

                }

                // If dropdown list is populated and clt-drpdwnlst specified then set dropDownValuesExist=true
                MySessionLvlValues.dropDownValuesExist = false;

                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst"))
                {
                    MySessionLvlValues.dropDownValuesExist = true;
                }

                // If users security level >=9 then allow user to view transaction variables
                MySessionLvlValues.dispVarRqd = false;
                if (MyRtnFromServiceParms.passedSecLvl == "9")
                {
                    MySessionLvlValues.dispVarRqd = true;
                }


                //=======================================================================
                // Determine what type of display I am (a Menu, a Transaction, a List )
                //=======================================================================

                dispIsAMenu = false;
                MySessionLvlValues.whatAmI = " ";
                if (MyRtnFromServiceParms.MyDispSeqList.Count() > 0)
                {
                    MyDisplaySeq = MyRtnFromServiceParms.MyDispSeqList[0];
                }
                if (MyRtnFromServiceParms.MyDispSeqList.Count() > 0 && MyDisplaySeq.type.ToLower() == "m")
                {
                    dispIsAMenu = true;
                    MySessionLvlValues.whatAmI = "Menu";
                    FileUpload1.Visible = false;
                }
                else
                    MySessionLvlValues.whatAmI = "Transaction";

                if (MySessionLvlValues.displayList == true)
                {
                    MySessionLvlValues.whatAmI = "List";
                }
                if (MySessionLvlValues.displayVariables == true)
                {
                    MySessionLvlValues.whatAmI = "Variables";
                }


                ComboBox1.ClearSelection();
                ComboBox1.Dispose(); // required to clear previous values
                ComboBox1.Items.Clear();
                ComboBox1.Text = " ";
                string defaultValue = MyRtnFromServiceParms.passedInpFldVal;

                if (String.IsNullOrEmpty(defaultValue) && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspcal"))
                {
                    defaultValue = DateTime.Today.ToString("dd/MM/yyyy");
                    ComboBox1.Items.Add(defaultValue);
                    ComboBox1.SelectedIndex = 0;
                }

                // If dropdown list is populated
                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnlst"))
                {
                    dropDown = new string[rtnDataSet.Tables[0].Rows.Count + 1];
                    dropDown2 = new string[rtnDataSet.Tables[0].Rows.Count + 1];
                    int idx = 0;
                    foreach (DataTable table in rtnDataSet.Tables)
                        foreach (DataRow row in table.Rows)
                        {
                            string ComboValue = row.ItemArray[0].ToString().Trim();
                            string ComboValue2 = row.ItemArray[rtnDataSetColCnt - 1].ToString().Trim();
                            dropDown[idx] = ComboValue;
                            dropDown2[idx] = ComboValue2;


                            ComboBox1.Items.Add(ComboValue);
                            if (idx == 0) //|| ComboValue == MyRtnFromServiceParms.passedUserCompanyName)
                            {
                                ComboBox1.SelectedIndex = idx;
                            }


                            // If a default value was passed in via FieldValue then set to this value if encountered.
                            if (defaultValue == ComboValue)
                            {
                                ComboBox1.SelectedIndex = idx;
                                defaultValue = " ";
                            }

                            idx = idx + 1;
                        }

                    // If default value was passed but it does not exist in the ComboBox Value then set it into values
                    if (defaultValue != "" && defaultValue != " " && defaultValue != null)
                    {
                        string ComboValue = defaultValue.Trim();
                        dropDown[idx] = ComboValue;
                        //string dsUserId = row.ItemArray[1].ToString();
                        ComboBox1.Items.Add(ComboValue);
                        ComboBox1.SelectedIndex = idx;
                    }
                }

                // If in a Transaction and ComboBox does not have a selected value then check if  a scanned transaction exists for this user 
                if (MyRtnFromServiceParms.passedCurrentTransType == "t" && ComboBox1.SelectedIndex == -1)
                {
                    //
                    // CANNOT DO THIS HERE AS PAGE HAS NOT LOADED AT THIS TIME
                    // looking at using SIGNALR as an alternative.  BGWorker wil still be useful for other jobs and so will retain logic
                    //
                    //CheckforSacnnedTransactions will run in background and populate any scanned value to ComboBox if ComboBox is empty 
                    //CheckForScannedTransactions();

                }


                //NEWSTART/////////////////////////////
                // If dropdown list is populated with a file sent from the servicee (not for dropdown list)
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-filfrmsrv") && MyPrevErrorsEncounteredList.Count() == 0)
                {

                    bool displayFile = false;
                    if (MyRtnFromServiceParms.passedToFileAction.ToLower() == "open")
                    {
                        displayFile = true;
                    }
                    string filename = MyRtnFromServiceParms.passedFromFileName;
                    string download_folder = MyRtnFromServiceParms.passedFromFileLoc;
                    string fileType = MyRtnFromServiceParms.passedFromFileType;
                    string path1 = String.Format("~/{0}/{1}/{2}", download_folder, MyRtnFromServiceParms.passedEnterpriseId, filename);
                    string path1url = ResolveUrl(path1);
                    //Check for existance 
                    //if (!File.Exists(path1))
                    //{
                    //    return;
                    //}
                    try
                    {
                        if (!displayFile)
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "myId5", string.Format("downloadFile('{0}');", path1url), true); // Closed
                        }
                        else
                        {
                            // browsers are able to open xml files with no issues
                            // to be sure that this works everywhere, the easiest way is to simply clone the file changing its file extension
                            string physicalPath = MapPath(path1url);
                            string physicalPathXml = physicalPath + ".xml";
                            File.Copy(physicalPath, physicalPathXml, true);
                            string path1urlxml = ResolveUrl(String.Format("~/{0}/{1}/{2}", download_folder, MyRtnFromServiceParms.passedEnterpriseId, new FileInfo(physicalPathXml).Name));
                            //ClientScript.RegisterStartupScript(this.GetType(), "myId6", string.Format("displayFile('{0}');", path1urlxml), true);      // Open 
                            ClientScript.RegisterStartupScript(this.GetType(), "myId6", string.Format("displayFile('{0}');", path1url), true);      // Open 

                        }
                    }
                    catch (Exception ex)
                    {
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Error:" + ex;
                            WriteLogDetails("Error", logText);
                        }

                    }
                }


                // If client keyword clt-RedFilToDs specified and file specified in MyRtnFromServiceParms.passedToFileName then read this file into Data Structure

                dsTxtString = "";
                MySessionLvlValues.prtDymoLabelViaApi = false;
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-redfiltods") && MyPrevErrorsEncounteredList.Count() == 0 && (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedToFileName)))
                {

                    string filename = MyRtnFromServiceParms.passedToFileName;
                    dsTxtString = "";
                    try
                    {
                        // 
                        // read special text file
                        // 
                        DataTable dt = new DataTable();
                        DataSet ds = new DataSet();
                        dt.Columns.Add("detail", typeof(String));
                        string line;
                        int counter = 0;

                        System.IO.StreamReader file = new System.IO.StreamReader(File.Open(MyRtnFromServiceParms.passedToFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));

                        while ((line = file.ReadLine()) != null)
                        {
                            string Value = line;
                            dsTxtString = dsTxtString + line;
                            MySessionLvlValues.prtDymoLabelViaApi = true;
                            dt.Rows.Add(Value);
                            counter++;
                        }

                        ds.Tables.Add(dt);
                    }
                    catch (Exception ex)
                    {
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                            WriteLogDetails("Error", logText);

                        }
                    }
                }

                //
                // If keyword contains clt-prtviaapi then call Dymo print API from javascript function to do so.
                // Because Javascript run on the browser it will have access to local label printer
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-prtviaapi") && MySessionLvlValues.prtDymoLabelViaApi == true && dsTxtString != "") // non blank entry required
                {
                    if (forwardDirection == true)
                    {
                        try
                        {
                            //ClientScript.RegisterStartupScript(GetType(), "myId992", "printDymoLabel();", true);
                            // ClientScript.RegisterStartupScript(GetType(), "myId992", string.Format("dymoframeworkInit('{0}');", dsTxtString), true);
                            ClientScript.RegisterStartupScript(GetType(), "myId992", string.Format("printDymoLabel2('{0}');", dsTxtString), true);
                        }

                        catch (Exception ex)
                        {
                            if (MyRtnFromServiceParms != null)
                            {
                                logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                                WriteLogDetails("Error", logText);
                            }
                        }
                    }
                }

                //NEWEND///////////////////////////////

                //
                // If list is to be displayed for selection rather than a standard Input
                //

                // TODO: ContainsClientKeyword was removed from the service?
                if (rtnDataSetRowCnt > 0 && MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dsplst"))
                {

                    int idx = 0;
                    foreach (DataTable table in rtnDataSet.Tables)
                        foreach (DataRow row in table.Rows)
                        {
                            // come back to this. At moment going to copy trnDataSet to dt
                            idx = idx + 1;
                        }
                }


                saveSessionParms();  // save Session parameters from this call

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        public String GetThemeDirectoryUrl
        {
            get
            {
                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedEnterpriseSkin))
                    return "Themes/" + MyRtnFromServiceParms.passedEnterpriseSkin;
                else
                    return "Themes/default";
            }
        }

        /// <summary>
        /// Get the display keywords in JSON format
        /// </summary>
        public String GetJSONGridKeywords
        {

            get
            {
                List<dynamic> rows = new List<dynamic>();

                /*
                When you are displaying a List you should ignore any keywords in MyDispSeqList (even though it may have values and keywords).
                This is because the list being displayed is not built from MyDispSeqList.
                */
                if (MySessionLvlValues.whatAmI != "List")
                {
                    foreach (var row in MyRtnFromServiceParms.MyDispSeqList)
                    {
                        rows.Add(new { keyword = row.dispKeyWord, field = row.dispIdx });
                    }
                }

                JavaScriptSerializer json = new JavaScriptSerializer();

                return json.Serialize(rows);
            }
        }

        public String GetJSONPassedClientKeywords
        {
            get
            {
                List<String> rows = new List<String>();

                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedClientKeywords))
                    rows = MyRtnFromServiceParms.passedClientKeywords.Replace(" ", "").Split(',').ToList();

                JavaScriptSerializer json = new JavaScriptSerializer();

                return json.Serialize(rows);
            }
        }



        public void processTransaction()
        {
            string logSourceMethod = "processTransaction()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            //Update previous transactions
            UpdatePreviousTransactions();

            // Update selected option to Passed Input Value
            MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();


            callService();  // call the Service 

            //if (MyRtnFromServiceParms.MyErrorsEncounteredList.Count()>0)
            only1TransLineExists = false;

            if (MyErrorsEncounteredList.Count() > 0)
            {
                serverSideError = true;
                retrieveErrors();  // retrieve returned errors

            }
            else
                if (clientSideError == false && serverSideError == false)
            {
                TextBox1.Visible = false;
            }

            if (TextBox1.Visible == false)
            {
                retrievePromptMsgs(); // retrieve prompt message if no error message
            }

            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;

            if (MySessionLvlValues != null)
            {
                //Label3.Text = MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " - <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span>";
                //Label3.Text = "[ Trans: " + MyRtnFromServiceParms.passedCurrentTransId + " /" + MyRtnFromServiceParms.passedCurSeq + "  ]         " + MyRtnFromServiceParms.passedUserName + " " + MyRtnFromServiceParms.passedEnv + " - <span style='background:" + MyRtnFromServiceParms.passedEnvColour + "'>" + MyRtnFromServiceParms.passedEnvDesc + "</span>";

                lblEnvironment.Text = MyRtnFromServiceParms.passedEnvDesc;
                ContextPanel.Style.Add(HtmlTextWriterStyle.BackgroundColor, MyRtnFromServiceParms.passedEnvColour);
                lblTransaction.Text = String.Format("[ Trans: {0}/{1} ]", MyRtnFromServiceParms.passedCurrentTransId, MyRtnFromServiceParms.passedCurSeq);
                lblUserName.Text = MyRtnFromServiceParms.passedUserName;
                lblTime.Text = "00/00/00 00:00";
            }
            if (MyRtnFromServiceParms.passedInpFldVal != "" && MyRtnFromServiceParms.passedInpFldVal != null)
            {
                // Re-instate this by adding passed field to comboBox
                //ComboBox1.SelectedValue = MyRtnFromServiceParms.passedInpFldVal;
            }
            processRtnDisp();  // Process the display sequence returned from Service


            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            if (MySessionLvlValues.whatAmI != "List")
            {
                dt.Columns.Remove("Idx");
                dt.Columns.Remove("Keyword");
            }

            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            //SetColWidthRowHeight();
            GridView1.DataBind();



        }

        public void processRtnDisp()
        {
            string logSourceMethod = "processRtnDisp()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                //Convert the returned Display seq into a table which can be bounded to GridView1
                //The display may be alternated via the whatAmI MySessionLvlValue variable 

                dt = new DataTable("Flex DataTable");
                dtRow = dt.NewRow();
                rmvDspRecords();   // remove the display records which have a lower instance than Current instance
                setDspHeadings();  // retrieve the headings for this display


                // For Menus & transactions Read through Display sequence list and output the rows

                cCnt = 0;
                if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "Transaction")
                {
                    for (int cnt = 0; cnt < MyRtnFromServiceParms.MyDispSeqList.Count(); cnt++) // Loop through Display Seq List with for loop
                    {
                        MyDisplaySeq = MyRtnFromServiceParms.MyDispSeqList[cnt];

                        // 1st Column = dispTxt1
                        dtRow[cCnt] = MyDisplaySeq.dispTxt1;
                        cCnt = cCnt + 1;
                        //
                        // * * * T E M P  D I S P L A Y * * *
                        //

                        // 2nd Column = dispTxt2 if processing a menu 
                        if (MyDisplaySeq.type.ToLower() == "m") // Menu
                        {
                            dtRow[cCnt] = " ";
                            if (MyDisplaySeq.dispTxt2 != null)
                            {
                                dtRow[cCnt] = MyDisplaySeq.dispTxt2;
                            }
                            cCnt = cCnt + 1;
                        }
                        else
                        // 2nd Column = dispFldName if processing a transaction 
                        {
                            dtRow[cCnt] = " ";
                            if (MyDisplaySeq.dispFldName != null)
                            {
                                dtRow[cCnt] = MyDisplaySeq.dispFldName;
                            }
                            cCnt = cCnt + 1;
                        }

                        // 3rd Column = dispIdx (Non display Column)                             
                        dtRow[cCnt] = " ";
                        if (MyDisplaySeq.dispIdx != null && MyDisplaySeq.dispIdx != "" && MyDisplaySeq.dispIdx != " ")
                        {
                            dtRow[cCnt] = MyDisplaySeq.dispIdx;
                        }
                        cCnt = cCnt + 1;

                        // 4th Column = dispKeyWord (Non display Column)    
                        dtRow[cCnt] = " ";
                        if (MyDisplaySeq.dispKeyWord != null && MyDisplaySeq.dispKeyWord != "" && MyDisplaySeq.dispKeyWord != " ")
                        {
                            dtRow[cCnt] = MyDisplaySeq.dispKeyWord;
                        }
                        cCnt = cCnt + 1;

                        // Add this row
                        dt.Rows.Add(dtRow);
                        cCnt = 0;           // Reset column count
                        rCnt = rCnt + 1;    // Increment row count
                        dtRow = dt.NewRow();

                    }
                }

                //
                // for Lists take the Gridview content from the returned dataset
                //

                if (MySessionLvlValues.whatAmI == "List")
                {
                    string myPath = "C:\\inetpub\\wwwroot\\" + MyRtnFromServiceParms.passedEnterpriseId + "\\" + MyRtnFromServiceParms.passedUserId + "_MyDispSeq2.txt";
                        rtnDataSet = CopyFileToDS(myPath);
                        rtnDataSetRowCnt = rtnDataSet.Tables[0].Rows.Count;
                        dt = rtnDataSet.Tables[0];
                }




                //
                // Display Transaction Variable values 
                //
                if (MySessionLvlValues.whatAmI == "Variables")
                {

                    // Acquire keys and sort them.
                    var sortedList = MyRtnFromServiceParms.MyVarValuesDict.Keys.ToList();
                    sortedList.Sort();

                    for (int cnt = 0; cnt < sortedList.Count(); cnt++) // Loop through Variable values Dictionary with for loop
                    {
                        var itemKey = sortedList.ElementAt(cnt);
                        var itemValue = " ";
                        if (MyRtnFromServiceParms.MyVarValuesDict.ContainsKey(itemKey))
                        {
                            itemValue = MyRtnFromServiceParms.MyVarValuesDict[itemKey];
                        }
                        // 1st Column = dictionary key
                        dtRow[cCnt] = itemKey;
                        cCnt = cCnt + 1;


                        // 2nd Column = dictionary Value
                        dtRow[cCnt] = itemValue;
                        cCnt = cCnt + 1;

                        // Add this row
                        dt.Rows.Add(dtRow);
                        cCnt = 0;           // Reset column count
                        rCnt = rCnt + 1;    // Increment row count
                        dtRow = dt.NewRow();
                    }
                }


                // Fill remainder of gridview with blanks of record < mininum required
                //for (int cnt = rCnt; cnt < minRowsRqd; cnt++) // Loop through Display Seq List with for loop
                //{
                //    dtRow[0] = " ";
                //    dtRow[1] = " ";
                //    dtRow[2] = " ";
                //    dtRow[3] = " ";
                //    dt.Rows.Add(dtRow);
                //    dtRow = dt.NewRow();
                //}

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        //
        // Set the display Headings for the Gridview
        //
        public void setDspHeadings()
        {
            string logSourceMethod = "setDspHeadings()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                //
                // if no heading records check if this is a menu (type="m")
                //

                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    //dt.Columns.Add("Opt");
                    dt.Columns.Add("Option");
                    dt.Columns.Add("Description");
                }
                else

                    if (MySessionLvlValues.whatAmI == "Transaction")
                {
                    dt.Columns.Add(MyRtnFromServiceParms.passedCurrentTransDesc);
                    dt.Columns.Add("Col2");
                }

                else
                        if (MySessionLvlValues.whatAmI == "Variables")
                {
                    dt.Columns.Add("Variable");
                    dt.Columns.Add("Current Value");

                }

                if (MySessionLvlValues.whatAmI != "List")
                {
                    dt.Columns.Add("Idx");          // Hidden index (left or Right)
                    dt.Columns.Add("Keyword");      // Hidden Keyword
                }
            }


            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        public void rmvDspRecords()
        {
            string logSourceMethod = "rmvDspRecords()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {

                //
                // This is being done in the Service at the processInput routine
                // (future - cater for subroutines by setting the display seq = line number subr called from) ***
                //

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void retrieveErrors()
        {
            string logSourceMethod = "retrieveErrors()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                errText = " ";
                TextBox1.Text = " ";
                TextBox1.BackColor = System.Drawing.Color.Green;
                TextBox1.Visible = false;

                for (int cnt = 0; cnt < MyErrorsEncounteredList.Count(); cnt++) // Loop through Error List with for loop
                {
                    //MyErrorsEncountered = MyRtnFromServiceParms.MyErrorsEncounteredList[cnt];
                    MyErrorsEncountered = MyErrorsEncounteredList[cnt];
                    if (string.IsNullOrWhiteSpace(MyErrorsEncountered.errorDescr))
                    {
                        MyErrorsEncountered.errorDescr = MyErrorsEncountered.errorDescr + " / " + MyErrorsEncountered.errorData;
                    }
                    errText = errText + MyErrorsEncountered.errorDescr + "\r\n";
                    TextBox1.Visible = true;
                    TextBox1.Text = errText;
                    TextBox1.BackColor = System.Drawing.Color.Red;
                    if (GridView1.FooterRow != null)
                    {
                        GridView1.FooterRow.BackColor = System.Drawing.Color.Red;
                    }
                    // If error encountered then go to previous input but retain error messages
                    if (MyPrevErrorsEncounteredList != null)
                    {
                        if (MyPrevErrorsEncounteredList.Count() > 0)
                        {
                            MyPassToServiceParms.passedCurSeq = prevSeq;
                            forwardDirection = false;  // Previous is going backwards
                            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;

                            // return previous transaction and transaction seq
                            //
                            // Get the number of transactions recorded in Prev array
                            //
                            int i = 0;
                            int num = 0;
                            for (i = 0; i < prevSeqArr.Count(); i++) // Loop through array
                            {
                                if (prevSeqArr[i] != " " ) //&& !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp2"))
                                {
                                    string type = prevSeqArr[i].Substring(0, 1);
                                    if (type == "t")
                                    {
                                        num++;
                                    }

                                }
                                else
                                    i = 201;
                            }
                            // Only go back to previous transaction line when one exists
                            only1TransLineExists = false;
                            if (num == 1)
                            {
                                only1TransLineExists = true;
                            }
                            RtnPrevTranAndSeq();

                            MyPassToServiceParms.passedCurrentTransId = prevTran;
                            MyPassToServiceParms.MyErrorsEncounteredList = MyRtnFromServiceParms.MyErrorsEncounteredList;
                            //
                            // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                            //
                            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                            {
                                MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                            }
                            processTransaction();

                        }
                    }
                }

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void retrievePromptMsgs()
        {
            string logSourceMethod = "retrievePromptMsgs()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                promptText = " ";

                // Only if nor errors (clientside or serverside) should we display prompts
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedPromptDescription) && clientSideError == false && serverSideError == false) // returned from service
                {
                    TextBox1.Visible = true;
                    TextBox1.Text = MyRtnFromServiceParms.passedPromptDescription;
                    promptText = MyRtnFromServiceParms.passedPromptDescription;
                    TextBox1.BackColor = System.Drawing.Color.Green;
                }

            }

            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void saveSessionParms()
        {
            string logSourceMethod = "saveSessionParms()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                // Save session parameters
                Session["returnParms"] = MyRtnFromServiceParms;
                Session["toParms"] = MyPassToServiceParms;
                Session["client"] = client;
                Session["dropDownList"] = dropDown;
                Session["dropDownList2"] = dropDown2;
                Session["previousSeqArray"] = prevSeqArr;
                Session["prevErrorsEncountered"] = MyPrevErrorsEncounteredList;
                Session["sessionLvlValues"] = MySessionLvlValues;

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }

        public void restoreSessionParms()
        {
            string logSourceMethod = "restoreSessionParms()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            try
            {
                // Restore Session parameters from previous screen 
                MyRtnFromServiceParms = (TiosServiceReference1.RtnFromServiceParms)Session["returnParms"];
                MyPassToServiceParms = (TiosServiceReference1.PassToServiceParms)Session["toParms"];
                client = (TiosServiceReference1.TransactionClient)Session["client"];
                dropDown = (string[])Session["dropDownList"];
                dropDown2 = (string[])Session["dropDownList2"];
                prevSeqArr = (string[])Session["previousSeqArray"];
                MyPrevErrorsEncounteredList = (List<TiosServiceReference1.ErrorsEncountered>)Session["prevErrorsEncountered"];
                MySessionLvlValues = (TiosServiceReference1.SessionLvlValues)Session["sessionLvlValues"];

            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

        }


        //
        // Convert dataset to xml string
        public static string Serialize(object obj)
        {
            string logSourceMethod = "callService()";
            using (MemoryStream memoryStream = new MemoryStream())
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
                serializer.WriteObject(memoryStream, obj);
                memoryStream.Position = 0;
                return reader.ReadToEnd();
            }
        }

        // Convert xml string back to obj
        public static object Deserialize(string xml, Type toType)
        {
            using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
                DataContractSerializer serializer = new DataContractSerializer(toType);
                return serializer.ReadObject(reader);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            string logSourceMethod = "OnPreRender()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            // 1. code put here will be executed first

            // now we call the base class' version, which will then raise the
            // PreRender event
            base.OnPreRender(e);

            // 3. code put here will be executed last
        }


        // Called when page has finished - cleanup here
        protected void Page_Unload(object sender, EventArgs e)
        {
            string logSourceMethod = "page_Unload()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
        }

        // DropDownList Changed
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string logSourceMethod = "DropDownList1_SelectedIndexChanged()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            MyPassToServiceParms.passedInpVal = ComboBox1.SelectedValue.Trim();

            ////
            //// If a value has been selected from the Dropdown List other than the defaulted one (index 0) then force Next
            ////
            //if (ComboBox1.SelectedIndex > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt")) 
            //{
            //    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
            //    {
            //        MyRtnFromServiceParms.passedClientKeywords = "clt-atoclknxt";
            //    } 
            //    else
            //        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";
            //}
        }


        //
        // Previous Button pressed
        //
        protected void Button1_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "Button1_Click(Previous)";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            //
            // If previously selected on a transaction which is the only transaction record in prevSeqArr 
            // Then remove this record from prevSeqArr to avoid the screen being re-displayed when previous selected.
            //
            int i = 0;
            int j = 0;
            int num = 0;
            for (i = 0; i < prevSeqArr.Count(); i++) // Loop through array
            {
                if (prevSeqArr[i] != " ")
                {
                    string type = prevSeqArr[i].Substring(0, 1);
                    if (type == "t")
                    {
                        num++;
                        j = i;

                    }

                }
                else
                    i = 201;
            }

            // Remove record when its the only existing transaction record && Overriding keyword "Clt-KepPrvArrVal" not present

            if (num == 1 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval"))
            {
                prevSeqArr[j] = " ";
            }

            ComboBox1.Visible = true;
            FileUpload1.Visible = false;
            forwardDirection = false;  // Previous is going backwards
            lblComboInfo.Text = MyRtnFromServiceParms.passedInpFldTxt;
            prevClicked = true;

            // return previous transaction and transaction seq
            RtnPrevTranAndSeq();
            MyPassToServiceParms.passedCurrentTransId = prevTran;

            processTransaction();
        }

        //
        // Next Button pressed
        //
        protected void Button2_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "Button2_Click(Next)";
            //MySessionLvlValues.dispVarRqd = false;
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            cancellationTokenSource.Cancel();  // Cancel any existing Pooling for barcoded transactions
            clientSideError = false;
            serverSideError = false;
            forwardDirection = true;
            nextClicked = true;

            // Test reflection
            string tempa = " ";
            if (tempa == "Y")
            {
                GetObjProperties(GridView1);
            }

            if (this.FileUpload1.HasFile)
                //{
                //    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
                //}

                //
                // If mandatory dropdown entry requireed then error if not in list
                //
                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-cpylsttoexl")) // copy contents of gridview List to Excel
                {

                    if (ComboBox1.SelectedValue.ToLower().Trim() == "y")
                    {
                        ExportToExcel(); // Export contents to Excel
                    }

                }

            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-dspfilupl")) // upload file from client to Server
            {

                if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrv"))  // Return DS from client to Service
                {
                    ImportFile(); // Import file from client to Server
                }

            }


            // Validate Prefix/ Suffix if specified on input

            int pfxLen = MyRtnFromServiceParms.passedBarcodePrefix.Length;
            int sfxLen = MyRtnFromServiceParms.passedBarcodeSuffix.Length;
            bool prefixSuffixRqd = true;
            if (MyRtnFromServiceParms.passedScanPfxSfxRequired.ToLower() != "y")
            {
                prefixSuffixRqd = false;
            }
            string barcodeSetting = MyRtnFromServiceParms.passedBarcodeSetting;

            MyPassToServiceParms.passedBarcodeScannedInput = false;

            //
            // Check for the existance of a scanned value in hiudden scan field
            //
            if (!String.IsNullOrWhiteSpace(hiddenScannedValue.Value))
            {
                string scannedValue = hiddenScannedValue.Value;
                int totLen = scannedValue.Length;
                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodePrefix))
                {
                    //
                    // Validate & Remove Prefix from value if existing
                    //
                    var pos = scannedValue.IndexOf(MyRtnFromServiceParms.passedBarcodePrefix);
                    if (pos == 0 && totLen > pfxLen)
                    {
                        scannedValue = scannedValue.Substring(pfxLen, (totLen - pfxLen)).Trim();
                    }
                    if (prefixSuffixRqd && pos != 0)
                    {

                        // If from mobile device 
                        string message = "This input field has a pre-defined Prefix which does not match the value entered. Please check that you have scanned the correct label ?";
                        if (mobileOrNonMobile.Value == "mobile")
                        {
                            ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                            clientSideError = true;
                        }
                        // non - mobile device
                        else
                        {
                            ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                            clientSideError = true;
                        }

                    }

                }


                if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodeSuffix))
                {
                    //
                    // Validate & Remove Suffix from value if existing
                    //
                    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedBarcodeSuffix) && clientSideError != true && serverSideError != true)
                    {
                        totLen = scannedValue.Length;
                        var pos = scannedValue.LastIndexOf(MyRtnFromServiceParms.passedBarcodeSuffix);
                        if (pos > 0 && totLen > sfxLen)
                        {
                            scannedValue = scannedValue.Substring(0, (totLen - sfxLen));
                        }
                        if (prefixSuffixRqd && pos < 0 || (pos + sfxLen) != totLen)
                        {

                            // If from mobile device 
                            string message = "This input field has a pre-defined Suffix which does not match the value entered. Please check that you have scanned the correct label ?!";
                            if (mobileOrNonMobile.Value == "mobile")
                            {
                                ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                                clientSideError = true;
                            }
                            // non-mobile device 
                            else
                            {
                                ClientScript.RegisterStartupScript(GetType(), "myId21", string.Format("GeneralErrorMsg('{0}');", message.Trim()), true);
                                clientSideError = true;
                            }

                        }
                    }
                }
                string returnedScannedValue = "";
                // Insert scanned value into ComboBox1
                ComboBox1.ClearSelection();
                ComboBox1.Dispose(); // required to clear previous values
                ComboBox1.Items.Clear();
                ComboBox1.Text = " ";
                MyPassToServiceParms.passedBiometricConfirmationSuccessful = false;
                MyPassToServiceParms.passedBarcodeScannedInput = false;

                // Biometric confirmation
                if (scannedValue.ToLower().Contains("[tiosbiometricconfirmation]"))
                {
                    MyPassToServiceParms.passedBiometricConfirmationSuccessful = true;
                    MyPassToServiceParms.passedBarcodeScannedInput = true;
                    // if clt-BioCfmTxt keyword exists then substitute text for "[TiosBiometricConfirmation]" 
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-biocfmtxt"))
                    {
                        returnedScannedValue = "Y";  // Change to be the character(s) after the keyword
                    }
                }

                // scanned barcode value
                if (scannedValue.ToLower().Contains("scannedtransaction2"))
                {
                    delimitedList1 = RtnDelimitedValues(scannedValue);
                    // Should be 5 values passed scannedtransaction2, enterpriseId, UserId, deviceId, scannedValue
                    if (delimitedList1.Count() == 5 && MyRtnFromServiceParms.passedEnterpriseId==delimitedList1[1] && MyRtnFromServiceParms.passedUserId == delimitedList1[2])
                    {
                        MyPassToServiceParms.passedBarcodeScannedInput = true;


                            returnedScannedValue = delimitedList1[4];  // element 4 is the value scanned
                    }
                }

                ComboBox1.Items.Add(returnedScannedValue);
                ComboBox1.Text = returnedScannedValue;
                ComboBox1.SelectedIndex = 0;
                
 
                if (MyRtnFromServiceParms != null)
                {
                    logText = "SCAN:: - scannedValue: " + scannedValue + "   returnedScannedValue: " + returnedScannedValue;
                    WriteLogDetails("Information", logText);
                }
                hiddenScannedValue.Value = "";  // Reset scanned value to blanks

            }




            //
            // If mandatory dropdown entry requireed then error if not in list
            //
            // TODO: ContainsClientKeyword was removed from the service?
            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-drpdwnman")) // Mandatory dropdown list selection required
            {
 
                bool AutoClickNext = MyRtnFromServiceParms.passedAtoClkNxtVal.ToLower().Split(',').Contains(TextBox2.Text.ToLower());
                logText = "****AUTOCLICKNEXT**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Trus/false: "+  AutoClickNext.ToString() +  "  passedAtoClkNxtVal: " + MyRtnFromServiceParms.passedAtoClkNxtVal.ToLower() + " TextBox2: " +TextBox2.Text.ToLower()+" *****";
                WriteLogDetails("Information", logText);
                if (AutoClickNext  && clientSideError==false && MySessionLvlValues.errorExists==false && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                {
                    if (string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + "clt-atoclknxt";
                    }
                    else
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";

                    logText = "****AUTOCLICKNEXT2**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Keywords: " + MyRtnFromServiceParms.passedClientKeywords +" *****";
                    WriteLogDetails("Information", logText);
                }

                int resultIndex = -1;
                if (dropDown != null)
                {
                    resultIndex = Array.IndexOf(dropDown, ComboBox1.SelectedValue.Trim());
                }
                if (resultIndex == -1)
                {
                    logText = "****AUTOCLICKNEXT3**** Transaction: " + MyRtnFromServiceParms.passedCurrentTransId + " Dropdown: " + dropDown + "Selected Value: "+ ComboBox1.SelectedValue.Trim()+" * ****";
                    WriteLogDetails("Information", logText);
                    ClientScript.RegisterStartupScript(GetType(), "myId1", "chkAgainstDropdownList();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }

            //
            // TEST Look for changes in ComboBox1 dropdownlist
            //
            if (testDropdown == true)
            {
                ClientScript.RegisterStartupScript(GetType(), "myId7", "ComboBox1_Check();", true);
            }

            //
            // If mandatory entry (ie Non Blank) then validate via Javascript
            //

            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-manent")) // non blank entry required
            {

                if (ComboBox1.SelectedValue == "" || ComboBox1.SelectedValue == " ")
                {
                    ClientScript.RegisterStartupScript(GetType(), "myId2", "mandatoryEntry();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }


            //
            // If email format required then check for existance of '@' via Javascript
            //
            // TODO: ContainsClientKeyword was removed from the service?
            if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-emlfmt")) // email address format required
            {

                if (!ComboBox1.SelectedValue.Contains("@") && ComboBox1.SelectedValue != "" && ComboBox1.SelectedValue != " ")
                {

                    ClientScript.RegisterStartupScript(GetType(), "myId3", "emailFormatRqd();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }



            //
            // If input value is numeric then validate that value is numeric via Javascript
            //
            if (MyRtnFromServiceParms.passedInpFldTyp.ToLower() == "n") // Numeric
            {
                string myValue = ComboBox1.SelectedValue.Trim();
                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    myValue = myValue.Replace(".", "");         // Remove '.' from menu option
                }


                bool isNumeric = myValue.All(char.IsDigit);
                if (!isNumeric)
                {
                    var type = GetType();
                    ClientScript.RegisterStartupScript(GetType(), "myId4", "numericRqd();", true);
                    clientSideError = true;
                    //
                    // If clt-atoclknxt exists for transaction in error then remove (to prevent looping)
                    //
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                    {
                        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords.Replace("clt-atoclknxt", ""); // Remove 'clt-atoclknxt' from client keywords
                    }
                }
            }
            // If no client side errors then return input and process next transaction via Javascript
            if (!clientSideError)
            {
                processTransaction();
            }


            if (MySessionLvlValues.dspFileUploadCtl == true)
            {
                FileUpload fileUpload1 = new FileUpload();
                FileUpload1.Visible = true;
                ComboBox1.Visible = false;
                MySessionLvlValues.dspFileUploadCtl = false;
                FileUpload1.Dispose();
            }
        }

        protected void TextBox1_TextChanged1(object sender, EventArgs e)
        {

        }

        //*************************************************************************
        //                  BUILDING THE GRIDVIEW
        // This will trigger for each row that is bound to the gridview
        //*************************************************************************
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string logSourceMethod = "GridView1_RowDataBound()";

            // This will highlist the gridview rows when cursor on positioned on them
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
            e.Row.ToolTip = "<Click> to select this row.";

            // e.Row.Attributes["onmouseover"] = "onMouseOver('" + (e.Row.RowIndex + 1) + "')";
            // e.Row.Attributes["onmouseout"] = "onMouseOut('" + (e.Row.RowIndex + 1) + "')";


            gVRowCnt = e.Row.Cells.Count;
            string gVRowName = " ";
            gVColCnt = dt.Columns.Count;
            int dtColCnt = dt.Columns.Count;
            int dispSeqCnt = MyRtnFromServiceParms.MyDispSeqList.Count();
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.Footer)
            {
                //
                // Format how menu's should appear
                //
                if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "Variables")
                {
                    e.Row.Cells[1].Width = 50;
                    e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                    e.Row.Cells[2].Width = 300;
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
                    e.Row.Height = 40;
                    GridView1.GridLines = GridLines.None;
                }



                if (MySessionLvlValues.whatAmI == "List")
                {

                    GridView1.GridLines = GridLines.Both;

                }
                if (MySessionLvlValues.whatAmI != "List")
                {

                    GridView1.GridLines = GridLines.None;

                }
                //if (MySessionLvlValues.whatAmI == "List" || MySessionLvlValues.whatAmI == "Transaction")
                //{
                //    GridView1.GridLines = GridLines.None;
                //    try
                //    {


                //        for (int i = 0; i < gVColCnt; i++)
                //        {
                //            // Set the column widths based on maxColWidth array
                //            //

                //            if (i > 0)
                //            {
                //                // Colomn width
                //                e.Row.Cells[i].Width = maxColWidthArray[i - 1] * 30;
                //                e.Row.Cells[i].Wrap = false;

                //                // Row Height
                //                e.Row.Height = rowHeightArray[i - 1];
                //            }
                //        }
                //    }

                //    catch (Exception ex)
                //    {

                //    }
                //}


                //
                // START OF HEADER ============================================================================
                //
                if (e.Row.RowType == DataControlRowType.Header)  // Header record
                {

                    for (int i = 0; i < gVRowCnt; i++)
                    {

                        gVRowName = e.Row.Cells[i].Text;
                        switch (gVRowName)
                        {
                            case "Idx": // Index
                                idxCol = i;
                                break;
                            case "Keyword": // Index
                                kwdCol = i;
                                break;

                        }

                        // Remove all headings except 1st one for Transactions
                        if (MySessionLvlValues.whatAmI == "Transaction" && i > 1)
                        {
                            e.Row.Cells[i].Text = "";
                        }

                        //GrdVieiw1.Rows[i].Height = rowHeightArray[i + 1];

                    }

                    //
                    // Merge columns 1 & 2 in Header for Transactions 
                    //

                    //if (MySessionLvlValues.whatAmI == "Transaction")
                    //{
                    //    e.Row.Cells[1].RowSpan = 1;  // Unable to Merge using =2 !!!!
                    //}
                }

                //
                // END OF HEADER ==============================================================================
                //


                // HEADER/FOOTER/DETAIL

                // For unknown reason when table datasource contains n fields, the Gridview is created with n+1 
                // columns with the extra BLANK column in 1st position. Below we are making this row non visible

                e.Row.Cells[0].Visible = false; // Extra 1st column set to non display

                // Make rows 3 & 4 invisable (keyword index & Keyword) when not displaying a LIST
                if (gVRowCnt >= idxCol && MySessionLvlValues.whatAmI != "List")
                {
                    e.Row.Cells[idxCol].Visible = false;
                    e.Row.Cells[kwdCol].Visible = false;
                }
            }

            //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.Cells[kwdCol].Text != " ")
            //{

            //    ProcessGVKeywords(e.Row.Cells[kwdCol].Text.ToLower(), e.Row.Cells[idxCol].Text.ToLower(), e);  // Process ClientSide Keywords
            //}



            //
            // START OF FOOTER ==============================================================================
            //

            if (e.Row.RowType == DataControlRowType.Footer)   // Footer record
            {

                e.Row.Cells.Clear();
                TableCell tableCell = new TableCell();
                tableCell.Font.Bold = true;
                tableCell.HorizontalAlign = HorizontalAlign.Left;
                if (errText != " ")
                {
                    tableCell.Text = errText;
                    tableCell.BackColor = System.Drawing.Color.Red;
                }
                else
                    if (promptText != " ")
                {
                    tableCell.Text = promptText;
                    tableCell.BackColor = System.Drawing.Color.Green;
                }
            }
            //
            // END OF FOOTER ================================================================================
            //

        }

        //**************************************************************************************
        //                       GRIDVIEW BUILD  ABOVE /\
        //**************************************************************************************



        //
        // Fires when Gridview row is clicked
        //

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string logSourceMethod = "GridView1_SelectedIndexChanged()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            if (GridView1.SelectedIndex >= 0)
            {
                foreach (GridViewRow row in GridView1.Rows)
                {

                    if (row.RowIndex == GridView1.SelectedIndex)
                    {
                        if (GridView1.SelectedIndex < 0)
                        //if (GridView1.SelectedIndex < 0)
                        {
                            return;
                        }

                        //row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
                        row.ToolTip = string.Empty;
                        string ComboValue = GridView1.SelectedRow.Cells[1].Text;
                        if (MySessionLvlValues.whatAmI == "Menu")
                        {
                            ComboValue = ComboValue.Replace(".", "");         // Remove '.' from menu option
                        }
                        ComboValue = ComboValue.Trim();                       // Trim leading and trailing spaces
                        ComboBox1.Items.Add(ComboValue);
                        ComboBox1.SelectedValue = ComboValue.Trim();
                        ComboBox1.Text = ComboValue.Trim();
                        GridView1.SelectedIndex = -1;
                        //
                        // Only act as though Next Clicked when user clicks on a menu or a list
                        //
                        if (MySessionLvlValues.whatAmI == "Menu" || MySessionLvlValues.whatAmI == "List")
                        {
                            Button2_Click(null, new EventArgs());  // Click Next
                        }
                    }

                    else
                    {
                        //row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
                        row.ToolTip = "Click to select this row.";
                    }
                }
            }
        }

        protected void ComboBox1_SelectedIndexChanged4(object sender, EventArgs e)
        {
            string logSourceMethod = "ComboBox1_SelectedIndexChanged4()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            ////
            //// If a value has been selected from the Dropdown List other than the defaulted one (index 0) then force Next
            ////
            //if (ComboBox1.SelectedIndex > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
            //{
            //    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedClientKeywords))
            //    {
            //        MyRtnFromServiceParms.passedClientKeywords = "clt-atoclknxt";
            //    }
            //    else
            //        MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + ",clt-atoclknxt";
            //}
        }


        //
        // It is critical for the client to know exactly where in the transaction you are currently positioned. Selection of "Prev" can result in
        // moving to the previous input field or back to previous transaction or menu. The 'prevSeqArr' array will keep track of where we are.
        //
        public void UpdatePreviousTransactions()
        {
            string logSourceMethod = "UpdatePreviousTransactions()";
            MySessionLvlValues.dispVarRqd = false;
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            int i = 0;
            int j = 0;
            string blankValu = " ";
            string arrValue = MyRtnFromServiceParms.passedCurrentTransType + "," + MyPassToServiceParms.passedCurrentTransId + "," + MyPassToServiceParms.passedCurSeq;
            string arrValue2 = MyRtnFromServiceParms.passedCurrentTransType + "," + MyPassToServiceParms.passedCurrentTransId;

            //
            // If not going forward (ie Previous selected) then back out last transaction
            //
            if (forwardDirection == false)
            {
                // Find the next available Blank array element        
                j = 0;
                blankValu = " ";
                j = Array.IndexOf(prevSeqArr, arrValue);
                if (j != -1 && only1TransLineExists == false && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt"))
                {
                    // clt-kepprvarrval is used where the same input line is used in a loop and you dont want to remove it on PREV
                    if (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval"))
                    {
                        prevSeqArr[j] = " ";
                    }
                }

                //
                // If transactions and Current Seq < last entry in prevSeqArr then remove entries in
                // prevSeqArr that are either ahead or equal the current sequence.
                //
                if (MySessionLvlValues.whatAmI == "Transaction")
                {
                    string curTransName = "t," + MyRtnFromServiceParms.passedCurrentTransId;
                    int curTranSeq = MyRtnFromServiceParms.passedCurSeq;
                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        if (prevSeqArr[i].Contains(curTransName))
                        {
                            delimitedList1 = RtnDelimitedValues(prevSeqArr[i]);
                            prevSeq = 0;
                            bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                            if (prevSeq >= curTranSeq)
                            {
                                    // clt-kepprvarrval is used where the same input line is used in a loop and you dont want to remove it on PREV
                                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-kepprvarrval") && prevSeq==curTranSeq )
                                    {
                                       // Do nothing
                                    }
                                    else
                                        prevSeqArr[i] = " ";
                                }
                        }

                    }

                }

            }
            else
            {
                //Update previous transactions
                //

                // If this transaction is a menu then clear down all previous transactions details
                if (MySessionLvlValues.whatAmI == "Menu")
                {
                    string lastMenuEntry = " ";
                    string lastMenuName = " ";
                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        // Save the last Menu entry in the array
                        if (prevSeqArr[i].Contains("m,"))
                        {
                            lastMenuEntry = prevSeqArr[i];
                        }

                        // If this transaction is a Menu then remove all transactions from array
                        if (prevSeqArr[i].Contains("t,"))
                        {
                            prevSeqArr[i] = " ";
                        }
                        else
                        if (prevSeqArr[i] == " ")
                        {
                            i = 200; ;
                        }
                    }
                    // Store name of Last menu entry if existing
                    if (!string.IsNullOrWhiteSpace(lastMenuEntry))
                    {
                        delimitedList1 = RtnDelimitedValues(lastMenuEntry);
                        lastMenuName = delimitedList1[1];
                    }

                    // Find the next available Blank array element        
                    j = 0;
                    blankValu = " ";
                    j = Array.IndexOf(prevSeqArr, blankValu);
                    if (j != -1)
                    {
                        // If already exists then do not write again
                        int k = j - 1;

                        if (k < 0)
                        {
                            k = 0;
                        }


                        if (!prevSeqArr[k].Contains(arrValue2))
                        {
                            prevSeqArr[j] = arrValue;
                        }
                    }

                }
                // If this transaction is a Transaction 
                if (MySessionLvlValues.whatAmI == "Transaction")
                {

                    // Only proceed if this transactions sequence has not already been recorded
                    j = 0;
                    j = Array.IndexOf(prevSeqArr, arrValue);


                    for (i = 0; i < 200; i++) // Loop through array
                    {
                        if (prevSeqArr[i].Contains("t,") && !prevSeqArr[i].Contains(arrValue2) || i >= j && j != -1)  // If array holds a different transaction then remove
                        {                                                                                         // If entry alreay exists then remove all below this  
                            prevSeqArr[i] = " ";
                        }
                        else
                            if (prevSeqArr[i] == " ")
                        {
                            i = 200; ;
                        }
                    }

                    //
                    // set up the current seq in prev seq array                    
                    //
                    if (forwardDirection == true)
                    {
                        j = 0;
                        j = Array.IndexOf(prevSeqArr, blankValu);
                        if (j != -1 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp"))
                        {
                            prevSeqArr[j] = arrValue;
                        }
                    }

                }

                //
                // Set the previous transactions and seq
                //
                // Find the next available Blank array element        
                j = 0;
                j = Array.IndexOf(prevSeqArr, blankValu);
                if (j > 0 && !MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-ignprvinp"))
                {
                    arrValue = prevSeqArr[j - 1];
                }
                delimitedList1 = RtnDelimitedValues(arrValue);
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                if (prevType != "m")
                {
                    bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                }
            }
        }

        // Return delimited values
        public String[] RtnDelimitedValues(string inValue)
        {
            string logSourceMethod = "RtnDelimitedValues()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            string[] dList = new string[100];
            try
            {
                if (inValue == null)
                {
                    inValue = " ";
                }
                dList = inValue.Split(',');
                // check if value is a field     
            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                    WriteLogDetails("Error", logText);
                }
            }

            //return delimitedList;
            return dList;
        }

        //
        // Return previous transaction & ssequence
        //
        public void RtnPrevTranAndSeq()
        {
            string logSourceMethod = "RtnPrevTranAndSeq()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            // default exist transaction
            bool gotoHomePage = false;
            prevTran = MyRtnFromServiceParms.passedCurrentTransId;
            prevSeq = MyPassToServiceParms.passedCurSeq;
            //
            // Determine what the previous transaction and seq No was
            //
            string blankValu = " ";
            string arrValue = " ";
            int j = 0;
            j = Array.IndexOf(prevSeqArr, blankValu);
            if (j > 0)
            {
                arrValue = prevSeqArr[j - 1];
            }
            else
                arrValue = prevSeqArr[0];

            delimitedList1 = RtnDelimitedValues(arrValue);

            // 
            // If j=0 then previous will take us back to home page
            // 
            if (j == 0)
            {
                gotoHomePage = true;
            }

            if (delimitedList1.Count() > 0 && (!string.IsNullOrWhiteSpace(delimitedList1[0])))
            {
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                // If menu then jump back 1
                if (prevType == "m" && j > 0)
                {

                    arrValue = prevSeqArr[j - 1];
                    prevSeqArr[j - 1] = " ";
                }

                delimitedList1 = RtnDelimitedValues(arrValue);
                prevType = delimitedList1[0];
                prevTran = delimitedList1[1];
                prevSeq = 0;
                if (prevType != "m")
                {
                    bool result = int.TryParse(delimitedList1[2].ToString(), out prevSeq);
                }
            }
            MyPassToServiceParms.passedCurrentTransId = prevTran;
            MyPassToServiceParms.passedCurSeq = prevSeq;

            // 
            // If prevSeqArr[0] is blanks then take us back to home page
            // 
            if (string.IsNullOrWhiteSpace(prevSeqArr[0]) && string.IsNullOrWhiteSpace(prevTran))
            {
                gotoHomePage = true;
            }


            if (gotoHomePage || MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-logout"))
            {
                gotoHomePage = false;
                Response.Redirect("~/Default.aspx", true);
            }

        }

        //
        // Load the Transaction view 
        //

        protected void Show_Transaction(object sender, EventArgs e)
        {
            string logSourceMethod = "Show_Transaction()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            if (MySessionLvlValues.displayVariables == true)
            {
                MySessionLvlValues.displayVariables = false;
                if (dispIsAMenu)
                {
                    MySessionLvlValues.whatAmI = "Menu";
                }
                else
                    MySessionLvlValues.whatAmI = "Transaction";


                if (MySessionLvlValues.displayList == true)
                {
                    MySessionLvlValues.whatAmI = "List";
                }
            }

            processRtnDisp();
            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            SetColWidthRowHeight();
            GridView1.DataBind();


            saveSessionParms();  // save Session parameters from this call
        }

        // Show the Variables view

        protected void Show_Variables(object sender, EventArgs e)
        {
            string logSourceMethod = "Show_Variables()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            MySessionLvlValues.displayVariables = true;
            MySessionLvlValues.whatAmI = "Variables";

            processRtnDisp();
            //now since you have your datasource,bind it to the grid
            //GridView1.RowStyle.Height = 50;
            GridView1.DataSource = dt;
            tblColCnt = dt.Columns.Count;
            tblRowCnt = dt.Rows.Count;
            //SetColWidthRowHeight();
            GridView1.DataBind();


            if (dispIsAMenu)
            {
                //string colWidth = GridView1.Columns[0].ItemStyle.Width.Value.ToString();
                //GridView1.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Left;

            }
            saveSessionParms();  // save Session parameters from this call
        }


        //
        // Set default Column width & Row Height for Gridview
        //
        public void SetColWidthRowHeight()
        {
            string logSourceMethod = "SetColWidthRowHeight()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            maxColWidthArray = new int[tblColCnt]; // based on field lengths in each column
            colWidthArray = new int[tblColCnt]; // based on user override
            rowHeightArray = new int[tblColCnt];// based on user override
            for (int x = 0; x < tblColCnt; x++)
            {
                colWidthArray[x] = dftColWidth;
                maxColWidthArray[x] = 0;
            }

            //
            // get with actual size of longest text in each column
            //

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    String cellText = row[i].ToString();
                    int maxColLen = cellText.Length;
                    // Replace Max Col Length with widest
                    if (maxColLen > maxColWidthArray[i])
                    {
                        maxColWidthArray[i] = maxColLen;

                    }
                }
            }

            //
            // Now default the Row Heights
            //
            for (int x = 0; x < tblColCnt; x++)
            {
                rowHeightArray[x] = dftRowHeight;
            }
        }

        //
        // Export transaction to excel
        //
        protected void ExportToExcel()
        {
            string logSourceMethod = "ExportToExcel()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                //To Export all pages
                GridView1.AllowPaging = false;

                GridView1.RenderControl(hw);
                //style to format numbers to string
                string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }
        //
        // Export transaction to excel
        //
        protected void ImportFile()
        {
            string logSourceMethod = "ImportFle()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            string Username1 = User.Identity.Name;

 
            if (this.FileUpload1.HasFile)
            {
                try
                {
                    string logonName2 = Environment.UserName;

                    string uploadPath1 = MapPath("~/" + MyRtnFromServiceParms.passedEnterpriseId); // Default

                    // If you want to upload the file to somewhere other than root directory + enterprise then use "MyRtnFromServiceParms.passedToFileLoc"
                    if (!string.IsNullOrWhiteSpace(MyRtnFromServiceParms.passedToFileLoc))
                    {
                        uploadPath1 = MyRtnFromServiceParms.passedToFileLoc;
                    }

                    if (!Directory.Exists(uploadPath1))
                    {
                        Directory.CreateDirectory(uploadPath1);
                        DirectorySecurity sec = Directory.GetAccessControl(uploadPath1);
                        // Using this instead of the "Everyone" string means we work on non-English systems.
                        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        Directory.SetAccessControl(uploadPath1, sec);

                    }


                    //determine if file exist
                    //string uploadPath1 = Server.MapPath(Path.Combine("~/" + MyRtnFromServiceParms.passedEnterpriseId + "/", FileUpload1.FileName));
                    if (MyRtnFromServiceParms != null)
                    {
                        logText = "IMPORT - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   importing file:" + uploadPath1 + "/" + FileUpload1.FileName;
                        WriteLogDetails("Information", logText);
                    }

                    if (File.Exists(uploadPath1 + "\\" + FileUpload1.FileName))
                    {
                        try
                        {
                            //delete existing file
                            File.Delete(uploadPath1 + "\\" + FileUpload1.FileName);
                            logText = "DELETE - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   importing file:" + uploadPath1 + "/" + FileUpload1.FileName;
                            WriteLogDetails("Information", logText);
                        }
                        catch (Exception ex)
                        {
                            if (MyRtnFromServiceParms != null)
                            {
                                logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                                WriteLogDetails("Error", logText);
                            }
                        }
                    }
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsdtetim"))  // Return DS plus datetime appended from client to Service
                    {
                        var curdatetime = System.DateTime.Now.ToString("yyMMdd HHmmss");
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");             // Remove extension from filename
                        saveAsName = saveAsName+ "_"+curdatetime;                   // append current datetime
                        saveAsName = saveAsName + Extension;                        // re-append extension
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsdte"))  // Return DS plus datetime appended from client to Service
                    {
                        var curdate = System.DateTime.Now.Date.ToString("yyMMdd");
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");             // Remove extension from filename
                        saveAsName = saveAsName + "_"+ curdate;                     // append current datetime
                        saveAsName = saveAsName + Extension;                        // re-append extension
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    if (MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-rtndstosrvplsusr"))  // Return DS plus userId appended from client to Service
                    {
                        
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        string saveAsName = FileUpload1.FileName;
                        saveAsName = saveAsName.Replace(Extension, "");                      // Remove extension from filename
                        saveAsName = saveAsName + "_"+ MyRtnFromServiceParms.passedUserId;   // append current datetime
                        saveAsName = saveAsName + Extension;                                 // re-append extension
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + saveAsName);
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + saveAsName);
                        ComboBox1.SelectedValue = saveAsName.Trim();
                    }
                    else
                    {
                        FileUpload1.PostedFile.SaveAs(uploadPath1 + "\\" + FileUpload1.FileName);
                        MyPassToServiceParms.passedLastUploadedFilePath = (uploadPath1 + "\\" + FileUpload1.FileName);
                        string FileName = Path.GetFileName(FileUpload1.FileName);
                        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string FilePath = uploadPath1;
                        ComboBox1.SelectedValue = FileName.Trim();
                    }


                    //FileName = Path.GetFileName(FileUpload1.FileName);
                    //Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                    //FilePath = uploadPath1;
                    //ComboBox1.SelectedValue = FileName.Trim();



                    try
                    {
                        //FileUpload1.PostedFile.SaveAs(FilePath);
                    }
                    catch (Exception ex)
                    {
                        //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                        if (MyRtnFromServiceParms != null)
                        {
                            logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                            WriteLogDetails("Error", logText);
                        }


                    }
                    // Test1 - read through uploaded file
                    //string line = " ";
                    //var csvData = Encoding.UTF8.GetString(FileUpload1.FileBytes);

                    //using (var reader = new StringReader(csvData))
                    //{
                    //    var headers = reader.ReadLine().Split(',');
                    //    while ((line = reader.ReadLine()) != null)
                    //    {
                    //        var fields = line.Split(',');
                    //    }
                    //}

                    // Test1 end

                    // Test2  Serialize contents of uploaded data table
                    //dt = ConvertCSVtoDataTable(FilePath);
                    //dt.TableName = "myTable";
                    //DataSet ds = new DataSet();
                    //ds.Merge(dt);
                    //MyPassToServiceParms.passedDs3XmlString = Serialize(ds);
                    //MyGlobals.logger2.Information("ds3XmlString: {ds3xmlstring} ", MyPassToServiceParms.passedDs3XmlString);
                    // Test2



                }
                catch (Exception ex)
                {
                    //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                    if (MyRtnFromServiceParms != null)
                    {
                        logText = "ERROR- EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   error:" + ex;
                        WriteLogDetails("Error", logText);
                    }

                }
                finally
                {
                    FileUpload1.PostedFile.InputStream.Dispose();
                    FileUpload1.PostedFile.InputStream.Flush();
                    FileUpload1.PostedFile.InputStream.Close();
                    FileUpload1.FileContent.Dispose();
                    FileUpload1.PostedFile.InputStream.Dispose();
                    FileUpload1.Dispose();              // This is required to remove IIS lock on uploaded file
                    //GC.Collect();
                    //GC.WaitForPendingFinalizers(); CAUSING APPLICATION TO HANG!!!!

                    //Release File from Memory after uploading
                }
            }

        }


        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        public static DataTable ConvertCSVtoDataTable(string strFilePath)
        {

            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }


            return dt;
        }


        public void GetObjProperties(object MyObj)
        {
            string logSourceMethod = "GetObjProperties()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Type MyType = GridView1.GetType();
            PropertyInfo[] properties = MyType.GetProperties();
            FieldInfo[] fields = MyType.GetFields();
            foreach (PropertyInfo property in properties)
            {
                var type = " Type: " + property.PropertyType.Name + " Name: " + property.Name + " Value: " + property.GetValue(GridView1, null);
                var valu = " Value: " + property.GetValue(GridView1, null);
            }
            foreach (FieldInfo field in fields)
            {
                var type = " Type: " + field.FieldType.Name + " Name: " + field.Name + " Value: " + field.GetValue(GridView1);
                var valu = " Value: " + field.GetValue(GridView1);
            }
        }

        protected void btnMobileAppRegistration_Click(object sender, EventArgs e)
        {
            string logSourceMethod = "btnMobileAppRegistration()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Response.Redirect("~/MobileRegister.aspx");
        }

        public String GetMobileSessionID
        {
            get
            {
                return String.Format(
                    "{0}/{1}/{2}",
                    MyRtnFromServiceParms.passedUserCompanyName,
                    MyRtnFromServiceParms.passedUserName,
                    MyRtnFromServiceParms.passedUserId);
            }
        }


        public void CheckForScannedTransactions()
        {
            string logSourceMethod = "CheckForScannedTransactions()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            BGJobParms MyBGJobParms = new BGJobParms();
            MyBGJobParms.BGJobName = "BGJOB01";
            MyBGJobParms.BGJobDescription = "Check for Barcode Scanned Transactions";
            MyBGJobParms.BGJobThreadName = "TiosClientBackgroundWorkerThread";
            MyBGJobParms.BGJobAction = "loop";
            MyBGJobParms.BGJobMaxRunSeconds = 20; // Max Time nn seconds
            MyBGJobParms.BGJobDelaySeconds = 2;   // 2 second
            MyBGJobParms.BGJobReportProgress = false;
            MyBGJobParms.BGJobParm1 = MyRtnFromServiceParms.passedEnterpriseId;
            MyBGJobParms.BGJobParm2 = MyRtnFromServiceParms.passedUserId;
            MyBGJobParms.BGJobTransName = MyRtnFromServiceParms.passedCurrentTransId;
            MyBGJobParms.BGJobTransSeq = MyRtnFromServiceParms.passedCurSeq;
            BGWorker MyBGWorker = new BGWorker();

            //Pass BGWorker & BGWorker Parameters to Background job 
            MyBGWorker.ReceiveMyBGWorker(MyBGWorker);
            MyBGWorker.ReceiveMyBGJobParms(MyBGJobParms);

            // Pass MyWebForm1 to Background job to enable call back with results 
            WebForm1 MyWebForm1 = HttpContext.Current.Handler as WebForm1;
            MyBGWorker.ReceiveMyWebForm1(MyWebForm1);

            // Call Background Job
            Debug.WriteLine("INT - Prior to call to StartBackgroundProcess: " + DateTime.Now);

            MyBGWorker.StartBackgroundProcess(MyBGJobParms);
            Debug.WriteLine("INT - Returned from call to StartBackgroundProcess: " + DateTime.Now);
        }


        public void UpdateComboBoxWithScannedValue(string scanValue)
        {
            string logSourceMethod = "UpdateComboBoxWithScannedValue()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            Debug.WriteLine("INT - In UpdateComboBoxWithScannedValue: " + DateTime.Now);
            ComboBox1.Items.Add(scanValue.Trim());
            if (!String.IsNullOrEmpty(scanValue))
            {
                ComboBox1.Items.Add(scanValue.Trim());
                ComboBox1.SelectedIndex = 0;
                Debug.WriteLine("INT - In UpdateComboBox Value with: " + scanValue + "  " + DateTime.Now);
            }
            if (!MyRtnFromServiceParms.passedClientKeywords.ToLower().Contains("clt-atoclknxt")) // Auto Click Next after successful scan
            {
                Debug.WriteLine("INT - Adding clt-AtoClkNxt keyword: " + DateTime.Now);
                // HOLD OFF UNTIL TESTED MyRtnFromServiceParms.passedClientKeywords = MyRtnFromServiceParms.passedClientKeywords + "clt-atoclknxt";
            }

            // ClientScript.RegisterStartupScript(GetType(), "myId996", "RefreshPage();", true);   

        }

        public void CheckForScannedTransactions2()
        {
            string logSourceMethod = "CheckForScannedTransactions2()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }
            int delay = 2000;
            cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;
            var listener = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    CheckForScannedTransactions();
                    Thread.Sleep(delay);
                    if (token.IsCancellationRequested)
                        break;
                }

                //cleanup
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith((prevTask) =>
            {

            });
        }

        public void CheckForScannedTransactionsOrig(string passedEnterpriseId, string passedUserId)
        {
            string logSourceMethod = "CheckForScannedTransactionsOrig()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            bool found = false;
            string bcReturnedValue = "";
           TiosServiceReference1.TransactionClient client2 = new TiosServiceReference1.TransactionClient();
            DateTime curDateTime = DateTime.Now;
            int delay = 1;
            cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;
            var listener = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    // Do polling here
                    if (!String.IsNullOrEmpty(ComboBox1.SelectedValue) && ComboBox1.SelectedValue != " " || forwardDirection == false)
                    {
                        cancellationTokenSource.Cancel();
                    }
                    else
                    {

                        bcReturnedValue = client2.RetrieveLastScannedValue(passedEnterpriseId, passedUserId, curDateTime);
                        if (!String.IsNullOrEmpty(bcReturnedValue) && bcReturnedValue != "[EMPTY]")
                        {
                            //ComboBox1.Items.Add(bcReturnedValue.Trim());
                            // ComboBox1.Text = "SCANNED VALUE";
                            //ComboBox1.SelectedIndex = 0;
                            found = true;

                            // ClientScript.RegisterStartupScript(GetType(), "myId995", string.Format("SetComboBoxValue('{0}');", bcReturnedValue.Trim()), true);
                            cancellationTokenSource.Cancel();  // Value found - Cancel polling for value
                        }
                    }

                    Thread.Sleep(delay);
                    if (token.IsCancellationRequested)
                        break;
                }

                //cleanup
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith((prevTask) =>
            {
                if (found == true)
                {
                    ClientScript.RegisterStartupScript(GetType(), "myId995", string.Format("SetComboBoxValue('{0}');", bcReturnedValue.Trim()), true);
                }
            });
        }

        // Test SignalR
        public void AnnounceAll(string message)
        {
            string logSourceMethod = "AnnounceAll()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "SCANNED DATA EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Scanned Data: " + message;
                WriteLogDetails("Information", logText);
            }
            else
            {
                logText = "SCANNED DATA: " + message;
                WriteLogDetails("Information", logText);
            }
            string msg = message;
        }
        public void AnnounceUser(string message)
        {
            string logSourceMethod = "AnnounceUser()";
            if (MyRtnFromServiceParms != null)
            {
                logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   In this Method";
                WriteLogDetails("Verbose", logText);
            }

            string msg = message;
        }
        
        
        // Copy file to DataSet 
        public DataSet CopyFileToDS(string filePath)
        {
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            // 
            // read text file into DS
            // 
            try
            {
                string line;
                int counter = 0;
                using (StreamReader sr = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string Value = line;
                        delimitedList1 = RtnDelimitedValues(Value);
                        if (counter == 0)
                        {
                            for(int i=0;i<delimitedList1.Count();i++)
                            {
                                dt.Columns.Add(delimitedList1[i], typeof(String));
                            }
                        }
                        else
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < delimitedList1.Count(); i++)
                            {
                                dr[i] = delimitedList1[i];
                            }
                            dt.Rows.Add(dr);
                        }
                        counter++;
                    }
                }
                ds.Tables.Add(dt);
                return ds;
            }
         
            catch (Exception ex)
            {
                logText = "Error Reading _MyDispSeq2 file - EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Client Keywords:" + MyRtnFromServiceParms.passedClientKeywords + "error: " + ex.ToString();
                WriteLogDetails("Error", logText);
                return ds;
            }
        }


        //Write to Serilog Logger
        public void WriteLogDetails(string logtype, string logText)
        {
            logSourceMethod = "WriteLogDetails";

            bool activateLoggingForUser = false;
            try
            {
                if (MyGlobals.logger2 == null)
                {
                    MyGlobals.logger2 = new LoggerConfiguration()
                   .ReadFrom.AppSettings()
                   .CreateLogger();
                    Log.Logger = MyGlobals.logger2;
                }

                if (!String.IsNullOrEmpty(MyRtnFromServiceParms.passedUserId))
                {
                    if (MyRtnFromServiceParms.passedActivateLoggingForUser.ToLower() == "y")
                    {
                        activateLoggingForUser = true;
                    }
                }
                // Check if logging required globally or for user
                string globalLogging = ConfigurationManager.AppSettings.Get("switch on global logging");

                if (activateLoggingForUser == true || globalLogging.ToLower() == "true")
                {
                    MyGlobals.loggingRequired = true;
                }


                if (MyGlobals.loggingRequired)
                {
                    // substitute field names for actual values


                    switch (logtype.ToLower())
                    {
                        case ("verbose"):
                            MyGlobals.logger2.Verbose(logText);
                            break;
                        case ("debug"):
                            MyGlobals.logger2.Debug(logText);
                            break;
                        case ("information"):
                            MyGlobals.logger2.Information(logText);
                            break;
                        case ("warning"):
                            MyGlobals.logger2.Warning(logText);
                            break;
                        case ("error"):
                            MyGlobals.logger2.Error(logText);
                            break;
                        default:
                            MyGlobals.logger2.Fatal(logText);
                            break;

                    }
                }
            }
            catch (Exception ex)
            {
                if (MyRtnFromServiceParms != null)
                {
                    logText = "EnterpriseId" + MyRtnFromServiceParms.passedEnterpriseId + "   UserId:" + MyRtnFromServiceParms.passedUserId + "   TransactionId:" + MyRtnFromServiceParms.passedCurrentTransId + "   Trans Seq:" + MyRtnFromServiceParms.passedCurSeq + "   Environment:" + MyRtnFromServiceParms.passedEnv + "   Method:" + (logSourceFile + "/" + logSourceMethod).ToUpper() + "   Error Desc:" + ex;
                    MyGlobals.logger2.Error(logText);
                }

            }
        }

    }

}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial