public static bool GetGlobalConfig(
            ref DataAccessTools dA,
            ref PawnSecVO pwnSec,
            out string decryptKey)
        {
            //Set changed public key to false
            decryptKey = string.Empty;

            //Get global configuration
            DataReturnSet globalConfig;

            if (!DataAccessService.ExecuteQuery(false,
                                                PawnStoreSetupQueries.SELECT_PAWNSEC_GLOBAL,
                                                "globalconfig",
                                                PAWNSEC,
                                                out globalConfig,
                                                ref dA))
            {
                MessageBox.Show("Could not query global configuration from pawn sec",
                                "Alert");
                return(false);
            }

            if (globalConfig == null || globalConfig.NumberRows <= 0)
            {
                MessageBox.Show("Invalid or unexpected number of global config rows returned",
                                "Alert");
                return(false);
            }

            //Retrieve the data row
            DataReturnSetRow globDr;

            if (!globalConfig.GetRow(0, out globDr))
            {
                MessageBox.Show("Could not retrieve first row of the global config data table",
                                "Alert");
                return(false);
            }

            pwnSec.GlobalConfiguration.Version =
                Utilities.GetStringValue(globDr.GetData("APPVERSIONID"));
            pwnSec.GlobalConfiguration.BaseTemplatePath =
                Utilities.GetStringValue(globDr.GetData("TEMPLATEPATH"));
            //BZ 485: RB:  The following line needs to be added to pickup the base log path and keep it from getting hard coded.
            pwnSec.GlobalConfiguration.BaseLogPath =
                Utilities.GetStringValue(globDr.GetData("LOGPATH"));
            pwnSec.GlobalConfiguration.BaseMediaPath =
                Utilities.GetStringValue(globDr.GetData("MEDIAPATH"));
            pwnSec.GlobalConfiguration.AdobeReaderPath =
                Utilities.GetStringValue(globDr.GetData("ADOBEPATH"));
            pwnSec.GlobalConfiguration.GhostScriptPath =
                Utilities.GetStringValue(globDr.GetData("GHOSTPATH"));
            //Decrypt the global public key
            var globPubKeyEnc = Utilities.GetStringValue(globDr.GetData("PUBLICKEY"));
            var globPubKeyDec =
                StringUtilities.Decrypt(globPubKeyEnc,
                                        Common.Properties.Resources.PrivateKey,
                                        true);

            //Set the global public key if we do not have one
            if (string.IsNullOrEmpty(pwnSec.GlobalConfiguration.DataPublicKey))
            {
                pwnSec.GlobalConfiguration.DataPublicKey = globPubKeyDec;
            }

            //If we made it here, we were successful in acquiring global configuration
            decryptKey = globPubKeyDec + Common.Properties.Resources.PrivateKey;

            //Pull MD5 hash
            DataReturnSet verDataOut;

            if (!DataAccessService.ExecuteQuery(false, "select verchk from pawnsec.storeappversion where id = 5",
                                                "storeappversion", PAWNSEC, out verDataOut, ref dA))
            {
                MessageBox.Show("Could not retrieve version row from pawnsec");
                return(false);
            }

            //Validate data set
            if (verDataOut == null || verDataOut.NumberRows <= 0)
            {
                MessageBox.Show("No rows returned from storeappversion table in pawnsec");
                return(false);
            }

            //Extract row data
            DataReturnSetRow verRow;

            if (!verDataOut.GetRow(0, out verRow))
            {
                MessageBox.Show("Could not retrieve row data from pawnsec appversion data set");
                return(false);
            }

            //Retrieve remote MD5 value for this application
            var remoteMD5 = Utilities.GetStringValue(verRow.GetData("VERCHK"));

            //Generate MD5 value for this application version
            var appMD5 = StringUtilities.GenerateRawMD5Hash(Assembly.GetExecutingAssembly().GetName().Version.ToString(), Encoding.ASCII);

            //Ensure the MD5 keys match
            if (!string.Equals(remoteMD5, appMD5, StringComparison.OrdinalIgnoreCase))
            {
                MessageBox.Show("App version in pawn sec does not match the executing assembly version.");
                return(false);
            }

            return(true);
        }
        /*
         * select storenumber, storage_id, storage_date, storage_time from ccsowner.pawndocumentregistry pdr
         *  where PDR.STORENUMBER = '02030'
         *  and   PDR.DOC_TYPE = 'PDF'
         *  and   PDR.RECEIPTDETAIL_NUMBER = 0
         *  and   PDR.TICKET_NUMBER = 0
         *  and   PDR.CUSTOMERNUMBER is null
         *  and   PDR.STORAGE_DATE > (sysdate-90);
         *
         */

        private void submitStoreButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.storeCalendar != null)
            {
                this.storeCalendar.IsEnabled = false;
            }
            //Check file time - we do not want to hit production if the time limit is still in effect
            TupleType <long, long, string> timeData;

            if (TimeFileExists() && WithinTimeLimit(out timeData))
            {
                var diffTime = timeData.Right;
                MessageBox.Show("You are still within the time restriction limit. " + Environment.NewLine + " The application will now close.", "*** TIME LIMIT WARNING ***");
                Application.Current.Shutdown();
                this.Close();
                return;
            }
            if (!string.IsNullOrEmpty(this.selectedStore))
            {
                //Check to see if the store is in the list
                if (this.storeList.BinarySearch(this.selectedStore) < 0)
                {
                    MessageBox.Show("That store has not yet been converted to Cashlinx.  Please enter a different store number.");
                    return;
                }
                string errTxt;
                var    dTools = this.CshLnxDataTools;
                this.submitStoreButton.IsEnabled = false;
                var ninetyDaysAgo   = DateTime.Now.Date.Subtract(new TimeSpan(90, 0, 0, 0));
                var toDateConstruct = string.Format(
                    "to_date('{0}/{1}/{2}', 'MM/DD/YYYY')",
                    ninetyDaysAgo.Date.Month.ToString().PadLeft(2, '0'),
                    ninetyDaysAgo.Date.Day.ToString().PadLeft(2, '0'),
                    ninetyDaysAgo.Date.Year.ToString().PadLeft(4, '0'));

                if (!InitCouchDB())
                {
                    MessageBox.Show("Cannot connect to couch server! Exiting...", "Exit Warning");
                    Application.Current.Shutdown();
                    this.DialogResult = false;
                    this.Close();
                }
                var procMsg = new ProcessingMessage("*** PLEASE WAIT - FINDING DOCUMENTS ***");
                procMsg.Show();
                if (!DataAccessService.ExecuteQuery(
                        false,
                        string.Format(
                            "select storage_id, storage_time from ccsowner.pawndocumentregistry where storenumber = '{0}' " +
                            "and receiptdetail_number = 0 and ticket_number = 0 and doc_type = 'PDF' " +
                            "and customernumber is null and storage_date > {1} order by storage_time desc",
                            this.selectedStore, toDateConstruct),
                        "ccsowner.pawndocumentregistry",
                        PawnStoreProcedures.CCSOWNER,
                        out dstrStorageData,
                        ref dTools))
                {
                    procMsg.Hide();
                    errTxt = string.Format(
                        "Could not find any DSTR documents for that store");
                    showError(errTxt);
                    this.submitStoreButton.IsEnabled = true;
                    return;
                }
                if (dstrStorageData == null || dstrStorageData.NumberRows <= 0)
                {
                    procMsg.Hide();
                    errTxt = string.Format(
                        "Could not find any DSTR documents to view");
                    showError(errTxt);
                    this.submitStoreButton.IsEnabled = true;
                    return;
                }

                //Collect dates into a temporary map
                this.dateStorageMap.Clear();
                bool foundValidDoc = false;
                for (var j = 0; j < dstrStorageData.NumberRows; ++j)
                {
                    DataReturnSetRow dRow;
                    if (!dstrStorageData.GetRow(j, out dRow))
                    {
                        continue;
                    }
                    var dRowDate = Utilities.GetDateTimeValue(dRow.GetData("STORAGE_TIME"), DateTime.Now.Date);
                    List <PairType <string, Document> > storageIds;
                    var ticksKey = dRowDate.Date.Ticks;
                    if (CollectionUtilities.isNotEmptyContainsKey(this.dateStorageMap, ticksKey))
                    {
                        storageIds = this.dateStorageMap[ticksKey];
                    }
                    else
                    {
                        storageIds = new List <PairType <string, Document> >();
                        this.dateStorageMap.Add(ticksKey, storageIds);
                    }
                    //Get the storage id first
                    var      storageId = Utilities.GetStringValue(dRow.GetData("STORAGE_ID"), string.Empty);
                    Document doc;
                    if (IsDocumentDSTR(storageId, out doc))
                    {
                        storageIds.Add(new PairType <string, Document>(storageId, doc));
                        foundValidDoc = true;
                    }
                }

                procMsg.Hide();

                if (!foundValidDoc)
                {
                    procMsg.Hide();
                    errTxt = string.Format(
                        "Could not find any DSTR documents to view for this store");
                    showError(errTxt);
                    this.submitStoreButton.IsEnabled = true;
                    return;
                }


                //Update calendar
                var today        = DateTime.Now.Date;
                var tomorrowDate = DateTime.Now.Date.Add(new TimeSpan(1, 0, 0, 0));
                //Clear calendar black out dates
                this.storeCalendar.BlackoutDates.Clear();
                //Black out calendar from start of time to 90 days ago
                this.storeCalendar.BlackoutDates.Add(new CalendarDateRange(DateTime.MinValue.Date, ninetyDaysAgo.Date));
                //Black out calendar from tomorrow to the end of time
                this.storeCalendar.BlackoutDates.Add(new CalendarDateRange(tomorrowDate.Date, DateTime.MaxValue.Date));
                //Ensure store calendar is set to single date mode
                this.storeCalendar.SelectionMode = CalendarSelectionMode.SingleDate;
                //Ensure calendar is on today's date
                this.storeCalendar.SelectedDate = null;
                //Go through the ninety day range to today and black out dates we do not have storage ids for...
                var curDay = ninetyDaysAgo.Date;
                while (curDay.Date.CompareTo(today.Date) < 0)
                {
                    if (!CollectionUtilities.isNotEmptyContainsKey(this.dateStorageMap, curDay.Date.Ticks))
                    {
                        this.storeCalendar.BlackoutDates.Add(new CalendarDateRange(curDay.Date));
                        if (FileLogger.Instance.IsLogDebug)
                        {
                            FileLogger.Instance.logMessage(LogLevel.DEBUG, this, "Blackout date found = " + curDay.Date.ToLongDateString() + ", Ticks = " + curDay.Date.Ticks);
                        }
                    }
                    else
                    {
                        var idList = this.dateStorageMap[curDay.Date.Ticks];
                        if (CollectionUtilities.isEmpty(idList))
                        {
                            this.storeCalendar.BlackoutDates.Add(new CalendarDateRange(curDay.Date));
                            if (FileLogger.Instance.IsLogWarn)
                            {
                                FileLogger.Instance.logMessage(LogLevel.WARN, this, "Date with no DSTR found = " + curDay.Date.ToLongDateString() + ", Ticks = " + curDay.Date.Ticks);
                            }
                        }
                        else
                        {
                            if (FileLogger.Instance.IsLogDebug)
                            {
                                FileLogger.Instance.logMessage(LogLevel.DEBUG, this, "Valid date found = " + curDay.Date.ToLongDateString() + ", Ticks = " + curDay.Date.Ticks);
                            }
                        }
                    }
                    //Increment date
                    curDay = curDay.Date.Add(new TimeSpan(1, 0, 0, 0));
                }
                //Enable calendar
                this.storeCalendar.IsEnabled = true;
            }
        }
Esempio n. 3
0
        private void addMachineButton_Click(object sender, EventArgs e)
        {
            string macName = this.machineNameComboBox.Text;

            if (!string.IsNullOrEmpty(macName) &&
                macName.ToLowerInvariant().Contains(CASHAM_DOMAIN))
            {
                macName = macName.Trim();
                var res = MessageBox.Show("Are you sure you want to add " + macName + " to PAWNSEC™ ?",
                                          PawnStoreSetupForm.SETUPALERT_TXT,
                                          MessageBoxButtons.YesNo,
                                          MessageBoxIcon.Question);
                if (res == DialogResult.No)
                {
                    return;
                }

                //Ensure that this machine does not exist in pawn sec already for this store or
                //any other store
                var fndMachine = false;
                var pgFm       = new InProgressForm("* VERIFYING UNIQUENESS OF MACHINE *");
                if (CollectionUtilities.isNotEmpty(this.storeData.PawnSecData.ClientMachines))
                {
                    var fndMac = this.storeData.PawnSecData.ClientMachines.Find(
                        x => x.Machine.MachineName.Equals(macName, StringComparison.OrdinalIgnoreCase));
                    if (fndMac != null)
                    {
                        fndMachine = true;
                    }
                    if (fndMachine == false &&
                        !string.IsNullOrEmpty(ipAddressTextBox.Text))
                    {
                        var trimIp = ipAddressTextBox.Text.Trim();
                        if (!string.IsNullOrEmpty(trimIp))
                        {
                            //See if IP address is used, and if so, ensure uniqueness
                            var fndIp =
                                this.storeData.PawnSecData.ClientMachines.Find(
                                    x => x.Machine.IPAddress.Equals(trimIp));
                            if (fndIp != null)
                            {
                                fndMachine = true;
                            }
                        }
                    }

                    if (fndMachine == false &&
                        !string.IsNullOrEmpty(macAddressTextBox.Text))
                    {
                        var trimMac = macAddressTextBox.Text.Trim();
                        if (!string.IsNullOrEmpty(trimMac))
                        {
                            var fndMacAddr =
                                this.storeData.PawnSecData.ClientMachines.Find(
                                    x =>
                                    x.Machine.MACAddress.Equals(trimMac, StringComparison.OrdinalIgnoreCase));
                            if (fndMacAddr != null)
                            {
                                fndMachine = true;
                            }
                        }
                    }
                }

                //Now check globally against all entries
                if (!fndMachine)
                {
                    var whereClause = "machinename = '" + macName + "'";
                    if (!string.IsNullOrEmpty(ipAddressTextBox.Text))
                    {
                        var trimIp = ipAddressTextBox.Text.Trim();
                        if (!string.IsNullOrEmpty(trimIp))
                        {
                            whereClause += " or ipaddress = '" + trimIp + "'";
                        }
                    }
                    if (!string.IsNullOrEmpty(macAddressTextBox.Text))
                    {
                        var trimMac = macAddressTextBox.Text.Trim();
                        if (!string.IsNullOrEmpty(trimMac))
                        {
                            whereClause += " or macaddress = '" + trimMac + "'";
                        }
                    }
                    DataReturnSet dS;
                    if (DataAccessService.ExecuteQuery(false,
                                                       string.Format(
                                                           "select machinename from clientregistry where {0}",
                                                           whereClause),
                                                       "clientregistry",
                                                       PawnStoreSetupForm.PAWNSEC,
                                                       out dS,
                                                       ref this.dAPawnSec))
                    {
                        if (dS != null && dS.NumberRows > 0)
                        {
                            fndMachine = true;
                        }
                    }
                    pgFm.HideMessage();
                }

                if (fndMachine)
                {
                    pgFm.Dispose();
                    MessageBox.Show(
                        "This machine already exists in the pawn security database. " + Environment.NewLine +
                        "  If this machine has moved to a different store, please " + Environment.NewLine +
                        "remove it from that store's security database first.",
                        PawnStoreSetupForm.SETUPALERT_TXT);
                    return;
                }
                pgFm.Dispose();
                this.addMachineButton.Enabled    = false;
                this.removeButton.Enabled        = false;
                this.machineNameComboBox.Enabled = false;
                var newMac     = new PawnSecVO.ClientPawnSecMachineVO();
                var newMapping = new PawnSecVO.ClientStoreMapVO();
                newMac.Machine.MachineName = macName;
                int perIdx = macName.IndexOf(".");
                if (perIdx != -1)
                {
                    newMac.Machine.WorkstationName = macName.Substring(0, perIdx);
                }
                //Set terminal number
                if (CollectionUtilities.isNotEmpty(this.storeData.PawnSecData.ClientMachines))
                {
                    newMac.StoreMachine.TerminalNumber =
                        this.storeData.PawnSecData.ClientMachines.Max(
                            x => x.StoreMachine.TerminalNumber) + 1;
                }
                else
                {
                    newMac.StoreMachine.TerminalNumber = 1;
                }
                //Set store client config id
                //ulong storeMachineId = 0;
                //this.storeData.PawnSecData.NextIdSet.GetNextIds(PawnSecVO.PawnSecNextIdVO.SELECTOR.STOCLICFG_ID, ref storeMachineId);
                newMac.StoreMachine.Id = 0;//storeMachineId;

                //Set client id
                //ulong clientRegId = 0;
                //this.storeData.PawnSecData.NextIdSet.GetNextIds(PawnSecVO.PawnSecNextIdVO.SELECTOR.CLIREG_ID, ref clientRegId);
                newMac.Machine.ClientId = 0;

                //Set mapping id
                //ulong newMappingId = 1;
                //this.storeData.PawnSecData.NextIdSet.GetNextIds(PawnSecVO.PawnSecNextIdVO.SELECTOR.CLISTOMAP_ID, ref newMappingId);
                newMapping.Id = 0;
                newMapping.ClientRegistryId = newMac.Machine.ClientId;

                //Set store config id
                newMapping.StoreClientConfigId = newMac.StoreMachine.Id;

                var curSto = this.getStoreInformation();
                if (curSto == null)
                {
                    MessageBox.Show("Cannot find store to add this client to for mapping purposes",
                                    PawnStoreSetupForm.SETUPALERT_TXT);
                    return;
                }
                newMapping.StoreSiteId   = curSto.StoreSiteId;
                newMapping.StoreConfigId = curSto.StoreConfiguration.Id;
                newMapping.StoreNumber   = this.storeNumber;
                this.storeData.PawnSecData.ClientMachines.Add(newMac);
                this.storeData.PawnSecData.ClientStoreMapList.Add(newMapping);
                this.storeData.PawnSecData.GenerateMaps();
            }
            else
            {
                MessageBox.Show(
                    "Please enter a valid machine name. It must contain the full domain name: " + CASHAM_DOMAIN,
                    PawnStoreSetupForm.SETUPALERT_TXT);
            }
        }
        private void DSTRViewerWindowForm_Loaded(object sender, RoutedEventArgs e)
        {
            TupleType <long, long, string> timeData;

            if (IsRestrictedEnvironment())
            {
                var timeLimitValue = DSTRViewer.Properties.Settings.Default.timeLimiter;
                if (string.IsNullOrEmpty(timeLimitValue))
                {
                    timeLimitValue = "300000";
                }
                var timeLimitAct = Utilities.GetLongValue(timeLimitValue, 300000L);
                //Convert from milliseconds to minutes
                timeLimitAct = timeLimitAct / 1000 / 60;

                var res = MessageBox.Show(
                    "*************** WARNING ***************" + Environment.NewLine +
                    "  You are accessing a live production" + Environment.NewLine +
                    "  system. Your activity is being     " + Environment.NewLine +
                    "  logged and your access will be     " + Environment.NewLine +
                    "  limited to one document retrieval  " + Environment.NewLine +
                    "  every " + timeLimitAct + " minutes. If you do not  " + Environment.NewLine +
                    "  agree with this policy, click      " + Environment.NewLine +
                    "  Cancel. By clicking OK you are     " + Environment.NewLine +
                    "  bound to this time limit policy.   ",
                    "Time Limit Policy For Cashlinx Production Systems",
                    MessageBoxButton.OKCancel, MessageBoxImage.Stop);
                if (res == MessageBoxResult.Cancel)
                {
                    if (FileLogger.Instance.IsLogFatal)
                    {
                        FileLogger.Instance.logMessage(LogLevel.FATAL, this, "User {0} clicked cancel when presented with the production time limit policy.", this.curUserName);
                    }

                    MessageBox.Show("*** Application Exiting ***");
                    Application.Current.Shutdown();
                    this.Close();
                    return;
                }
                else if (res == MessageBoxResult.OK)
                {
                    try
                    {
                        //Determine if the file exists
                        //                        var filesExisting = Directory.GetFiles(".", TIME_FILE, SearchOption.TopDirectoryOnly);
                        //                        var fileExists = filesExisting.Length > 0;
                        if (TimeFileExists() && WithinTimeLimit(out timeData))
                        {
                            //Warn about time limit, then exit
                            MessageBox.Show(
                                "You are still in the waiting period to fetch a document from production." + Environment.NewLine +
                                "Exiting the application.",
                                "*** TIME LIMIT WARNING ***",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                            //Exit the app
                            Application.Current.Shutdown();
                            this.Close();
                            return;
                        }
                    }
                    catch (Exception eX)
                    {
                        if (FileLogger.Instance.IsLogError)
                        {
                            FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Could not read time limit file data: {0}", eX.Message);
                        }
                    }
                }
            }
            checkInitialized();
            if (!initialized)
            {
                MessageBox.Show("DSTR Viewer is not initialized");
                this.Close();
            }


            //Check file time - we do not want to hit production if the time limit is still in effect
            if (TimeFileExists() && WithinTimeLimit(out timeData))
            {
                var diffTime = timeData.Right;
                MessageBox.Show("You are still within the time restriction limit.  The application will now close.", "*** TIME LIMIT WARNING ***");
                Application.Current.Shutdown();
                this.Close();
                return;
            }

            //Populate store drop down
            DataReturnSet dSet;
            string        errTxt;
            var           dTools = this.CshLnxDataTools;

            if (!DataAccessService.ExecuteQuery(
                    false,
                    "select storenumber from ccsowner.store where alias_id is not null and pawn_conversion is not null",
                    "ccsowner.store",
                    PawnStoreProcedures.CCSOWNER,
                    out dSet,
                    ref dTools))
            {
                errTxt = string.Format(
                    "Could not find any stores! Store query failed.");
                showError(errTxt);
                this.Close();
                return;
            }

            if (dSet == null || dSet.NumberRows <= 0)
            {
                errTxt = string.Format(
                    "Invalid result sets from store query!");
                showError(errTxt);
                this.Close();
                return;
            }
            //Extract the stores from the data set
            for (var j = 0; j < dSet.NumberRows; ++j)
            {
                DataReturnSetRow dRow;
                if (!dSet.GetRow(j, out dRow))
                {
                    continue;
                }
                if (dRow == null)
                {
                    continue;
                }
                var storeNum = Utilities.GetStringValue(dRow.GetData(0), string.Empty);
                if (!string.IsNullOrEmpty(storeNum))
                {
                    this.storeList.Add(storeNum);
                }
            }

            //Order them to enhance search speed
            this.storeList.Sort();

            /* No need to do this anymore with text box submit
             * //Order the stores
             * orderedShopList.Sort();
             *
             * //Put the stores into the combo box
             * foreach(var s in orderedShopList)
             * {
             *  var storeNum = s;
             *  if (storeNum != null)
             *  {
             *      var newComboItem = new ComboBoxItem
             *                         {
             *                             Content = storeNum
             *                         };
             *      this.storeComboBox.Items.Add(newComboItem);
             *  }
             * }*/
        }