Example #1
0
        //-----------------------------------------------------------
        public int StartProcess()
        {
            int result = 1;
            if (core == null)
            {
                throw new Exception("Empty core object");
            }
            try
            {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Start processing");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Reading dynamic configuration");
              #region Variables from xml configuration
              String url = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "url");
              String apiKey = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "api-key");
              String secretApiKey = PasswordEncoder.PtrDecryptText(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "secret-api-key"));
              String sharedKey = PasswordEncoder.PtrDecryptText(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "web-service-shared-key"));
              String serviceURL = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "blue-media-ws-url");
              EntriesDownloadMode entriesDownloadMode = (EntriesDownloadMode)Convert.ToInt32(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode").Substring(0, 1));
              EntriesDownloadDate entriesDownloadDate =
                ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date").Substring(0, 3).ToUpper() == "YES" ?
                EntriesDownloadDate.AUTOMATIC : EntriesDownloadDate.MANUAL;
              String startDateString = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date:start-date");
              DateTime startDate = DateTime.MinValue;
              if(entriesDownloadDate == EntriesDownloadDate.MANUAL)
              {
                if(!DateTime.TryParseExact(startDateString, "yyyy-MM-dd", null, DateTimeStyles.None, out startDate))
                {
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Could not parse the date provided in the configuration. Taking all entries.");
                  entriesDownloadMode = EntriesDownloadMode.ALL;
                }
              }
              String connectionString = ConverterUtils.GetDBConvertersConnectionString(core);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Url to connect to: {0}", url);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Api key: {0}", apiKey);
              if(entriesDownloadMode == EntriesDownloadMode.SELECTED && entriesDownloadDate == EntriesDownloadDate.AUTOMATIC)
              {
                using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString))
                {
                  startDate = (from dinfo in dc.entry_status_change_update_times
                               orderby dinfo.last_verification_status_change_update_date descending
                               select dinfo.last_verification_status_change_update_date).FirstOrDefault();
                  if(startDate == DateTime.MinValue)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "No record indicating last update time in database. Taking all entries.");
                    entriesDownloadMode = EntriesDownloadMode.ALL;
                  }
                }
              }

              if(entriesDownloadMode == EntriesDownloadMode.ALL)
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading all entries");
              }
              else
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading selected entries from {0}.", startDate.ToString("yyyy-MM-dd HH:mm:ss.fff"));
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Secret api key decrypted succesfully");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Web service shared key decrypted succesfully");
              #endregion
              XNamespace serv = "http://leader.raiffeisen.pl/api";
              //url = "http://localhost:65301/LeaderTestWebApp/Test/";
              ActiveForm form = new ActiveForm(serv, apiKey, secretApiKey, url);

              List<Tuple<String, String>> messageParameters = new List<Tuple<String, String>>();
              messageParameters.Add(new Tuple<string, string>("lastVerificationStatusUpdateThreshold", String.Empty));
              ActiveForm.ActiveFormAnswer answer = form.CallActiveFormsMethod("getEntriesAfterEmployeeVerification", messageParameters);
              XElement entryData = answer.ResponseXml;
              //Przygotowanie do generowania
              using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(ConverterUtils.GetDBConvertersConnectionString(core)))
              {
                if(answer.AnswerCode == ActiveForm.AnswerCodes.OK)
                {
                  var verifiedEntryList = (from entry in entryData.Descendants(serv + "entry")
                                           select new
                                           {
                                             entryId = Int32.Parse(entry.Descendants(serv + "entryId").First().Value.Trim()),
                                             verificationStatus = Int32.Parse(entry.Descendants(serv + "verificationStatusId").First().Value.Trim()),
                                           }).ToList();
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retreived {0} entries with updated status.", verifiedEntryList.Count);
                  if(verifiedEntryList.Count > 0)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Their ids are {0}.", String.Join(",",verifiedEntryList.Select(x=>x.entryId.ToString()).ToArray()));
                  }
                  var entryList = (from entry in dc.leader_entries
                                   where verifiedEntryList.Select(x => x.entryId).Contains(entry.entryId)
                                   select entry).ToList();
                  foreach(var item in entryList)
                  {
                    item.status = verifiedEntryList.Where(x => x.entryId == item.entryId).First().verificationStatus;
                  }
                  var temp1 = verifiedEntryList.Select(x => x.entryId.ToString());
                  var temp2 = entryList.Select(x=>x.entryId.ToString());
                  var temp3 = temp1.Except(temp2);
                  if(verifiedEntryList.Count > entryList.Count)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Some of them ({0}) are missing from leader_entries table.",
                        String.Join(",",temp3.ToArray()));
                  }
                  String lastVerificationStatusDateString = String.Empty;
                  try
                  {
                    lastVerificationStatusDateString = entryData.Descendants(serv + "lastVerificationStatusUpdateTime").First().Value;
                  }
                  catch(Exception)
                  {
                  }
                  DateTime lastVerificationStatusDate;
                  if(!String.IsNullOrEmpty(lastVerificationStatusDateString))
                  {
                    Boolean success = DateTime.TryParse(lastVerificationStatusDateString, out lastVerificationStatusDate);
                    if(success)
                    {
                      entry_status_change_update_time time = new entry_status_change_update_time() { last_verification_status_change_update_date = lastVerificationStatusDate, date_received = DateTime.Now };
                      dc.entry_status_change_update_times.InsertOnSubmit(time);
                    }
                  }
                  dc.SubmitChanges();
                }
                else
                {
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Could not get valid response from Leader. Error: {0}. Will continue processing without updating leader entries.", answer.AnswerCode.ToString());
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Full response xml:", answer.ResponseXml.ToString());
                }
                //var recordsToRetransfer = from entry in dc.leader_entries
                //                          join itn in dc.itn_transactions
                //                          on entry.transactionId equals itn.orderID into itn_
                //                          from itn__ in itn_.DefaultIfEmpty()
                //                          where ((entry.status == 3 || entry.status == 4 || entry.status == 5 || (entry.status == 100 && itn__ != null))
                //                          && !itn__.retransferConfirmationDate.HasValue)
                //                          select new
                //                         {
                //                           itn = itn__,
                //                           entry = entry
                //                         };
                var recordsToRetransfer = (from entry in dc.leader_entries
                                          join itn in dc.itn_transactions on entry.transactionId equals itn.orderID
                                          join retr in dc.retransfers on itn.id equals retr.itn_transaction_id into retr_join
                                          from ret in retr_join.DefaultIfEmpty()
                                          group new
                                          {
                                            itn = itn,
                                            entry = entry,
                                            ret = ret
                                          } by new {
                                            itn = itn,
                                            entry = entry
                                          } into groups
                                          from g in groups
                                          where (g.entry.status == 3 || g.entry.status == 4 || g.entry.status == 5 || g.entry.status == 100) && g.itn.retransferConfirmationDate == null
                                            && groups.Count(x=>x.ret != null) < 3
                                          select new
                                          {
                                            itn = groups.Key.itn, entry=groups.Key.entry, triesCount = groups.Count(x=>x.ret != null)
                                          }).Distinct().ToList();
                int recordToRetransferCount = recordsToRetransfer.Count();
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "There are {0} transaction to retransfer", recordToRetransferCount);
                int lastTimeRetransferCount = recordsToRetransfer.Count(x => x.triesCount == 2);
                //if(lastTimeRetransferCount > 0)
                //{
                //  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "There are {0} transaction(s) which will be tried to retransfer for the third time. This is the last try.", lastTimeRetransferCount);
                //  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "These transactions id(s): {0}", String.Join(",",recordsToRetransfer.Where(x=>x.triesCount == 2).Select(x=>x.itn.id.ToString()).ToArray()));
                //}
                DateTime now = DateTime.Now;
                foreach (var record in recordsToRetransfer)
                {
                  ChangeNullStringToEmpty(record.entry);
                  BMWebReference.TransactionIn trin = new global::BMRetransfer.BMWebReference.TransactionIn();
                  trin.parentTransactionMerchantID = record.itn.merchantID.ToString();
                  trin.parentTransactionOrderID = record.itn.orderID;

                  BMWebReference.TransactionOut trout = new global::BMRetransfer.BMWebReference.TransactionOut();
                  trout.amount = new global::BMRetransfer.BMWebReference.Money() { currency = global::BMRetransfer.BMWebReference.Currency.PLN, value = record.itn.value };
                  trout.bmAccountId = "RAIFFEISENVERIFICATION";
                  trout.receiverAccount = record.itn.customerAccount;
                  trout.receiverName = record.entry.firstName + " " + record.entry.lastName; // record.itn.customerAddress;
                  trout.receiverAddress = String.Join(" ",
                    new String[] { record.entry.street,
                      String.IsNullOrEmpty(record.entry.apartmentNumber.Trim()) ? record.entry.houseNumber :
                        record.entry.houseNumber + "/" + record.entry.apartmentNumber, record.entry.postCode, record.entry.city });
                  switch(record.entry.status)
                  {
                    case 3:
                    {
                      trout.title = "Umowa o konta, kartę i kanały elektroniczne w Raiffeisen Polbank nie została zawarta";
                      break;
                    }
                    case 4:
                    {
                      trout.title = "Potwierdzamy zawarcie umów o konta, kartę i kanały elektroniczne w Raiffeisen Polbank";
                      break;
                    }
                    case 5:
                    {
                      trout.title = "Umowa o konta, kartę i kanały elektroniczne w Raiffeisen Polbank nie została zawarta";
                      break;
                    }
                    default:
                      break;
                  }
                  trout.transferBankId = record.itn.id.ToString(); //TU SIĘ ZASTANOWIC
                  StringBuilder hashedValue = new StringBuilder();
                  hashedValue.Append(trin.parentTransactionOrderID).Append(trin.parentTransactionMerchantID).
                    Append(trout.transferBankId).Append(trout.bmAccountId).
                    Append(trout.amount.value.ToString("0.00").Replace(",", ".")).
                    Append(trout.amount.currency.ToString()).
                    Append(trout.title).
                    Append(trout.receiverAccount).
                    Append(trout.receiverName).
                    Append(trout.receiverAddress).
                    Append(sharedKey);
                  String hash = String.Empty;
                  using (MD5 md5Hash = MD5.Create())
                  {
                    hash = GetHash(md5Hash,hashedValue.ToString());
                  }
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Sending the retransfer order for transaction with id {0}.", record.itn.orderID);
                  BMWebReference.TransferData td = new BMWebReference.TransferData() { transactionIn = trin, transactionOut = trout, hash = hash };
                  BMWebReference.TransferService ts = new BMWebReference.TransferService();
                  BMWebReference.TransferConfirmation tc = ts.ReceiveTransfer(td);
                  if(tc != null)
                  {
                    retransfer retr = new retransfer() { itn_transaction_id = record.itn.id, retransfer_try_date = now  };
                    dc.retransfers.InsertOnSubmit(retr);
                    if(tc.trStatus == global::BMRetransfer.BMWebReference.ConfirmationStatus.CONFIRMED)
                    {
                      record.itn.retransferConfirmationDate = DateTime.Now;
                      retr.confirmed = true;
                      PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retransfer for transaction with id {0} was confirmed.", record.itn.orderID);
                    }
                    else if(tc.trStatus == global::BMRetransfer.BMWebReference.ConfirmationStatus.ALREADY_CONFIRMED)
                    {
                      PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Retransfer for transaction with id {0} was already confirmed. This is not a normal situation and should be verified.", record.itn.orderID);
                      retr.confirmed = true;
                    }
                    else
                    {
                      if(record.triesCount == 2)
                      {
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Retransfer for transaction with id {0} was not confirmed. This was the third and the last try", record.itn.orderID);
                      }
                      else
                      {
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retransfer for transaction with id {0} was not confirmed. Will try again when the converter is executed again", record.itn.orderID);
                      }

                      retr.confirmed = false;
                    }
                    dc.SubmitChanges();
                  }
                }
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Save dynamic configuration");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Finish processing");

            }
            catch (Exception ex)
            {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, ex, "");
                result = -1;
            }
            return result;
        }
        private String sharedKey = "raiffeisen.online.test.12gdf3"; //do uzgodnienia i zmiany oraz przemyślenia czy zaszyty w kodzie

        #endregion Fields

        #region Methods

        // Do uzgodnienia - chcą używać typu BigDecimal - nie jest wspierany przez .NET- piszemy klasę do obsługi?
        //
        public Confirmation transAlerts(Transaction transaction)
        {
            StringBuilder logMessage = new StringBuilder();
              logMessage.Append("merchantID=").AppendLine(transaction.merchantID.ToString()).
            Append("orderId=").AppendLine(transaction.orderID).
            Append("transId=").AppendLine(transaction.transID).
            Append("transDate=").AppendLine(transaction.transDate.ToString("yyyy-MM-dd HH:mm:ss")).
            Append("transTitle=").AppendLine(transaction.transTitle).
            Append("value=").AppendLine(transaction.amount.value.ToString()).
            Append("currency=").AppendLine(transaction.amount.currency.ToString()).
            Append("paywayID=").AppendLine(transaction.paywayID.ToString()).
            Append("statusDate=").AppendLine(transaction.statusDate.ToString("yyyy-MM-dd HH:mm:ss")).
            Append("status=").AppendLine(transaction.status.ToString()).
            Append("customerAddress=").AppendLine(transaction.customerData == null ? String.Empty : transaction.customerData.customerAddress).
            Append("customerNRB=").AppendLine(transaction.customerData == null ? String.Empty : transaction.customerData.customerNRB).
            Append("klucz_współdzielony=").AppendLine(sharedKey).
            Append("hash=").AppendLine(transaction.docHash);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "A transaction has just arrived");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, logMessage.ToString());

              StringBuilder sb = new StringBuilder();
              sb.Append(transaction.merchantID).Append(transaction.orderID).Append(transaction.transID).
            Append(transaction.transDate.ToString("yyyy-MM-dd HH:mm:ss")).
            Append(transaction.transTitle).
            Append(transaction.amount.value.ToString().Replace(",", ".")).Append(transaction.amount.currency).
            Append(transaction.paywayID).Append(transaction.statusDate.ToString("yyyy-MM-dd HH:mm:ss")).
            Append(transaction.status).Append(transaction.customerData == null ? String.Empty : transaction.customerData.customerAddress).
            Append(transaction.customerData == null ? String.Empty : transaction.customerData.customerNRB).Append(sharedKey);
              Boolean hashCorrect;
              Confirmation.ConfirmationEnum confirmationValue = Confirmation.ConfirmationEnum.CONFIRMED;
              using (MD5 md5Hash = MD5.Create())
              {
            hashCorrect = HelperMethods.VerifyHash(md5Hash, sb.ToString(), transaction.docHash);
              }
              if (hashCorrect)
              {
            try
            {
              using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(TaskInserter.connectionString))
              {
            var transactions = from tr in dc.itn_transactions
                               where tr.transID == transaction.transID
                               select tr;
            var currencies = from cur in dc.itn_currencies
                             where cur.currency.ToString() == transaction.amount.currency.ToString()
                             select cur;
            if (currencies.Count() == 0) // Zgodnie ze specyfikacją sytuacja nie może zaistnieć - dopuszczają tylko PLN - można zakomentować if
            {
              itn_currency newCurrency = new itn_currency() { currency = transaction.amount.currency.ToString() };
              dc.itn_currencies.InsertOnSubmit(newCurrency);
              dc.SubmitChanges();
            }
            int currencyID = currencies.First().id;
            if (transactions.Count() == 1)
            {
              itn_transaction modifiedTransaction = transactions.First();
              if (modifiedTransaction.status > 0 && transaction.status <= 0)
              {
                // jeżeli taka sytuacja zaistnieje, to błąd
                // do uzgodnienia co wtedy robimy,
                // na razie zwracam NOT_CONFIRMED;
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Transaction with id {0} wants to change the status from positive to negative. This situation is unexpected and should be verified.",modifiedTransaction.id);
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Transaction will be NOT_CONFIRMED");
                confirmationValue = Confirmation.ConfirmationEnum.NOT_CONFIRMED;
              }
              else if (modifiedTransaction.merchantID != transaction.merchantID
                || modifiedTransaction.orderID != transaction.orderID
                || modifiedTransaction.value != transaction.amount.value)
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Transaction with id {0} wants to change one of the values: merchantID, orderID, value. This situation is unexpected and should be verified.", modifiedTransaction.id);
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Transaction will be NOT_CONFIRMED");
                confirmationValue = Confirmation.ConfirmationEnum.NOT_CONFIRMED;
              }
              else
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Transaction already exists in the database.");
                modifiedTransaction.transID = transaction.transID;
                modifiedTransaction.paywayID = transaction.paywayID;
                modifiedTransaction.merchantID = transaction.merchantID;
                modifiedTransaction.status = transaction.status;
                modifiedTransaction.statusDate = transaction.transDate;
                modifiedTransaction.transTitle = transaction.transTitle;
                modifiedTransaction.customerAccount = transaction.customerData == null ? String.Empty : transaction.customerData.customerNRB;
                modifiedTransaction.customerAddress = transaction.customerData == null ? String.Empty : transaction.customerData.customerAddress;
                modifiedTransaction.transDate = transaction.transDate;
                modifiedTransaction.value = transaction.amount.value;
                modifiedTransaction.currencyID = currencyID;
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Transaction will be CONFIRMED and updated in the database.");
                dc.SubmitChanges();
              }
            }
            else if (transactions.Count() == 0)
            {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Transaction is a new one.");
              itn_transaction newTransaction = new itn_transaction()
              {
                transID = transaction.transID,
                orderID = transaction.orderID,
                paywayID = transaction.paywayID,
                merchantID = transaction.merchantID,
                status = transaction.status,
                statusDate = transaction.transDate,
                customerAccount = transaction.customerData == null ? String.Empty : transaction.customerData.customerNRB,
                customerAddress = transaction.customerData == null ? String.Empty : transaction.customerData.customerAddress,
                transDate = transaction.transDate,
                transTitle = transaction.transTitle,
                value = transaction.amount.value,
                currencyID = currencyID
              };
              dc.itn_transactions.InsertOnSubmit(newTransaction);
              dc.SubmitChanges();
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Transaction will be CONFIRMED and inserted into the database.");
            }
            else
              {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "There is more than one transaction with transId {0}. This situation is unexpected and should be verified.", transaction.transID);
              }
              }
            }
            catch (Exception e)
            {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, "Error when connecting to database {0}", e.Message);
            }
              }
              else
              {
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Hash incorrect");
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Transaction will be NOT_CONFIRMED");
            confirmationValue = Confirmation.ConfirmationEnum.NOT_CONFIRMED;
              }
              if(confirmationValue == Confirmation.ConfirmationEnum.CONFIRMED)
              {
            String message = "ITN arrived. Timer1 is reset, Timer2 will start if it is not running. ";
            TaskInserter.shortTimer.Reset();
            if (!TaskInserter.longTimer.Timer.Enabled)
            {
              TaskInserter.longTimer.Start();
              message += "Timer 2 is not enabled and starts now.";
            }
            else
            {
              message += "Timer 2 was already started.";
            }
            PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, message);
              }
              String confirmationHash = String.Empty;
              using (MD5 md5Hash = MD5.Create())
              {
            confirmationHash = HelperMethods.GetHash(md5Hash, transaction.merchantID + transaction.orderID +
              confirmationValue.ToString() + sharedKey);
              }
              return new Confirmation()
              {
            confirmation = confirmationValue,
            merchantID = transaction.merchantID,
            orderID = transaction.orderID,
            docHash = confirmationHash
              };
        }
Example #3
0
        //-----------------------------------------------------------
        public int StartProcess()
        {
            int result = 1;
            if (core == null)
            {
                throw new Exception("Empty core object");
            }
            //PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, Properties.Settings.Default.PTR_Convert_RAIFF_PAZRConnectionString);
            try
            {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Start processing");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Reading dynamic configuration");
              #region Variables from xml configuration
              String url = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "url");
              String apiKey = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "api-key");
              String secretApiKey = PasswordEncoder.PtrDecryptText(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "secret-api-key"));
              EntriesDownloadMode entriesDownloadMode = (EntriesDownloadMode)Convert.ToInt32(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode").Substring(0, 1));
              EntriesDownloadDate entriesDownloadDate =
                ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date").Substring(0, 3).ToUpper() == "YES" ?
                EntriesDownloadDate.AUTOMATIC : EntriesDownloadDate.MANUAL;
              String startDateString = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date:start-date");
              DateTime startDate = DateTime.MinValue;
              if(entriesDownloadDate == EntriesDownloadDate.MANUAL)
              {
                if(!DateTime.TryParseExact(startDateString, "yyyy-MM-dd", null, DateTimeStyles.None, out startDate))
                  {
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Could not parse the date provided in the configuration. Taking all entries.");
                  entriesDownloadMode = EntriesDownloadMode.ALL;
                  }
              }
              String connectionString = ConverterUtils.GetDBConvertersConnectionString(core);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Url to connect to: {0}", url);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Api key: {0}", apiKey);
              if(entriesDownloadMode == EntriesDownloadMode.SELECTED && entriesDownloadDate== EntriesDownloadDate.AUTOMATIC)
              {
                using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString)) //"Data Source=172.17.25.59;Initial Catalog=PTR_Convert_RAIFF_PAZR;User ID=sa;Password=R%T*2011;Connection Timeout=3600;Asynchronous Processing=true;MultipleActiveResultSets=true;Persist Security Info=True;"))
                {
                  startDate = (from dinfo in dc.entry_status_update_times
                               orderby dinfo.last_verification_status_update_date descending
                               select dinfo.last_verification_status_update_date).FirstOrDefault();
                  if(startDate == DateTime.MinValue)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "No record indicating last update time in database. Taking all entries.");
                    entriesDownloadMode = EntriesDownloadMode.ALL;
                  }
                }
              }

              if(entriesDownloadMode == EntriesDownloadMode.ALL)
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading all entries");
              }
              else
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading selected entries from {0}.", startDate.ToString("yyyy-MM-dd HH:mm:ss.fff"));
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Secret api key decrypted succesfully");
              #endregion
              XNamespace serv = "http://leader.raiffeisen.pl/api";
              //url = "http://localhost:65301/LeaderTestWebApp/Test/";
              ActiveForm form = new ActiveForm(serv, apiKey, secretApiKey, url);

              List<Tuple<String, String>> messageParameters = new List<Tuple<String, String>>();
              //Format daty: "2014-02-05T10:22:32.112+01:00"
              //2014-02-12T12:28:15.497+01:00
              //2014-02-12T12:27:46.954+01:00
              //2014-02-12T12:14:33.019+01:00
              //2014-02-12T12:14:33.019+01:00
              //2014-02-12T12:14:02.352+01:00
              //2014-02-12T12:13:13.693+01:00
              //2014-02-12T12:12:51.861+01:00

              messageParameters.Add(new Tuple<string, string>("lastVerificationStatusUpdateThreshold", startDate.ToString("yyyy-MM-ddTHH:mm:ss.ff+01:00")));//startDate.AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ss.fff+01:00")));//
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading entries changed from {0}", startDate.ToString("yyyy-MM-ddTHH:mm:ss.fff+01:00"));
              ActiveForm.ActiveFormAnswer answer = form.CallActiveFormsMethod("getEntriesForPaymentVerification",messageParameters);
              XElement entryData = answer.ResponseXml;
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Received message {0}", answer.AnswerCode.ToString());
              if(answer.AnswerCode == ActiveForm.AnswerCodes.OK)
              {
                List<leader_entry> entryList = (from entry in entryData.Descendants(serv + "entry")
                  select new leader_entry()
                  {
                    entryId = Int32.Parse(entry.Descendants(serv + "entryId").First().Value.Trim()),
                    transactionId = entry.Descendants(serv + "transactionId").First().Value.Trim(),
                    firstName = entry.Descendants(serv + "firstName").First().Value.Trim(),
                    lastName = entry.Descendants(serv + "lastName").First().Value.Trim(),
                    street = entry.Descendants(serv+"registrationAddress").Descendants(serv + "street").First().Value.Trim(),
                    houseNumber = entry.Descendants(serv+"registrationAddress").Descendants(serv + "houseNumber").First().Value.Trim(),
                    apartmentNumber = entry.Descendants(serv+"registrationAddress").Descendants(serv + "apartmentNumber").First().Value.Trim(),
                    postCode = entry.Descendants(serv+"registrationAddress").Descendants(serv + "postCode").First().Value.Trim(),
                    city = entry.Descendants(serv+"registrationAddress").Descendants(serv + "city").First().Value.Trim(),
                    streetMail = entry.Descendants(serv + "mailAddress").Descendants(serv + "street").First().Value.Trim(),
                    houseNumberMail = entry.Descendants(serv + "mailAddress").Descendants(serv + "houseNumber").First().Value.Trim(),
                    apartmentNumberMail = entry.Descendants(serv + "mailAddress").Descendants(serv + "apartmentNumber").First().Value.Trim(),
                    postCodeMail = entry.Descendants(serv + "mailAddress").Descendants(serv + "postCode").First().Value.Trim(),
                    cityMail = entry.Descendants(serv + "mailAddress").Descendants(serv + "city").First().Value.Trim(),
                    createDate = Convert.ToDateTime(entry.Descendants(serv+"creationTime").First().Value.Trim())
                  }).ToList();
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retreived {0} entries.", entryList.Count);
                String lastVerificationStatusDateString = String.Empty;
                try
                {
                  lastVerificationStatusDateString = entryData.Descendants(serv + "lastVerificationStatusUpdateTime").First().Value;
                }
                catch(Exception)
                {
                }
                DateTime lastVerificationStatusDate;
                if(!String.IsNullOrEmpty(lastVerificationStatusDateString))
                {
                  Boolean success = DateTime.TryParse(lastVerificationStatusDateString, out lastVerificationStatusDate);
                  if(success)
                  {
                    using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString))
                    {
                      entry_status_update_time time = new entry_status_update_time() { last_verification_status_update_date = lastVerificationStatusDate, date_received = DateTime.Now };
                      dc.entry_status_update_times.InsertOnSubmit(time);
                      dc.SubmitChanges();
                    }
                  }
                }

                //using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString)
                //{
                //  entry_status_update_time est = new entry_status_update_time() { date_received = DateTime.Now, last_verification_status_update_date = entry
                //}
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "{0} entries downloaded", entryList.Count);
                TimeSpan expirationPeriod = new TimeSpan(3,0,0,0);
                DateTime now = DateTime.Now;
                foreach (leader_entry entry in entryList)
                {
                  // Na razie zakładam prostą obsługę - jeżeli przyjdzie wniosek o takim samym transaction Id - robię update na bazie
                  //
                  // jeśli transaction_id pojawia się po raz pierwszy, robię instert
                  try
                  {
                    using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString))
                    {
                      leader_entry entryFromBase = (from le in dc.leader_entries
                                                  where le.transactionId == entry.transactionId
                                                  select le).FirstOrDefault();
                      if (entryFromBase != null)
                      {
                        //Wniosek istniał w bazie - update
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Entry {0} allready exists in database. Updating fields.", entry.entryId);
                        CopyEntryFields(entry, entryFromBase);

                      }
                      else
                      {
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Entry {0} does not exist in database. Creating new entry.", entry.entryId);
                        entryFromBase = new leader_entry();
                        CopyEntryFields(entry, entryFromBase);
                        entryFromBase.transactionId = entry.transactionId;
                        entryFromBase.dateReceived = DateTime.Now; //Data rzeczywistego pobrania wniosku
                        dc.leader_entries.InsertOnSubmit(entryFromBase);
                      }
                      dc.SubmitChanges();
                    }
                  }
                  catch (Exception ex)
                  {
                    throw ex;
                  }
                }
                //Przedawnianie wniosków - dokładnie omówić z PL - wydaje mi się że moje podejście jest dobre
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Staring the expiration process");
                using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString))
                  {
                  var allExpiredEntries = (from entry in dc.leader_entries
                                   join itn in dc.itn_transactions on entry.transactionId equals itn.orderID into itng
                                   from itng_ in itng.DefaultIfEmpty()
                                           where entry.status == 0 &&
                                           ((itng_ == null && now - entry.createDate  > expirationPeriod) || (itng_ != null && itng_.transDate - entry.createDate > expirationPeriod))
                                   select entry).ToList();

                  if(allExpiredEntries.Count == 0)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "No entry has recently expired.");
                  }
                  else if(allExpiredEntries.Count == 1)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "1 entry has recently expired.");
                  }
                  else
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "{0} entries have recently expired.", allExpiredEntries.Count);
                  }

                  foreach(var entry in allExpiredEntries)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Setting the expired status for entry {0}", entry.entryId);
                    entry.status = 100;
                  }
                  dc.SubmitChanges();
                  }
              }
              else
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, "Could not get valid response from Leader. Error: {0}",answer.AnswerCode.ToString());
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Full response xml:", answer.ResponseXml.ToString());
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Save dynamic configuration");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Finish processing");

            }
            catch (Exception ex)
            {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, ex, "");
                result = -1;
            }
            return result;
        }