This class represents a response of DB transaction.
    private void displayMessageToTheUser(TransactionResponse response, bool noNotification)
    {
        if (noNotification)
        {
            InfoDIV.Visible = true;
            lblInformationMsg.Text = "You have no notification sent to you";
            return;
        }

        switch (response.getMessageType())
        {
            case TransactionResponse.SeverityLevel.SUCESS:
                SucessDIV.Visible = true;
                lblErrorMsg.Text = response.getMessage();
                break;
            case TransactionResponse.SeverityLevel.INFO:
                InfoDIV.Visible = true;
                lblInformationMsg.Text = response.getMessage();
                break;
            case TransactionResponse.SeverityLevel.WARNING:
                WarnDIV.Visible = true;
                lblWarningMsg.Text = response.getMessage() + response.getErrorCode() ;
                break;
            case TransactionResponse.SeverityLevel.ERROR:
                ErroroDIV.Visible = true;
                lblErrorMsg.Text = response.getMessage() + response.getErrorCode();
                break;
        }
    }
    /**
     * Return list of vacancy which have this status.
     */
    public static TransactionResponse getAllActiveVacancy(string status)
    {
        TransactionResponse response = new TransactionResponse();
        IDictionary<string, object> statusParams = new Dictionary<string, object>();
        statusParams.Add("@status", status);
        statusParams.Add("@districtId", PageAccessManager.getDistrictID());

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil dpOperation = new DBOperationsUtil(DbAccessConstants.spAllActiveVacancy, statusParams);
        try
        {
            DataTable dataTable = dpOperation.getRecord();

            response.Data = dataTable;
            response.setSuccess(true);
        }
        catch (SqlException ex)
        {
            //Other SqlException is catched
            response.setSuccess(false);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setMessage(DBOperationErrorConstants.M_UNKNOWN_EVIL_ERROR);
            response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            LoggerManager.LogError(ex.ToString(), logger);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }
        return response;
    }
 public static void upDateWithGenericErrorMessage(TransactionResponse response)
 {
     //Display generic message.
     response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
     response.setMessage(DBOperationErrorConstants.M_SYSTEM_ENCOUNTERED_UNKNOWN_ERROR);
     response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_EVIL_ERROR);
     response.setSuccess(false);
 }
    public static TransactionResponse getAllNotificationsForCurrentEmployee(MembershipUser currentUser)
    {
        //get detail of the logged on user.
        Employee employee = EmployeeManager.getLoggedOnUser((Guid)currentUser.ProviderUserKey);

        if (employee == null)
        {
            return EmployeeManager.handleLoggedInUserCanNotBeIdentfied();
        }

        TransactionResponse response = new TransactionResponse();
        try
        {
            IDictionary<string, object> employeeIdMap = new Dictionary<string, object>();
            employeeIdMap.Add("@EMP_ID", employee.EmpID);
            employeeIdMap.Add("@destrictID", PageAccessManager.getDistrictID());

            //Pass Stored Procedure Name and parameter list.
            DBOperationsUtil dbOperation = new DBOperationsUtil(DbAccessConstants.spGetAllNotificationForTheCurrentEmployee, employeeIdMap);
            DataTable dataTable = dbOperation.getRecord();
            //put the data on Transaction response
            response.Data = dataTable;
            response.setSuccess(true);
            response.setMessageType(TransactionResponse.SeverityLevel.INFO);
            response.setMessage(DBOperationErrorConstants.M_NOTIFICATION_INFO);
            //get Notifications inside the TransactionResponse.
            return response;
        }
        catch (SqlException ex)
        {
            response.setErrorCode(DBOperationErrorConstants.E_ERROR_WHILE_READING_NOTIFICATION);
            response.setMessage(DBOperationErrorConstants.M_ERROR_WHILE_READING_NOTIF);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setSuccess(false);
            return response;
        }

           //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            LoggerManager.LogError(ex.ToString(), logger);
            response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_EVIL_ERROR);
            response.setMessage(DBOperationErrorConstants.M_UNKNOWN_EVIL_ERROR);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setSuccess(false);
            return response;
        }
    }
    public static TransactionResponse getDistrictSettingValue(string paramTag)
    {
        TransactionResponse response = new TransactionResponse();

        IDictionary<string, object> argumentsMap = new Dictionary<string, object>();
        argumentsMap.Add("@paramter_tag", paramTag);
        argumentsMap.Add("@districtID", PageAccessManager.getDistrictID());

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil dbOperation = new DBOperationsUtil(DbAccessConstants.spGetDistrictSetting, argumentsMap);
        try
        {
            DataTable dataTable = dbOperation.getRecord();
            if (dataTable != null)
            {
                foreach (DataRow row in dataTable.Rows)
                {
                    //put the data on Transaction reponse
                    response.Data = row["parameter_value"].ToString();
                    response.setSuccess(true);
                    return response;
                }
            }
            response.Data = PARAMETER_NOT_DEFINED + DBOperationErrorConstants.CONTACT_ADMIN;
            response.setSuccess(false);
            return response;
        }
        catch (SqlException ex)
        {
            response.Data = PARAMETER_NOT_DEFINED + DBOperationErrorConstants.CONTACT_ADMIN;
            response.setSuccess(false);
            return response;
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            LoggerManager.LogError(ex.ToString(), logger);
            response.Data = PARAMETER_NOT_DEFINED + DBOperationErrorConstants.CONTACT_ADMIN;
            response.setSuccess(false);
            return response;
        }
    }
Beispiel #6
0
    private TransactionResponse sendInsertPromotionToDb(string spName, IDictionary<string, object> parameters)
    {
        //Pass Stored Procedure Name and parameter list. 
        DBOperationsUtil storeToDb = new DBOperationsUtil(spName, parameters);

        TransactionResponse response = new TransactionResponse();
        try
        {
            //call store to DB mathod and get reponse. 
            storeToDb.instertNewRecord();
            response.setSuccess(true);
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setMessage(DBOperationErrorConstants.M_PROMOTION_REGISTER_OK);
        }

        catch (SqlException ex) 
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_PROMOTION_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_APP_RATING_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {            
            //Write this exception to file for investigation of the issue later. 
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }

        return response;
    }
        public TransactionResponse DownloadAllAsync(string orderref = "", bool includeInvoiceAndReceipts = true, DocumentStatus documentStatus = DocumentStatus.Closed)
        {
            var time =new TimeSpan(0,0,5,0);
            var time1 = TimeSpan.FromMinutes(5).Seconds;
            var task= Task.Run(async () =>
                                     {
                                          TransactionResponse res=new TransactionResponse();
                                          try
                                          {
                                              string url = string.Format(MiddlewareHttpClient.BaseAddress +
                                                                         "api/Integrations/Transaction?username={0}&password={1}&integrationModule={2}&documentRef={3}&includeInvoiceAndReceipts={4}&documentStatus={5}",
                                                                         _userName,
                                                                         _otherUtilities.MD5Hash(_password),
                                                                         module, orderref,
                                                                         includeInvoiceAndReceipts,documentStatus);
                                              Messenger.Default.Send(
                                                  string.Format(DateTime.Now.ToString("hh:mm:ss") +
                                                                ":Contacting Server =>" +
                                                                MiddlewareHttpClient.BaseAddress));

                                              HttpResponseMessage response =
                                                  await MiddlewareHttpClient.GetAsync(url);
                                              Messenger.Default.Send(
                                                  string.Format(DateTime.Now.ToString("hh:mm:ss") +
                                                                ":Server Response=>" + response.StatusCode));
                                              res=await response.Content.ReadAsAsync<TransactionResponse>();
                                          }catch(Exception ex)
                                          {
                                              
                                          }

                                          return res;
                                          
                                      });

             //Task.Delay(TimeSpan.FromMinutes(5).Seconds);

            task.Wait(time);
            return task.Result;

        }
Beispiel #8
0
        /// <summary>
        /// Create QR Codes given a DealerPA, creates based upon what QRCodes and Catalogs already exist in the database.
        /// </summary>
        /// <param name="dealerPa"></param>
        /// <returns></returns>
        public TransactionResponse CreateQRCodeByDealerPa(string dealerPa, string userName)
        {
            var response = new TransactionResponse();
            try
            {
                var dealerSproc = new DealerGetDealerPaStoredProcedure();
                dealerSproc.SprocParameters["@DealerPa"] = dealerPa;

                var dealers =
                    _responseController.SprocController.ExecuteEntitySet<DealerGetDealerPaStoredProcedure, Dealer>(dealerSproc);

                var catalogs =
                    _responseController.SprocController.ExecuteEntitySet<CatalogGetInDealerQrCodesStoredProcedure, Catalog>(new CatalogGetInDealerQrCodesStoredProcedure());

                var dealerQrCodes = new List<DealerQRCode>();
                foreach (var catalog in catalogs)
                {
                    dealerQrCodes.AddRange(BuildDealerQRCodes(catalog, dealers));
                }

                var qrCodes = BuildQRCodes(dealerQrCodes);

                var container = BuildDealerQRCodeContainer(dealerQrCodes, qrCodes);
                response.ResponseCode = 200;

                ProcessQrCodes(container, ref response, userName);

                response.Message = "Success.";

            }
            catch (Exception exc)
            {
                response.Message = string.Format("Error! {0}", exc.Message);
                //response.Count = 0;
                response.ResponseCode = 500;
                //response.DealerPa = dealerPa;
                LogWriter.LogException(new Exception(string.Format("Qr Code Create For Dealers, DealerPa: {0}", dealerPa)), exc);
            }
            return response;
        }
    protected void Page_Load(object sender, EventArgs e)
    {

        VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager();
        TransactionResponse response = new TransactionResponse();
        response = manager.getVacancyToAnnounceToOutside();
        gvRss.Visible = true;
        DataTable vacancyDetail = (DataTable)response.Data;

        if (vacancyDetail != null && vacancyDetail.Rows.Count > 0)
        {
            msgDIV.Visible = false;
            noticeDIV.Visible = true;
            gvRss.DataSource = vacancyDetail;
            gvRss.DataBind();
        }
        else
        {
            noticeDIV.Visible = false;
            msgDIV.Visible = true;
        }
    }
    private void displayMessageToTheUser(TransactionResponse response)
    {
        clearMsgPanel();

        switch (response.getMessageType())
        {
            case TransactionResponse.SeverityLevel.SUCESS:
                msgPanel.Visible = true;
                SucessDIV.Visible = true;
                lblSuccessMessage.Text = response.getMessage();
                break;
            case TransactionResponse.SeverityLevel.INFO:
                msgPanel.Visible = true;
                InfoDIV.Visible = true;
                lblInformationMsg.Text = response.getMessage();
                break;
            case TransactionResponse.SeverityLevel.WARNING:
                msgPanel.Visible = true;
                WarnDIV.Visible = true;
                if (response.getErrorCode() != null)
                {
                    lblWarningMsg.Text = response.getMessage() + response.getErrorCode();
                    break;
                }
                lblWarningMsg.Text = response.getMessage();
                break;
            case TransactionResponse.SeverityLevel.ERROR:
                msgPanel.Visible = true;
                ErroroDIV.Visible = true;
                if (response.getErrorCode() != null)
                {
                    lblErrorMsg.Text = response.getMessage() + response.getErrorCode();
                    break;
                }
                lblErrorMsg.Text = response.getMessage();
                break;

        }
    }
    public TransactionResponse addNewPromotionAssignment()
    {
        //Add List of Arguments for new promotion Assigment
        IDictionary<string, object> promotionAssigmentParameters = new Dictionary<string, object>();

        promotionAssigmentParameters.Add("@minNo", promotionAssigment.MinuteNo);
        promotionAssigmentParameters.Add("@hROfficerID", promotionAssigment.HROfficerID);
        promotionAssigmentParameters.Add("@deadLine", promotionAssigment.DeadLine);
        promotionAssigmentParameters.Add("@remark", promotionAssigment.Remark);

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil dpOperation = new DBOperationsUtil(DbAccessConstants.spAddPromotionAssignmentToHROfficer, promotionAssigmentParameters);
        TransactionResponse response = new TransactionResponse();
        try
        {
            //call update to DB mathod and get reponse.
            dpOperation.updateRecord();
            response.setSuccess(true);
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setMessage(DBOperationErrorConstants.M_VACANCY_ASSIGNED_SUCCESS);
        }

        catch (SqlException ex)
        {
            //Other SqlException is catched
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setMessage(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR + ". "+ DBOperationErrorConstants.M_DUPLICATE_PROMOTION_ASSIGNEMENT);
            response.setErrorCode(DBOperationErrorConstants.E_PROMOTION_ASSIGNEMETN_FAILED);
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }
        return response;
    }
        public TransactionResponse[] GetTransactions()
        {
            List<TransactionResponse> actResponse = new List<TransactionResponse>();

            int count = Convert.ToInt32(UIUtil.DefaultProvider.GetXPathCountByXPath(TransactionRows)) - 1;

            for (int i = 0; i < count; i++)
            {
                TransactionResponse response = new TransactionResponse();
                response.Id = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[1]", i + 1), LocateBy.XPath);
                response.Date = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[2]", i + 1), LocateBy.XPath);
                response.Type = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[3]", i + 1), LocateBy.XPath);
                response.Notes = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[5]", i + 1), LocateBy.XPath);
                response.Amount = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[6]", i + 1), LocateBy.XPath);
                response.SubTotal = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[7]", i + 1), LocateBy.XPath);
                response.AddBy = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[8]", i + 1), LocateBy.XPath);
                response.ModBy = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[9]", i + 1), LocateBy.XPath);
                response.Delete = UIUtil.DefaultProvider.GetText(string.Format(TransactionRows + "[{0}]/td[10]", i + 1), LocateBy.XPath);
                actResponse.Add(response);
            }

            return actResponse.ToArray();
        }
Beispiel #13
0
        public ActionResult CreditVoid(int id, string type, decimal?amt, TransactionsModel m)
        {
            var t = DbUtil.Db.Transactions.SingleOrDefault(tt => tt.Id == id);

            if (t == null)
            {
                return(Content("notran"));
            }
            var qq = from tt in DbUtil.Db.Transactions
                     where tt.OriginalId == id || tt.Id == id
                     orderby tt.Id descending
                     select tt;
            var t0   = qq.First();
            var sage = new SagePayments(DbUtil.Db, t.Testing ?? false);
            TransactionResponse resp = null;
            var re = t.TransactionId;

            if (re.Contains("(testing"))
            {
                re = re.Substring(0, re.IndexOf("(testing)"));
            }
            if (type == "Void")
            {
                resp = sage.voidTransactionRequest(re);
                if (!resp.Approved)
                {
                    resp = sage.voidCheckRequest(re);
                }
                if (resp.Approved)
                {
                    t.Voided = true;
                }
                amt = t.Amt;
            }
            else
            {
                if (t.Batchtyp == "eft")
                {
                    resp = sage.creditCheckTransactionRequest(re, amt ?? 0);
                }
                else if (t.Batchtyp == "bankcard")
                {
                    resp = sage.creditTransactionRequest(re, amt ?? 0);
                }
                if (resp.Approved)
                {
                    t.Credited = true;
                }
            }
            if (!resp.Approved)
            {
                return(Content("error: " + resp.Message));
            }
            else             // approved
            {
                var tt = new Transaction
                {
                    TransactionId      = resp.TransactionId + (t.Testing == true ? "(testing)" : ""),
                    First              = t.First,
                    MiddleInitial      = t.MiddleInitial,
                    Last               = t.Last,
                    Suffix             = t.Suffix,
                    Amt                = -amt,
                    Amtdue             = t0.Amtdue + amt,
                    Approved           = true,
                    AuthCode           = t.AuthCode,
                    Message            = t.Message,
                    Donate             = -t.Donate,
                    Regfees            = -t.Regfees,
                    TransactionDate    = DateTime.Now,
                    TransactionGateway = t.TransactionGateway,
                    Testing            = t.Testing,
                    Description        = t.Description,
                    OrgId              = t.OrgId,
                    OriginalId         = t.OriginalId,
                    Participants       = t.Participants,
                    Financeonly        = t.Financeonly,
                };
                DbUtil.Db.Transactions.InsertOnSubmit(tt);
                DbUtil.Db.SubmitChanges();
                Util.SendMsg(Util.SysFromEmail, Util.Host,
                             Util.TryGetMailAddress(DbUtil.Db.StaffEmailForOrg(tt.OrgId ?? 0)),
                             "Void/Credit Transaction Type: " + type,
                             @"<table>
<tr><td>Name</td><td>{0}</td></tr>
<tr><td>Email</td><td>{1}</td></tr>
<tr><td>Address</td><td>{2}</td></tr>
<tr><td>Phone</td><td>{3}</td></tr>
<tr><th colspan=""2"">Transaction Info</th></tr>
<tr><td>Description</td><td>{4}</td></tr>
<tr><td>Amount</td><td>{5:N2}</td></tr>
<tr><td>Date</td><td>{6}</td></tr>
<tr><td>TranIds</td><td>Org: {7} {8}, Curr: {9} {10}</td></tr>
<tr><td>User</td><td>{11}</td></tr>
</table>".Fmt(Transaction.FullName(t), t.Emails, t.Address, t.Phone,
              t.Description,
              -amt,
              t.TransactionDate.Value.FormatDateTm(),
              t.Id, t.TransactionId, tt.Id, tt.TransactionId, Util.UserFullName
              ), Util.EmailAddressListFromString(DbUtil.Db.StaffEmailForOrg(tt.OrgId ?? 0)),
                             0, 0);
            }
            DbUtil.LogActivity("CreditVoid for " + t.TransactionId);
            return(View("List", m));
        }
Beispiel #14
0
        public async Task <bool> SettleUpAsync(TransactionResponse transaction)
        {
            Transaction transactions = new Transaction();

            if (transaction.groupId != 0)
            {
                transactions.groupId = transaction.groupId;
            }
            transactions.paid_amount = transaction.paid_amount;
            transactions.payeeId     = transaction.payeeId;
            transactions.payerId     = transaction.payerId;
            transactions.paid_on     = transaction.paid_on;
            _Context.transactions.Add(transactions);
            //await _Context.SaveChangesAsync();

            var settle = await _Context.settlements.FirstOrDefaultAsync(c =>
                                                                        c.payeeId == transactions.payeeId && c.payerId == transactions.payerId &&
                                                                        c.groupId == transactions.groupId);

            if (settle != null)
            {
                settle.amount = settle.amount - transactions.paid_amount;
                _Context.settlements.Attach(settle);
            }
            else
            {
                if (transaction.groupId != 0)
                {
                    Settlements settlements = new Settlements();
                    settlements.payerId = transactions.payeeId;
                    settlements.payeeId = transactions.payerId;
                    settlements.amount  = transactions.paid_amount;
                    settlements.groupId = transactions.groupId;

                    var settle1 = await _Context.settlements.FirstOrDefaultAsync(c =>
                                                                                 c.payeeId == settlements.payeeId && c.payerId == settlements.payerId);

                    if (settle1 != null)
                    {
                        settle1.amount = settle1.amount + transactions.paid_amount;
                        _Context.settlements.Attach(settle1);
                    }
                    else
                    {
                        _Context.settlements.Add(settlements);
                    }
                }
                else
                {
                    Settlements settlements = new Settlements();
                    settlements.payerId = transactions.payeeId;
                    settlements.payeeId = transactions.payerId;
                    settlements.amount  = transactions.paid_amount;

                    var settle1 = await _Context.settlements.FirstOrDefaultAsync(c =>
                                                                                 c.payeeId == settlements.payeeId && c.payerId == settlements.payerId);

                    if (settle1 != null)
                    {
                        settle1.amount = settle1.amount + transactions.paid_amount;
                        _Context.settlements.Attach(settle1);
                    }
                    else
                    {
                        _Context.settlements.Add(settlements);
                    }
                }
            }
            try
            {
                return(await _Context.SaveChangesAsync() > 0 ? true : false);
            }
            catch (Exception exp)
            {
                _Logger.LogError($"Error in {nameof(SettleUpAsync)}: " + exp.Message);
            }
            return(false);
        }
    /**
     * Get Inactive employee by date interval
     */
    public TransactionResponse getInactiveEmployeeResult(string startedDate, string endDate)
    {
        TransactionResponse response = new TransactionResponse();
        try
        {
            //Add List of Arguments for new employee
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("@startDate", startedDate);
            parameters.Add("@endDate", endDate);

            DBOperationsUtil dpOperation = new DBOperationsUtil(DbAccessConstants.spGetInactiveEmployeeDetail, parameters);

            DataTable getResult = dpOperation.getRecord();
            if (getResult != null && getResult.Rows.Count > 0)
            {
                response.Data = getResult;
                response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
                response.setMessage(DBOperationErrorConstants.M_REPORT_GENERATED_SUCCESS);
                response.setSuccess(true);
                return response;
            }
            else
            {
                response.setMessageType(TransactionResponse.SeverityLevel.INFO);
                response.setMessage(DBOperationErrorConstants.M_GENERATE_INACTIVE_EMPLOYEE_REPORT_EMPTY);
                response.setSuccess(false);
                return response;
            }
        }
        catch (SqlException ex)
        {
            //Other SqlException is catched
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setMessage(DBOperationErrorConstants.M_UNABLE_TO_GENERATE_INACTIVE_EMPLOYEE);
            response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            response.setSuccess(false);
        }
        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }
        return response;
    }
Beispiel #16
0
        public override void ProcessTransaction(Transaction t)
        {
            bool result = false;

            //'Get Configuration Settings
            string MerchantPartner  = Settings.MerchantPartner;
            string MerchantLogin    = Settings.MerchantLogin;
            string MerchantUser     = Settings.MerchantUser;
            string MerchantPassword = Settings.MerchantPassword;
            string CurrencyCode     = Settings.CurrencyCode;
            bool   TestMode         = Settings.TestMode;
            bool   DebugMode        = Settings.DeveloperMode;

            UserInfo User = new UserInfo(MerchantUser, MerchantLogin, MerchantPartner, MerchantPassword);


            //Set HostAddress URL
            string HostAddress = LiveUrl;

            if (TestMode)
            {
                HostAddress = TestUrl;
            }

            //Connection Info
            PayflowConnectionData Connection = new PayflowConnectionData(HostAddress, 443, 45); //', CertLocation)

            // *** Create a new Invoice data object ***
            // Set Invoice object with the Amount, Billing & Shipping Address, etc. ***
            Invoice Inv = new Invoice();

            // Set the amount object. A valid amount is a two decimal value.  An invalid amount will generate a result code
            Currency Amt = new Currency(Decimal.Round(t.Amount, 2), CurrencyCode); //' 840 is US ISO currency code.  If no code passed, 840 is default.

            Inv.Amt = Amt;

            // Generate a unique transaction ID
            string strRequestID = PayflowUtility.RequestId + t.MerchantInvoiceNumber;

            //InvNum and CustRef are sent to the processors and could show up on a customers
            // or your bank statement. These fields are reportable but not searchable in PayPal Manager.

            Inv.InvNum  = t.MerchantInvoiceNumber;
            Inv.CustRef = t.Customer.Email;

            //' Comment1 and Comment2 fields are searchable within PayPal Manager .
            Inv.Comment1 = "Order Number: " + Inv.InvNum;
            Inv.Comment2 = "Customer Email: " + t.Customer.Email;

            // Create the BillTo object.
            BillTo Bill = new BillTo();

            Bill.FirstName = t.Customer.FirstName;
            Bill.LastName  = t.Customer.LastName;
            Bill.Street    = t.Customer.Street;
            Bill.City      = t.Customer.City;
            Bill.Zip       = t.Customer.PostalCode;
            Bill.PhoneNum  = t.Customer.Phone;
            Bill.Email     = t.Customer.Email;
            Bill.State     = t.Customer.Region;

            //' BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            //Get Country Code
            string CountryCode = MerchantTribe.Web.Geography.Country.FindByName(t.Customer.Country).IsoNumeric;

            Bill.BillToCountry = CountryCode;

            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;

            CustomerInfo CustInfo = new CustomerInfo();

            CustInfo.CustId = t.Customer.Email;
            CustInfo.CustIP = t.Customer.IpAddress;

            // *** Create a new Payment Device - Credit Card data object. ***
            // Note: Expiration date is in the format MMYY
            string CCExpDate = t.Card.ExpirationMonthPadded + t.Card.ExpirationYearTwoDigits;

            CreditCard CC = new CreditCard(t.Card.CardNumber, CCExpDate);

            //' *** Card Security Code ***
            //' This is the 3 or 4 digit code on either side of the Credit Card.
            if (t.Card.SecurityCode.Length > 0)
            {
                CC.Cvv2 = t.Card.SecurityCode;
            }

            // Name on Credit Card is optional.
            CC.Name = t.Card.CardHolderName;

            // *** Create a new Tender - Card Tender data object. ***
            CardTender Card = new CardTender(CC);

            // *** Create a new Transaction. ***
            // The Request Id is the unique id necessary for each transaction.
            // If you pass a non-unique request id, you will receive the transaction details from the original request.

            //'DO TRANSACTION
            try
            {
                BaseTransaction Trans = null;

                switch (t.Action)
                {
                case ActionType.CreditCardHold:
                    Trans = new AuthorizationTransaction(User, Connection, Inv, Card, strRequestID);
                    break;

                case ActionType.CreditCardCharge:
                    Trans = new SaleTransaction(User, Connection, Inv, Card, strRequestID);
                    break;

                case ActionType.CreditCardCapture:
                    Trans = new CaptureTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID);
                    break;

                case ActionType.CreditCardRefund:
                    Trans = new CreditTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID);
                    break;

                case ActionType.CreditCardVoid:
                    Trans = new VoidTransaction(t.PreviousTransactionNumber, User, Connection, strRequestID);
                    break;
                }

                int Result = 0;
                System.Globalization.CultureInfo currCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
                Response Resp = null;

                try
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
                    //' Submit the Transaction
                    Resp = Trans.SubmitTransaction();
                }
                finally
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture = currCulture;
                }

                if (Resp != null)
                {
                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;

                    // RESULT codes returns.
                    if (TrxnResponse != null)
                    {
                        //Check for Approval (0 = approved, all else = Decline or Error)
                        Result = TrxnResponse.Result;
                        string RespMsg = TrxnResponse.RespMsg;

                        //if success then save our reference number
                        if (Result == 0)
                        {
                            t.Result.ReferenceNumber = TrxnResponse.Pnref;
                        }

                        t.Result.ResponseCode = TrxnResponse.AuthCode;

                        //Custom Properties
                        t.Result.AvsCode                 = AvsResponseType.Unavailable;
                        t.Result.AvsCodeDescription      = "AVSADDR: " + TrxnResponse.AVSAddr + " AVSZIP: " + TrxnResponse.AVSZip + " IAVS: " + TrxnResponse.IAVS;
                        t.Result.ResponseCode            = TrxnResponse.Result.ToString();
                        t.Result.CvvCode                 = CvnResponseType.Unavailable;
                        t.Result.CvvCodeDescription      = TrxnResponse.CVV2Match;
                        t.Result.ResponseCodeDescription = TrxnResponse.RespMsg;
                    }
                    else
                    {
                        t.Result.Messages.Add(new Message("Payment Error: Transaction Response is Null", "BVP_PFP_1003", MessageType.Error));
                    }

                    //Show Complete Response if Debug Mode
                    if (DebugMode)
                    {
                        t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Request, "REQ", MessageType.Information));
                        t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Response.ResponseString, "RES", MessageType.Information));

                        // Get the Transaction Context
                        Context TransCtx = Resp.TransactionContext;

                        if ((TransCtx != null) && (TransCtx.getErrorCount() > 0))
                        {
                            t.Result.Messages.Add(new Message("PayflowPro Context:" + TransCtx.ToString(), "CTX", MessageType.Information));
                        }
                    }

                    if (Result == 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    t.Result.Messages.Add(new Message("Payment Error: Response is Null", "BVP_PFP_1002", MessageType.Error));
                }
            }
            catch (Exception ex)
            {
                result = false;
                t.Result.Messages.Add(new Message("Payment Error: " + ex.Message, "BVP_PFP_1001", MessageType.Error));
                t.Result.Messages.Add(new Message("Stack Trace " + ex.StackTrace, "STACKTRACE", MessageType.Error));
            }

            t.Result.Succeeded = result;
        }
        private static string GetResonseMessage(TransactionResponse TrxnResponse)
        {
            string RespMsg;

            if (TrxnResponse.Result < 0)
            {
                // Transaction failed.
                RespMsg = "There was an error processing your transaction." +
                          Environment.NewLine + "Error: " + TrxnResponse.Result.ToString();
            }
            else if (TrxnResponse.Result == 1 || TrxnResponse.Result == 26)
            {
                RespMsg = "Account configuration issue.  Please verify your login credentials.";
            }
            else if (TrxnResponse.Result == 0)
            {
                // Example of a message you might want to display with an approved transaction.
                RespMsg = "Your transaction was approved.";
            }
            else if (TrxnResponse.Result == 12)
            {
                // Hard decline from bank.  Customer will need to use another card or payment type.
                RespMsg = "Your transaction was declined.";
            }
            else if (TrxnResponse.Result == 13)
            {
                // Voice authorization required.  You would need to contact your merchant bank to obtain a voice authorization.  If authorization is
                // given, you can manually enter it via Virtual Terminal in PayPal Manager or via the VoiceAuthTransaction object.
                RespMsg = "Your Transaction is pending. Contact Customer Service to complete your order.";
            }
            else if (TrxnResponse.Result == 23 || TrxnResponse.Result == 24)
            {
                // Issue with credit card number or expiration date.
                RespMsg = "Invalid credit card information. Please re-enter.";
            }
            else if (TrxnResponse.Result == 125)
            {
                RespMsg = "Your Transactions has been declined.";
            }
            else if (TrxnResponse.Result == 126)
            {
                // Decline transaction if AVS fails.
                if (TrxnResponse.AVSAddr != "Y" || TrxnResponse.AVSZip != "Y")
                {
                    RespMsg = "Your billing information does not match.  Please re-enter.";
                }
                else
                {
                    RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                }
                RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
            }
            else if (TrxnResponse.Result == 127)
            {
                // There is an issue with checking this transaction through the fraud service.
                // You will need to manually approve.
                RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
            }
            else
            {
                // Error occurred, display normalized message returned.
                RespMsg = TrxnResponse.RespMsg;
            }

            return(RespMsg);
        }
Beispiel #18
0
    private void logCustomTransaction(string id, string cardcode)
    {
        try
        {
            TransactionResponse resp = transObjForImport.Response;

            CCTRAN cctran = new CCTRAN();
            cctran.OrderID      = id;
            cctran.InvoiceID    = "";
            cctran.CreditMemoID = "";
            cctran.customerID   = cardcode;
            cctran.MethodID     = "";
            cctran.custNum      = "";
            string currency = getCurrency("ORDR", id);
            string group    = getGroupName(cardcode);
            string cardtype = transObjForImport.CreditCardData.CardType;
            string acctid   = "";
            string cardName = getCardName(group, cardtype, currency, ref acctid);
            cctran.CCAccountID = int.Parse(acctid);

            cctran.crCardNum   = transObjForImport.CreditCardData.CardNumber;
            cctran.Description = transObjForImport.Details.Description;
            cctran.recID       = transObjForImport.Details.Invoice;

            cctran.acsUrl                  = resp.AcsUrl;
            cctran.authAmount              = resp.AuthAmount.ToString();
            cctran.authCode                = resp.AuthCode;
            cctran.avsResult               = resp.AvsResult;
            cctran.avsResultCode           = resp.AvsResultCode;
            cctran.batchNum                = resp.BatchNum;
            cctran.batchRef                = resp.BatchRefNum;
            cctran.cardCodeResult          = resp.CardCodeResult;
            cctran.cardCodeResultCode      = resp.CardCodeResultCode;
            cctran.cardLevelResult         = resp.CardLevelResult;
            cctran.cardLevelResultCode     = resp.CardLevelResultCode;
            cctran.conversionRate          = resp.ConversionRate.ToString();
            cctran.convertedAmount         = resp.ConvertedAmount.ToString();
            cctran.convertedAmountCurrency = resp.ConvertedAmountCurrency.ToString();
            cctran.custNum                 = resp.CustNum;
            cctran.error            = resp.Error;
            cctran.errorCode        = resp.ErrorCode;
            cctran.isDuplicate      = resp.isDuplicate.ToString();
            cctran.payload          = resp.Payload;
            cctran.profilerScore    = resp.ProfilerScore;
            cctran.profilerResponse = resp.ProfilerResponse;
            cctran.profilerReason   = resp.ProfilerReason;
            cctran.refNum           = resp.RefNum;
            cctran.remainingBalance = resp.RemainingBalance.ToString();
            cctran.result           = resp.Result;
            cctran.resultCode       = resp.ResultCode;
            cctran.status           = resp.Status;
            cctran.statusCode       = resp.StatusCode;
            cctran.vpasResultCode   = resp.VpasResultCode;
            cctran.recDate          = DateTime.Now;//Use local time not server time
            cctran.command          = transObjForImport.TransactionType;
            if (transObjForImport.TransactionType == "Auth Only")
            {
                cctran.command = "cc:authonly";
            }
            cctran.amount = transObjForImport.Details.Amount.ToString();

            insert(cctran);
        }
        catch (Exception ex)
        {
            errorLog(ex);
        }
    }
Beispiel #19
0
 static ResponseCodeEnum getResponseCode(TransactionResponse response)
 {
     return(response.NodeTransactionPrecheckCode);
 }
Beispiel #20
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOSaleComplete.cs");
            Console.WriteLine("------------------------------------------------------");

            //
            // PLEASE READ ALL COMMENTS BELOW:
            // All information regarding the available objects within payflow_dotNET.dll can be found in the API doc
            // found under the "Docs" directory of the installed SDK.  You will also need to refer to the Website
            // Payments Pro Payflow Edition or Payflow Pro Developer’s Guide found in the downloads section of PayPal
            // Manager at https://manager.paypal.com or on the "X.COM" developers forum at
            // https://www.x.com/community/ppx/payflow_pro?view=documents
            //
            // This SDK is based on the HTTPS Service and it is highly suggested you read the post on the developer's forum
            // at https://www.x.com/docs/DOC-1642 to better understand what is happening behind the scenes.
            //
            // Regarding the Request ID:
            //
            // The request Id is a unique id that you send with your transaction data.  This Id if not changed
            // will help prevent duplicate transactions.  The idea is to set this Id outside the loop or if on a page,
            // prior to the final confirmation page.
            //
            // Once the transaction is sent and if you don't receive a response you can resend the transaction and the
            // server will respond with the response data of the original submission.  Also, the object,
            // Trans.Response.TransactionResponse.Duplicate will be set to "1" if the transaction is a duplicate.
            //
            // This allows you to resend transaction requests should there be a network or user issue without re-charging
            // a customers credit card.
            //
            // COMMON ISSUES:
            //
            // Result Code 1:
            // Is usually caused by one of the following:
            //		** Invalid login information, see result code 26 below.
            //		** IP Restrictions on the account. Verify there are no ip restrictions in Manager under Service Settings.
            //
            // Result Code 26:
            // Verify USER, VENDOR, PARTNER and PASSWORD. Remember, USER and VENDOR are both the merchant login
            // ID unless a Payflow Pro USER was created.  All fields are case-sensitive. See this post for more
            // information: http://www.x.com/docs/DOC-1884.
            //
            // Receiving Communication Exceptions or No Response:
            // Since this service is based on HTTPS it is possible that due to network issues either on PayPal's side or
            // yours that you can not process a transaction.  If this is the case, what is suggested is that you put some
            // type of loop in your code to try up to X times before "giving up".  This example will try to get a response
            // up to 3 times before it fails and by using the Request ID as described above, you can do these attempts without
            // the chance of causing duplicate charges on your customer's credit card.
            //
            // END COMMENTS

            // Begin Application
            //
            // Set the Request ID
            // Uncomment the line below and run two concurrent transactions to show how duplicate works.  You will notice on
            // the second transaction that the response returned is identical to the first, but the duplicate object will be set.
            // String strRequestID = "123456";
            // Comment out this line if testing duplicate response.
            String RequestID = PayflowUtility.RequestId;

            // *** Create the Data Objects. ***
            //
            // *** Create the User data object with the required user details. ***
            //
            // Should you choose to store the login information (Vendor, User, Partner and Password) in
            // app.config, you can retrieve the data using PayflowUtility.AppSettings.
            //
            // For Example:
            //
            //      App.Config Entry: <add key="PayflowPartner" value="PayPal"/>
            //
            //      String mUser = PayflowUtility.AppSettings("PayflowUser");
            //      String mVendor = PayflowUtility.AppSettings("PayflowVendor");
            //      String mPartner = PayflowUtility.AppSettings("PayflowPartner");
            //      String mPassword = PayflowUtility.AppSettings("PayflowPassword");
            //
            // UserInfo User = new UserInfo (mUser, mVendor, mPartner, mPassword);

            // Remember: <vendor> = your merchant (login id), <user> = <vendor> unless you created a separate <user> for Payflow Pro.
            // Result code 26 will be issued if you do not provide both the <vendor> and <user> fields.

            // The other most common error with authentication is result code 1, user authentication failed.  This is usually
            // due to invalid account information or ip restriction on the account.  You can verify ip restriction by logging
            // into Manager.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");


            // *** Create the Payflow Connection data object with the required connection details. ***
            //
            // To allow the ability to change easily between the live and test servers, the PFPRO_HOST
            // property is defined in the App.config (or web.config for a web site) file.  However,
            // you can also pass these fields and others directly from the PayflowConnectionData contructor.
            // This will override the values passed in the App.config file.
            //
            // For Example:
            //
            //      Example values passed below are as follows:
            //      Payflow Pro Host address : pilot-payflowpro.paypal.com
            //      Payflow Pro Host Port : 443
            //      Timeout : 45 ( in seconds )
            //
            //      PayflowConnectionData Connection = new PayflowConnectionData("pilot-payflowpro.paypal.com", 443, 45, "",0,"","");
            //
            // Obtain Host address from the app.config file and use default values for
            // timeout and proxy settings.

            PayflowConnectionData Connection = new PayflowConnectionData();

            // *** Create a new Invoice data object ***
            // Set Invoice object with the Amount, Billing & Shipping Address, etc. ***

            Invoice Inv = new Invoice();

            // Creates a CultureInfo for English in the U.S.
            // Not necessary, just here for example of using currency formatting.
            CultureInfo us         = new CultureInfo("en-US");
            String      usCurrency = "USD";

            // Set the amount object. For Partial Authorizations, refer to the DoPartialAuth example.
            // Currency Code 840 (USD) is US ISO currency code.  If no code passed, 840 is default.
            // See the Developer's Guide for the list of the three-digit currency codes.
            Currency Amt = new Currency(new decimal(25.25), usCurrency);

            // A valid amount has either no decimal value or only a two decimal value.
            // An invalid amount will generate a result code 4.
            //
            // For values which have more than two decimal places such as:
            // Currency Amt = new Currency(new Decimal(25.1214));
            // You will either need to truncate or round as needed using the following property: Amt.NoOfDecimalDigits
            //
            // If the NoOfDecimalDigits property is used then it is mandatory to set one of the following
            // properties to true.
            //
            //Amt.Round = true;
            //Amt.Truncate = true;
            //
            // For Currencies without a decimal, you'll need to set the NoOfDecimalDigits = 0.
            //Amt.NoOfDecimalDigits = 0;
            Inv.Amt = Amt;

            // PONum, InvNum and CustRef are sent to the processors and could show up on a customers
            // or your bank statement. These fields are reportable but not searchable in PayPal Manager.
            Inv.PoNum   = "PO12345";
            Inv.InvNum  = "INV12345";
            Inv.CustRef = "CustRef1";

            // Soft descriptor, used to change information on customer's credit card. Refer to the Payflow Pro Developer's
            // Guide to verify that your processor supports these.
            //Inv.MerchDescr = "Merchant Descr"
            //Inv.MerchSvc = "Merchant Svc"

            // Comment1 and Comment2 fields are searchable within PayPal Manager .
            // You may want to populate these fields with any of the above three fields or any other data.
            // However, the search is a case-sensitive and is a non-wildcard search, so plan accordingly.
            Inv.Comment1 = "Comment1";
            Inv.Comment2 = "Comment2";

            // There are additional Invoice parameters that could assist you in obtaining a better rate
            // from your merchant bank.  Refer to the Payflow Pro Developer’s Guide
            // and consult your Internet Merchant Bank on what parameters (if any) you can use.
            // Some of the parameters could include:
            // Inv.Recurring = "Y";
            // Inv.TaxExempt = "Y";

            // *** Set the Billing Address details. ***
            //
            // The billing details below except for Street and Zip are for reporting purposes only.
            // It is suggested that you pass all the billing details for enhanced reporting and as data backup.

            // Create the BillTo object.
            BillTo Bill = new BillTo();

            // Set the customer name.
            Bill.BillToFirstName   = "Joe";
            Bill.BillToMiddleName  = "M";
            Bill.BillToLastName    = "Smith";
            Bill.BillToCompanyName = "Joe's Hardware";
            // It is highly suggested that you pass at minimum Street and Zip for AVS response.
            // However, AVS is only supported by US banks and some foreign banks.  See the Payflow
            // Developer's Guide for more information.  Sending these fields could help in obtaining
            // a lower discount rate from your Internet merchant Bank.  Consult your bank for more information.
            Bill.BillToStreet  = "123 Main St.";
            Bill.BillToStreet2 = "Suite A";
            Bill.BillToCity    = "San Jose";
            Bill.BillToState   = "CA";
            Bill.BillToZip     = "12345";
            // BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            // For more information, refer to the Payflow Developer's Guide.
            Bill.BillToCountry = "840";
            Bill.BillToPhone   = "555-243-7689";
            // Secondary phone numbers (could be mobile number etc).
            Bill.BillToPhone2    = "222-222-2222";
            Bill.BillToHomePhone = "555-123-9867";
            Bill.BillToFax       = "555-343-5444";
            Bill.BillToEmail     = "*****@*****.**";

            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;
            // ECHODATA allows you to trigger data sent in the request to be returned in the request.
            // 'ADDRESS' will return both shipping and billing address data, if sent.
            Inv.EchoData = "ADDRESS";

            // Shipping details may not be necessary if providing a
            // service or downloadable product such as software etc.
            //
            // Set the Shipping Address details.
            // The shipping details are for reporting purposes only.
            // It is suggested that you pass all the shipping details for enhanced reporting.
            //
            // Create the ShipTo object.
            ShipTo Ship = new ShipTo();

            // To prevent an 'Address Mismatch' fraud trigger, we are shipping to the billing address.  However,
            // shipping parameters are listed.
            // Comment line below if you want a separate Ship To address.
            Ship = Bill.Copy();

            // Uncomment statements below to send to separate Ship To address.

            // Set the recipient's name.
            // Ship.ShipToFirstName = "Sam";
            // Ship.ShipToMiddleName = "J";
            // Ship.ShipToLastName = "Spade";
            // Ship.ShipToStreet = "456 Shipping St.";
            // Ship.ShipToStreet2 = "Apt A";
            // Ship.ShipToCity = "Las Vegas";
            // Ship.ShipToState = "NV";
            // Ship.ShipToZip = "99999";
            // ShipToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            // For more information, refer to the Payflow Pro Developer's Guide.
            // Ship.ShipToCountry = "840";
            // Ship.ShipToPhone = "555-123-1233";
            // Secondary phone numbers (could be mobile number etc).
            // Ship.ShipToPhone2 = "555-333-1222";
            // Ship.ShipToEmail = "*****@*****.**";
            // Ship.ShipFromZip = Bill.BillToZip;

            // Following 2 items are just for reporting purposes and are not required.
            // Ship.ShipCarrier = "UPS";
            // Ship.ShipMethod = "Ground";

            Inv.ShipTo = Ship;

            // ***  Create Customer Data ***
            // There are additional CustomerInfo parameters that are used for Level 2 Purchase Cards.
            // Refer to the Payflow Pro Developer’s Guide and consult with your Internet
            // Merchant Bank regarding what parameters to send.
            // Some of the parameters could include:
            //
            CustomerInfo CustInfo = new CustomerInfo();

            CustInfo.CustCode = "CustCode123";     // Customer Code
            CustInfo.CustId   = "CustId123";
            CustInfo.CustIP   = "255.255.255.255"; // Customer's ip address
            Inv.CustomerInfo  = CustInfo;

            // *** Send User fields ***
            // You can send up to ten string type parameters to store temporary data (for example, variables,
            // session IDs, order numbers, and so on). These fields will be echoed back either via API response
            // or as part of the Silent / Return post if using the hosted checkout page.
            //
            // Note: UserItem1 through UserItem10 are not displayed to the customer and are not stored in
            // the PayPal transaction database.
            //
            UserItem nUser = new UserItem();

            nUser.UserItem1 = "TUSER1";
            nUser.UserItem2 = "TUSER2";
            Inv.UserItem    = nUser;

            // *** Create a new Payment Device - Credit Card data object. ***
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            // Note: Expiration date is in the format MMYY.
            CreditCard CC = new CreditCard("4111111111111111", "0115");

            // Example of Swipe Transaction.
            // See DOSwipe.cs example for more information.
            //SwipeCard Swipe = new SwipeCard(";5105105105105100=15121011000012345678?");

            // *** Card Security Code ***
            // This is the 3 or 4 digit code on either side of the Credit Card.
            // It is highly suggested that you obtain and pass this information to help prevent fraud.
            // Sending this fields could help in obtaining a lower discount rate from your Internet merchant Bank.
            // CVV2 is not required when performing a Swipe transaction as the card is present.
            CC.Cvv2 = "123";
            // Name on Credit Card is optional and not used as part of the authorization.
            // Also, this field populates the NAME field which is the same as FIRSTNAME, so if you
            // are already populating first name, do not use this field.
            //CC.Name = "Joe Smith";

            // *** Create a new Tender - Card Tender data object. ***
            CardTender Card = new CardTender(CC);              // credit card

            // If you are doing card-present (retail)type transactions you will want to use the swipe object.  Before doing so, verify with
            // your merchant bank that you are setup to process card-present transactions and contact Payflow support to request your account
            // be setup to process these types of transactions.  You will need to request your market seqment be changed from e-commerce (default)
            // to retail.
            //CardTender Card = new CardTender(Swipe);

            // *** Create a new Sale Transaction. ***
            // The Request Id is the unique id necessary for each transaction.  If you are performing an authorization
            // - delayed capture trnsaction, make sure that you pass two different unique request ids for each of the
            // transaction.
            // If you pass a non-unique request id, you will receive the transaction details from the original request.
            // The only difference is you will also receive a parameter DUPLICATE indicating this request id has been used
            // before.
            // The Request Id can be any unique number such order id, invoice number from your implementation or a random
            // id can be generated using the PayflowUtility.RequestId.
            SaleTransaction Trans = new SaleTransaction(User, Connection, Inv, Card, RequestID);

            ClientInfo cInfo = new ClientInfo();

            cInfo.IntegrationProduct = "Test";
            cInfo.IntegrationVersion = "1.0";
            Trans.ClientInfo         = cInfo;


            // Transaction results (especially values for declines and error conditions) returned by each PayPal-supported
            // processor vary in detail level and in format. The Payflow Verbosity parameter enables you to control the kind
            // and level of information you want returned.
            //
            // By default, Verbosity is set to LOW. A LOW setting causes PayPal to normalize the transaction result values.
            // Normalizing the values limits them to a standardized set of values and simplifies the process of integrating
            // the Payflow SDK.
            //
            // By setting Verbosity to HIGH, you can view the processor's raw response values along with card information. This
            // setting is more verbose than the LOW or MEDIUM setting in that it returns more detailed, processor and card specific
            // information.
            //
            // Review the chapter in the Payflow Pro Developer's Guide regarding VERBOSITY and the INQUIRY function for more details.

            // Set the transaction verbosity to HIGH to display most details.
            Trans.Verbosity = "HIGH";

            // Try to submit the transaction up to 3 times with 5 second delay.  This can be used
            // in case of network issues.  The idea here is since you are posting via HTTPS behind the scenes there
            // could be general network issues, so try a few times before you tell customer there is an issue.
            int  trxCount = 1;
            bool RespRecd = false;

            while (trxCount <= 3 && !RespRecd)
            {
                // Notice we set the request id earlier in the application and outside our loop.  This way if a response was not received
                // but PayPal processed the original request, you'll receive the original response with DUPLICATE set.

                // Submit the Transaction
                Response Resp = Trans.SubmitTransaction();

                // Uncomment line below to simulate "No Response"
                //Resp = null;

                // Display the transaction response parameters.
                if (Resp != null)
                {
                    RespRecd = true;                      // Got a response.

                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;

                    // Refer to the Payflow Pro .NET API Reference Guide and the Payflow Pro Developer's Guide
                    // for explanation of the items returned and for additional information and parameters available.
                    if (TrxnResponse != null)
                    {
                        Console.WriteLine("Transaction Response:");
                        Console.WriteLine("Result Code (RESULT) = " + TrxnResponse.Result);
                        Console.WriteLine("Transaction ID (PNREF) = " + TrxnResponse.Pnref);
                        Console.WriteLine("Response Message (RESPMSG) = " + TrxnResponse.RespMsg);
                        Console.WriteLine("Authorization (AUTHCODE) = " + TrxnResponse.AuthCode);
                        Console.WriteLine("Street Address Match (AVSADDR) = " + TrxnResponse.AVSAddr);
                        Console.WriteLine("Streep Zip Match (AVSZIP) = " + TrxnResponse.AVSZip);
                        Console.WriteLine("International Card (IAVS) = " + TrxnResponse.IAVS);
                        Console.WriteLine("CVV2 Match (CVV2MATCH) = " + TrxnResponse.CVV2Match);
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Credit Card Information:");
                        Console.WriteLine("Last 4-digits Credit Card Number (ACCT) = " + TrxnResponse.Acct);
                        if (TrxnResponse.CardType != null)
                        {
                            Console.Write("Card Type (CARDTYPE) = ");
                            switch (TrxnResponse.CardType)
                            {
                            case "0":
                                Console.WriteLine("Visa");
                                break;

                            case "1":
                                Console.WriteLine("MasterCard");
                                break;

                            case "2":
                                Console.WriteLine("Discover");
                                break;

                            case "3":
                                Console.WriteLine("American Express");
                                break;

                            case "4":
                                Console.WriteLine("Diner's Club");
                                break;

                            case "5":
                                Console.WriteLine("JCB");
                                break;

                            case "6":
                                Console.WriteLine("Maestro");
                                break;

                            case "S":
                                Console.WriteLine("Solo");
                                break;
                            }
                        }
                        Console.WriteLine("Expiration Date (EXPDATE) = " + TrxnResponse.ExpDate);
                        Console.WriteLine("Billing Name (FIRSTNAME, LASTNAME) = " + TrxnResponse.FirstName + " " + TrxnResponse.LastName);
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Verbosity Response:");
                        Console.WriteLine("Processor AVS (PROCAVS) = " + TrxnResponse.ProcAVS);
                        Console.WriteLine("Processor CSC (PROCCVV2) = " + TrxnResponse.ProcCVV2);
                        Console.WriteLine("Processor Result (HOSTCODE) = " + TrxnResponse.HostCode);
                        Console.WriteLine("Transaction Date/Time (TRANSTIME) = " + TrxnResponse.TransTime);
                        // Displays amount formatted as currency for the CurrentCulture.
                        // Due to operating system differences, you cannot be sure what currency
                        // symbol will be used.
                        Console.WriteLine("Amount of Transaction (AMT) = " + Convert.ToDecimal(TrxnResponse.Amt).ToString("c", us));
                    }

                    // Get the Fraud Response parameters.
                    // All trial accounts come with basic Fraud Protection Services enabled.
                    // Review the PayPal Manager guide to set up your Fraud Filters prior to
                    // running this sample code.
                    // If Fraud Filters are not set, you will receive a RESULT code 126.
                    FraudResponse FraudResp = Resp.FraudResponse;
                    if (FraudResp != null)
                    {
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Fraud Response:");
                        Console.WriteLine("Pre-Filters (PREFPSMSG) = " + FraudResp.PreFpsMsg);
                        Console.WriteLine("Post-Filters (POSTFPSMSG) = " + FraudResp.PostFpsMsg);
                    }

                    // The details below describe what you'd see in the raw response which can be seen in the log file.
                    //
                    // Was this a duplicate transaction, ie the request ID was NOT changed.
                    // Remember, a duplicate response will return the results of the original transaction which
                    // could be misleading if you are debugging your software.
                    // For Example, let's say you got a result code 4, Invalid Amount from the original request because
                    // you were sending an amount like: 1,050.98.  Since the comma is invalid, you'd receive result code 4.
                    // RESULT=4&PNREF=V18A0C24920E&RESPMSG=Invalid amount&PREFPSMSG=No Rules Triggered
                    // Now, let's say you modified your code to fix this issue and ran another transaction but did not change
                    // the request ID.  Notice the PNREF below is the same as above, but DUPLICATE=1 is now appended.
                    // RESULT=4&PNREF=V18A0C24920E&RESPMSG=Invalid amount&DUPLICATE=1
                    // This would tell you that you are receving the results from a previous transaction.  This goes for
                    // all transactions even a Sale transaction.  In this example, let's say a customer ordered something and got
                    // a valid response and now a different customer with different credit card information orders something, but again
                    // the request ID is NOT changed, notice the results of these two sales.  In this case, you would have not received
                    // funds for the second order.
                    // First order: RESULT=0&PNREF=V79A0BC5E9CC&RESPMSG=Approved&AUTHCODE=166PNI&AVSADDR=X&AVSZIP=X&CVV2MATCH=Y&IAVS=X
                    // Second order: RESULT=0&PNREF=V79A0BC5E9CC&RESPMSG=Approved&AUTHCODE=166PNI&AVSADDR=X&AVSZIP=X&CVV2MATCH=Y&IAVS=X&DUPLICATE=1
                    // Again, notice the PNREF is from the first transaction, this goes for all the other fields as well.
                    // It is suggested that your use this to your benefit to prevent duplicate transaction from the same customer, but you want
                    // to check for DUPLICATE=1 to ensure it is not the same results as a previous one.
                    //
                    // Since we are using objects instead of the raw name-value-pairs, you'd check the Duplicate parameter of the TrxnResponse object.
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Duplicate Response:");
                    string DupMsg;
                    if (TrxnResponse.Duplicate == "1")
                    {
                        DupMsg = "Duplicate Transaction";
                    }
                    else
                    {
                        DupMsg = "Not a Duplicate Transaction";
                    }
                    Console.WriteLine(("Duplicate Transaction (DUPLICATE) = " + DupMsg));

                    // Part of accepting credit cards or PayPal is to determine what your business rules are.  Basically, what risk are you
                    // willing to take, especially with credit cards.  The code below gives you an idea of how to check the results returned
                    // so you can determine how to handle the transaction.
                    //
                    // This is not an exhaustive list of failures or issues that could arise.  Review the list of Result Code's in the
                    // Developer Guide and add logic as you deem necessary.
                    // These responses are just an example of what you can do and how you handle the response received
                    // from the bank/PayPal is dependent on your own business rules and needs.

                    string RespMsg;
                    // Evaluate Result Code
                    if (TrxnResponse.Result < 0)
                    {
                        // Transaction failed.
                        RespMsg = "There was an error processing your transaction. Please contact Customer Service." +
                                  Environment.NewLine + "Error: " + TrxnResponse.Result.ToString();
                    }
                    else if (TrxnResponse.Result == 1 || TrxnResponse.Result == 26)
                    {
                        // This is just checking for invalid login credentials.  You normally would not display this type of message.
                        // Result code 26 will be issued if you do not provide both the <vendor> and <user> fields.
                        // Remember: <vendor> = your merchant (login id), <user> = <vendor> unless you created a seperate <user> for Payflow Pro.
                        //
                        // The other most common error with authentication is result code 1, user authentication failed.  This is usually
                        // due to invalid account information or ip restriction on the account.  You can verify ip restriction by logging
                        // into Manager.  See Service Settings >> Allowed IP Addresses.  Lastly it could be you forgot the path "/transaction"
                        // on the URL.
                        RespMsg = "Account configuration issue.  Please verify your login credentials.";
                    }
                    else if (TrxnResponse.Result == 0)
                    {
                        // Example of a message you might want to display with an approved transaction.
                        RespMsg = "Your transaction was approved. Will ship in 24 hours.";

                        // Even though the transaction was approved, you still might want to check for AVS or CVV2(CSC) prior to
                        // accepting the order.  Do realize that credit cards are approved (charged) regardless of the AVS/CVV2 results.
                        // Should you decline (void) the transaction, the card will still have a temporary charge (approval) on it.
                        //
                        // Check AVS - Street/Zip
                        // In the message below it shows what failed, ie street, zip or cvv2.  To prevent fraud, it is suggested
                        // you only give a generic billing error message and not tell the card-holder what is actually wrong.  However,
                        // that decision is yours.
                        //
                        // Also, it is totally up to you on if you accept only "Y" or allow "N" or "X".  You need to decide what
                        // business logic and liability you want to accept with cards that either don't pass the check or where
                        // the bank does not participate or return a result.  Remember, AVS is mostly used in the US but some foreign
                        // banks do participate.
                        //
                        // Remember, this just an example of what you might want to do.
                        if (TrxnResponse.AVSAddr != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // 3 strikes your out check.
                            RespMsg = "Your billing (street) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                        if (TrxnResponse.AVSZip != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // 3 strikes your out check.
                            RespMsg = "Your billing (zip) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                        if (TrxnResponse.CVV2Match != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect.  Normally, to prevent
                            // fraud you would not want to tell a customer that the 3/4 digit number on
                            // the credit card was invalid.
                            RespMsg = "Your billing (cvv2) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                    }
                    else if (TrxnResponse.Result == 12)
                    {
                        // Hard decline from bank.  Customer will need to use another card or payment type.
                        RespMsg = "Your transaction was declined.";
                    }
                    else if (TrxnResponse.Result == 13)
                    {
                        // Voice authorization required.  You would need to contact your merchant bank to obtain a voice authorization.  If authorization is
                        // given, you can manually enter it via Virtual Terminal in PayPal Manager or via the VoiceAuthTransaction object.
                        RespMsg = "Your Transaction is pending. Contact Customer Service to complete your order.";
                    }
                    else if (TrxnResponse.Result == 23 || TrxnResponse.Result == 24)
                    {
                        // Issue with credit card number or expiration date.
                        RespMsg = "Invalid credit card information. Please re-enter.";
                    }
                    else if (TrxnResponse.Result == 125)
                    {
                        // Using the Fraud Protection Service.
                        // This portion of code would be is you are using the Fraud Protection Service, this is for US merchants only.
                        // 125, 126 and 127 are Fraud Responses.
                        // Refer to the Payflow Pro Fraud Protection Services User's Guide or Website Payments Pro Payflow Edition - Fraud Protection Services User's Guide.
                        RespMsg = "Your Transactions has been declined. Contact Customer Service.";
                    }
                    else if (TrxnResponse.Result == 126)
                    {
                        // One of more filters were triggered.  Here you would check the fraud message returned if you
                        // want to validate data.  For example, you might have 3 filters set, but you'll allow 2 out of the
                        // 3 to consider this a valid transaction.  You would then send the request to the server to modify the
                        // status of the transaction.  Performing this function is outside the scope of this sample, refer
                        // to the Fraud Developer's Guide.
                        //
                        // Decline transaction if AVS fails.
                        if (TrxnResponse.AVSAddr != "Y" || TrxnResponse.AVSZip != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // strikes your out check.
                            RespMsg = "Your billing information does not match.  Please re-enter.";
                        }
                        else
                        {
                            RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                        }
                        RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                    }
                    else if (TrxnResponse.Result == 127)
                    {
                        // There is an issue with checking this transaction through the fraud service.
                        // You will need to manually approve.
                        RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                    }
                    else
                    {
                        // Error occurred, display normalized message returned.
                        RespMsg = TrxnResponse.RespMsg;
                    }

                    // Display Message
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("User/System Response:");
                    Console.WriteLine("User Message (RESPMSG) = " + RespMsg);
                    Console.WriteLine("System Message (TRXNRESPONSE.RESPMSG) = " + TrxnResponse.RespMsg);

                    // Display the status response of the transaction.
                    // This is just additional information and normally would not be used in production.
                    // Your business logic should be built around the result code returned as shown above.
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Overall Transaction Status: " + PayflowUtility.GetStatus(Resp));

                    // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                    // This is not normally used in production.
                    Context TransCtx = Resp.TransactionContext;
                    if (TransCtx != null && TransCtx.getErrorCount() > 0)
                    {
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Transaction Context Errors: " + TransCtx.ToString());
                    }
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Press Enter to Exit ...");
                    Console.ReadLine();
                }
                else
                {
                    Thread.Sleep(5000);                     // let's wait 5 seconds to see if this is a temporary network issue.
                    Console.WriteLine("Retry #: " + trxCount.ToString());
                    trxCount++;
                }
            }
            if (!RespRecd)
            {
                Console.WriteLine("There is a problem obtaining an authorization for your order.");
                Console.WriteLine("Please contact Customer Support.");
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("Press Enter to Exit ...");
                Console.ReadLine();
            }
        }
    protected void btnFinalShowVac_Click(object sender, EventArgs e)
    {
        if (DateTime.Parse(dateStart0.Text) > DateTime.Parse(DateEnd0.Text))
        {
            lblInvalidInput.Visible = true;
            lblInvalidInput.Text = "End date can not be before start date.";

            //Empty DropDown
            DropDownListFinalResult.ClearSelection();
            secondPhasePanel.Visible = false;
        }

        startedDate = dateStart0.Text.Trim();
        endedDate = DateEnd0.Text.Trim();

        VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager();
        TransactionResponse response = new TransactionResponse();
        response = manager.getVacancyToGenerateReportByDateInterval(startedDate, endedDate, DbAccessConstants.spGetFinalPhaseVacancyByDateInterval);

        DataTable vacancyDetail = (DataTable)response.Data;

        DropDownListFinalResult.Items.Clear();
        DropDownListFinalResult.Items.Add(new ListItem(" -- SELECT VACANCY --", "-1"));

        if (vacancyDetail != null && vacancyDetail.Rows.Count > 0)
        {
            clearmsgPanel();
            secondPhasePanel.Visible = true;

            DropDownListFinalResult.DataSource = vacancyDetail;
            DropDownListFinalResult.DataValueField = "vacancy_detail_value";
            DropDownListFinalResult.DataTextField = "vacancy_detail";
            DropDownListFinalResult.DataBind();
        }
        else
        {
            selectedVacancyPanel.Visible = false;

            msgPanel.Visible = true;
            InfoDIV.Visible = true;
            lblInformationMsg.Text = "There is no final phase result bewteen the selected date interval";
            DropDownListFinalResult.ClearSelection();
        }
    }
Beispiel #22
0
        private void SubmitData(
            Arkivdel series,
            Klasse primaryClass,
            Klasse secondaryClass,
            AdministrativEnhet administrativeUnit,
            Skjerming screeningCode,
            Dokumenttype documentType,
            string caseFileTitle,
            string caseFileExternalId,
            string caseResponsibleName,
            string caseResponsibleId,
            string registryEntryTitle,
            string registryEntryExternalId)
        {
            #region Case file

            Saksmappe caseFile = new Saksmappe(caseFileTitle, administrativeUnit)
            {
                Saksansvarlig            = caseResponsibleName,
                SaksansvarligBrukerIdent = caseResponsibleId
            };

            EksternId caseFileExternalIdObj = new EksternId(EXTERNAL_SYSTEM, caseFileExternalId);

            #endregion Case file

            #region Registry entry

            Journalpost registryEntry = new Journalpost(registryEntryTitle, Journalposttype.UTGAAENDE_DOKUMENT)
            {
                Skjerming = screeningCode
            };

            registryEntry.VirksomhetsspesifikkeMetadata.AddBsmFieldValues("gr-1", "f-string", "value 1");

            EksternId registryEntryExternalIdObj = new EksternId(EXTERNAL_SYSTEM, registryEntryExternalId);

            Korrespondansepart correspondenceParty =
                new Korrespondansepart(Korrespondanseparttype.AVSENDER, "John Smith");

            #endregion Registry entry

            #region Documents

            //Upload two files

            Dokumentfil mainFile       = UploadDocument(this.testFile1);
            Dokumentfil attachmentFile = UploadDocument(this.testFile2);

            //Link the first document description to the registry entry as main document (HOVEDDOKUMENT).
            //Subsequent document descriptions will be linked as attachments (VEDLEGG).

            Dokument mainDocumentDescription =
                new Dokument("Main Document", TilknyttetRegistreringSom.HOVEDDOKUMENT)
            {
                Dokumenttype = documentType,
            };

            Dokumentversjon mainDocumentVersion =
                new Dokumentversjon(Variantformat.ARKIVFORMAT, ".pdf", mainFile);

            Dokument attachmentDocumentDescription =
                new Dokument("Attachment", TilknyttetRegistreringSom.VEDLEGG)
            {
                Dokumenttype = documentType     //here might as well be used another type
            };

            Dokumentversjon attachmentDocumentVersion =
                new Dokumentversjon(Variantformat.ARKIVFORMAT, ".pdf", attachmentFile);

            #endregion Documents

            NoarkClient client = this.documasterClients.GetNoarkClient();

            TransactionResponse transactionResponse = client.Transaction()
                                                      .Save(caseFile)
                                                      .Link(caseFile.LinkArkivdel(series))
                                                      .Link(caseFile.LinkPrimaerKlasse(primaryClass))
                                                      .Link(caseFile.LinkSekundaerKlasse(secondaryClass))
                                                      .Save(caseFileExternalIdObj)
                                                      .Link(caseFileExternalIdObj.LinkMappe(caseFile))
                                                      .Save(registryEntry)
                                                      .Link(registryEntry.LinkMappe(caseFile))
                                                      .Save(correspondenceParty)
                                                      .Link(correspondenceParty.LinkRegistrering(registryEntry))
                                                      .Save(registryEntryExternalIdObj)
                                                      .Link(registryEntryExternalIdObj.LinkRegistrering(registryEntry))
                                                      .Save(mainDocumentDescription)
                                                      .Link(mainDocumentDescription.LinkRegistrering(registryEntry))
                                                      .Save(mainDocumentVersion)
                                                      .Link(mainDocumentVersion.LinkDokument(mainDocumentDescription))
                                                      .Save(attachmentDocumentDescription)
                                                      .Link(attachmentDocumentDescription.LinkRegistrering(registryEntry))
                                                      .Save(attachmentDocumentVersion)
                                                      .Link(attachmentDocumentVersion.LinkDokument(attachmentDocumentDescription))
                                                      .Commit();

            // When new objects are initialized, a temporary Id is assigned to them.
            // transactionResponse.Saved contains a mapping between the temporary id's and the saved objects with their permanent id's
            Dictionary <string, INoarkEntity> savedObjects = transactionResponse.Saved;

            string template = "{0}: Temporary Id: {1} Permanent Id: {2}";

            Console.WriteLine(String.Format(template, "Case file", caseFile.Id, savedObjects[caseFile.Id].Id));
            Console.WriteLine(String.Format(template, "Registry entry", registryEntry.Id,
                                            savedObjects[registryEntry.Id].Id));
            Console.WriteLine(String.Format(template, "Main document description", mainDocumentDescription.Id,
                                            savedObjects[mainDocumentDescription.Id].Id));
            Console.WriteLine(String.Format(template, "Attachment document description",
                                            attachmentDocumentDescription.Id, savedObjects[attachmentDocumentDescription.Id].Id));
        }
Beispiel #23
0
    private void job_logCustomTransaction(CustomerTransactionRequest req, TransactionResponse resp, SAPCust sapcust, CCJOB job, string InvoiceID = "")
    {
        CCTRAN cctran = new CCTRAN();

        try
        {
            if (job.OrderID == null)
                job.OrderID = 0;
            if (job.InvoiceID == null)
                job.InvoiceID = 0;

            cctran.customerID = sapcust.cccust.CustomerID;
            cctran.CCAccountID = 0;
            cctran.jobID = (int)job.jobID;
            cctran.OrderID = job.OrderID.ToString();
            cctran.InvoiceID = InvoiceID;
            cctran.CreditMemoID = "";
            cctran.DownPaymentInvoiceID = "";
            if (sapcust != null)
            {
                try
                {
                    cctran.CCAccountID = int.Parse(sapcust.cccust.CCAccountID);
                    cctran.customerID = sapcust.cccust.CustomerID;
                    cctran.MethodID = sapcust.custObj.PaymentMethodProfiles[0].MethodID;
                    cctran.custNum = sapcust.cccust.CustNum;
                    cctran.crCardNum = sapcust.custObj.PaymentMethodProfiles[0].CardNumber;
                    cctran.CardHolder = sapcust.custObj.BillingAddress.FirstName + " " + sapcust.custObj.BillingAddress.LastName;
                }catch(Exception ex)
                {
                    errorLog(ex);
                }
            }
            cctran.Description = req.Details.Description;
            cctran.recID = req.Details.Invoice;
            cctran.acsUrl = resp.AcsUrl;
            cctran.authAmount = resp.AuthAmount.ToString();
            cctran.authCode = resp.AuthCode;
            cctran.avsResult = resp.AvsResult;
            cctran.avsResultCode = resp.AvsResultCode;
            cctran.batchNum = resp.BatchNum;
            cctran.batchRef = resp.BatchRefNum;
            cctran.cardCodeResult = resp.CardCodeResult;
            cctran.cardCodeResultCode = resp.CardCodeResultCode;
            cctran.cardLevelResult = resp.CardLevelResult;
            cctran.cardLevelResultCode = resp.CardLevelResultCode;
            cctran.conversionRate = resp.ConversionRate.ToString();
            cctran.convertedAmount = resp.ConvertedAmount.ToString();
            cctran.convertedAmountCurrency = resp.ConvertedAmountCurrency.ToString();
            cctran.custNum = resp.CustNum;
            cctran.error = resp.Error;
            cctran.errorCode = resp.ErrorCode;
            cctran.isDuplicate = resp.isDuplicate.ToString();
            cctran.payload = resp.Payload;
            cctran.profilerScore = resp.ProfilerScore;
            cctran.profilerResponse = resp.ProfilerResponse;
            cctran.profilerReason = resp.ProfilerReason;
            cctran.refNum = resp.RefNum;
            cctran.remainingBalance = resp.RemainingBalance.ToString();
            cctran.result = resp.Result;
            cctran.resultCode = resp.ResultCode;
            cctran.status = resp.Status;
            cctran.statusCode = resp.StatusCode;
            cctran.vpasResultCode = resp.VpasResultCode;
            cctran.recDate = DateTime.Now;//Use local time not server time
            cctran.command = req.Command;
            cctran.amount = req.Details.Amount.ToString();
            insert(cctran);
        }
        catch (Exception ex)
        {

            errorLog(ex);
        }
    }
Beispiel #24
0
    public bool job_runCustomerTrans(SAPCust sapcust, SAPbobsCOM.Documents oDoc, CCJOB job, string amt ="")
    {
        try
        {
            string cmd = "cc:sale";
            if (sapcust.custObj.PaymentMethodProfiles[0].MethodType == "check")
                cmd = "check";
            confirmNum = "";

            CustomerTransactionRequest req = job_createCustomRequest(job, oDoc, amt);
            req.Command = cmd;
            trace("Job_runCustomRequest: amount = " + req.Details.Amount + ", tax=" + req.Details.Tax + ",Subtotal=" + req.Details.Subtotal + ",shipping=" + req.Details.Shipping + ",Discount=" + req.Details.Discount +
             string.Format("runCustomerTrans, token={0}, method={1}:{2}", sapcust.custObj.CustomerToken, sapcust.custObj.PaymentMethodProfiles[0].MethodID, sapcust.custObj.PaymentMethodProfiles[0].CardNumber));
            req.CustReceipt = cfgsendCustomerEmail == "Y" ? true : false;
            req.CustReceiptName = "vterm_customer";
            req.CustReceiptEmail = sapcust.custObj.Email;
            if (req.Command == "cc:authonly" && cfgPreAuthEmail != "Y")
                req.CustReceipt = false;
            if (req.CustReceiptEmail == "")
                req.CustReceipt = false;
            SecurityToken token = getToken(sapcust.cccust.CCAccountID);
            TransactionResponse resp = new TransactionResponse();
            resp = ebiz.runCustomerTransaction(token, sapcust.custObj.CustomerToken, sapcust.custObj.PaymentMethodProfiles[0].MethodID, req);
            confirmNum = resp.RefNum;
            sendReceipt(token, sapcust, resp);
            int invoiceID = 0;
            if (oDoc != null)
                invoiceID = oDoc.DocEntry;
            job_logCustomTransaction(req, resp, sapcust, job, invoiceID.ToString());
            if (resp.Error.ToLower() == "approved")
            {
                job.Result = "Success";
                job.LastRunDate = DateTime.Today;
                update(job);
                return true;
            }
            else
            {
                if (resp.ResultCode == "D")
                {
                    if (req.CustReceiptEmail != "" && req.CustReceiptEmail != null && cfgCustomerReceipt != "")
                    {

                        try
                        {
                            EmailReceiptResponse emresp = ebiz.EmailReceipt(token, resp.RefNum, resp.RefNum, cfgCustomerReceipt, req.CustReceiptEmail);

                            if (emresp.ErrorCode == 0)
                            {
                                showStatus("Declined receipt sent.", SAPbouiCOM.BoMessageTime.bmt_Medium,false);
                            }
                            else
                                showStatus("Failed to send declined receipt.\r\n" + resp.Error, SAPbouiCOM.BoMessageTime.bmt_Medium,true);

                        }
                        catch (Exception ex2)
                        {
                            showStatus("Failed to send receipt.\r\n" + ex2.Message, SAPbouiCOM.BoMessageTime.bmt_Medium, false);
                        }

                    }
                }
                string err = "Job Failed. ID:" + job.jobID + "\r\n" + resp.Error;
                job.Result = err;
                job.LastRunDate = DateTime.Today;
                update(job);
                errorLog(err);
                return false;
            }

        }
        catch (Exception ex)
        {
            string err = "Job Failed. ID:" + job.jobID + "\r\n" + ex.Message;
            job.Result = err;
            job.LastRunDate = DateTime.Today;
            update(job);
            errorLog(ex);

            return false;
        }
    }
Beispiel #25
0
 protected abstract void ProcessTransactionTx(TransactionResponse tx);
    private void logTransaction(TransactionRequestObject req, TransactionResponse resp)
    {
        string sql = "";

        try
        {
            string cardLastFour = "";
            try
            {
                if (req.CreditCardData.CardNumber == null)
                {
                    cardLastFour = "";
                }
                else
                {
                    cardLastFour = req.CreditCardData.CardNumber.Substring(req.CreditCardData.CardNumber.Length - 4);
                }
            }catch (Exception)
            {}

            db.CommandTimeout = 30000;
            CCTRAN cctran = new CCTRAN();
            cctran.customerID              = req.CustomerID;
            cctran.customerName            = req.BillingAddress.Company;
            cctran.crCardNum               = cardLastFour;
            cctran.Description             = req.Details.Description;
            cctran.recID                   = req.Details.Invoice;
            cctran.acsUrl                  = resp.AcsUrl;
            cctran.authAmount              = resp.AuthAmount.ToString();
            cctran.authCode                = resp.AuthCode;
            cctran.avsResult               = resp.AvsResult;
            cctran.avsResultCode           = resp.AvsResultCode;
            cctran.batchNum                = resp.BatchNum;
            cctran.batchRef                = resp.BatchRefNum;
            cctran.cardCodeResult          = resp.CardCodeResult;
            cctran.cardCodeResultCode      = resp.CardCodeResultCode;
            cctran.cardLevelResult         = resp.CardLevelResult;
            cctran.cardLevelResultCode     = resp.CardLevelResultCode;
            cctran.conversionRate          = resp.ConversionRate.ToString();
            cctran.convertedAmount         = resp.ConvertedAmount.ToString();
            cctran.convertedAmountCurrency = resp.ConvertedAmountCurrency.ToString();
            cctran.custNum                 = resp.CustNum;
            cctran.error                   = resp.Error;
            cctran.errorCode               = resp.ErrorCode;
            cctran.isDuplicate             = resp.isDuplicate.ToString();
            cctran.payload                 = resp.Payload;
            cctran.profilerScore           = resp.ProfilerScore;
            cctran.profilerResponse        = resp.ProfilerResponse;
            cctran.profilerReason          = resp.ProfilerReason;
            cctran.refNum                  = resp.RefNum;
            cctran.remainingBalance        = resp.RemainingBalance.ToString();
            cctran.result                  = resp.Result;
            cctran.resultCode              = resp.ResultCode;
            cctran.status                  = resp.Status;
            cctran.statusCode              = resp.StatusCode;
            cctran.vpasResultCode          = resp.VpasResultCode;
            cctran.recDate                 = DateTime.Now;//Use local time not server time
            cctran.command                 = req.Command;
            cctran.amount                  = req.Details.Amount.ToString();
            db.CCTRANs.InsertOnSubmit(cctran);
            db.SubmitChanges();
        }catch (Exception ex)
        {
            errorLog(ex);
            errorLog(sql);
        }
    }
    protected void btnGenerateFinalReport_Click(object sender, EventArgs e)
    {
        if (DropDownListFinalResult.SelectedValue == "-1")
        {
            lblVacancyFinal.Visible = true;
            return;
        }
        lblVacancyFinal.Visible = false;

        string[] splitter = new string[] { PageConstants.GREATER_GREATER_THAN };
        VacancyInfoTosplit = (DropDownListFinalResult.SelectedValue).Split(splitter, StringSplitOptions.RemoveEmptyEntries);
        currentVacancyNo = VacancyInfoTosplit[0].Trim();
        currentVacancyDate = VacancyInfoTosplit[1].Trim();
        Vacancy vacancy = new Vacancy();
        vacancy.VacancyNo = currentVacancyNo;
        vacancy.PostedDate = currentVacancyDate;

        //get and display the vacancy to user. 
        int isfromAll = 0;
        getVacancyReportAndDisplayToUser(vacancy, PageConstants.REPORT_PHASE2, isfromAll);


        VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager();
        TransactionResponse response = new TransactionResponse();

        //get vacancy detail
        response = manager.getVacancyDetail(vacancy);
        DataTable dataTable = (DataTable)response.Data;
        string postDate = "";
        try
        {
            postDate = String.Format("{0:MMM d, yyyy}", Convert.ToDateTime(dataTable.Rows[0]["posted_date"]));
        }
        catch (Exception)
        {
        }
        VacDetailFinalPanel.Visible = true;
        lblfinalVacancyPost.Text = dataTable.Rows[0]["Vancay_title"].ToString() + "  ( JG - " +
                              dataTable.Rows[0]["vacancy_for_JobGrade"].ToString() + " )";
        lblfinalVacancyNum.Text = dataTable.Rows[0]["vacancy_No"].ToString() + " dated " + postDate;

        lblfinalJobReq.Text = dataTable.Rows[0]["JobDescription"].ToString() + " " + dataTable.Rows[0]["JobRequirement"].ToString() + ". ";
   
    }
Beispiel #28
0
 private IncomeTransactionTableModel ConvertTransactionResponseToIncomeTransaction(TransactionResponse transaction,
                                                                                   string shortNameCurrency, int walletId, string userId)
 {
     return(new IncomeTransactionTableModel()
     {
         CurrencyAcronim = shortNameCurrency,
         TransactionId = transaction.TxId,
         Amount = transaction.Amount,
         TransactionFee = transaction.Fee, // не видит комиссию
         ToAddress = transaction.Address,
         Date = transaction.Time,
         UserId = userId,
         WalletId = walletId
     });
 }
Beispiel #29
0
        public async Task <TransactionResponse> Execute(TransactionModel transactionModel)
        {
            SellerData sell = new SellerData(transactionModel.Price, transactionModel.Quantity);

            try
            {
                await _sellerRepository.AddSellerData(sell);

                List <BuyerData> BuyerList = await _buyerRepository.GetGreaterBuyerPriceListFromSellerPrice(sell.SellPrice);

                foreach (var buy in BuyerList)
                {
                    decimal Quantities = 0.0m;
                    if (sell.RemainingQuantity >= buy.RemainingQuantity)
                    {
                        Quantities = buy.RemainingQuantity;
                    }
                    else
                    {
                        Quantities = sell.RemainingQuantity;
                    }
                    sell.RemainingQuantity -= Quantities;
                    sell.SettledQuantity   += Quantities;
                    buy.RemainingQuantity  -= Quantities;
                    buy.SettledQuantity    += Quantities;

                    if (sell.RemainingQuantity == 0)
                    {
                        sell.StatusChangeToSettleStatus();
                    }
                    else
                    {
                        sell.StatusChangeToOnHoldStatus();
                    }
                    if (buy.RemainingQuantity == 0)
                    {
                        buy.StatusChangeToSettleStatus();
                    }
                    else
                    {
                        buy.StatusChangeToOnHoldStatus();
                    }

                    await _sellerRepository.UpdateSellerData(sell);

                    await _buyerRepository.UpdateBuyerData(buy);

                    await _ledgerRepository.AddLedgerData(sell, buy, Quantities);

                    if (sell.RemainingQuantity == 0)
                    {
                        break;
                    }
                }
                TransactionResponse transactionResponse = new TransactionResponse();
                transactionResponse.UniqId        = sell.SellerId.ToString();
                transactionResponse.StatusCode    = (int)sell.TransactionStatus;
                transactionResponse.StatusMessage = sell.TransactionStatus.ToString();
                return(transactionResponse);
            }
            catch (Exception)
            {
                return(new TransactionResponse {
                    ErrorCode = enErrorCode.InternalError, StatusCode = (int)TransactionStatus.Validationfail, StatusMessage = TransactionStatus.Validationfail.ToString()
                });
            }
        }
        public void VerifyTransactionsByOrder(TransactionResponse expectedResponse, int order)
        {
            TransactionResponse[] actualResponses = GetTransactions();
            if ((0 < order) && (order <= actualResponses.Length))
            {
                TransactionResponse actualResponse = actualResponses[order - 1];

                if (!actualResponse.Equals(expectedResponse))
                {
                    VerifyTool.VerifyValue(expectedResponse.Id, actualResponse.Id, "The transaction id is {0}");
                    VerifyTool.VerifyValue(expectedResponse.Date, actualResponse.Date, "The transaction date is {0}");
                    VerifyTool.VerifyValue(expectedResponse.Type, actualResponse.Type, "The transaction type is {0}");
                    VerifyTool.VerifyValue(expectedResponse.Notes, actualResponse.Notes, "The transaction notes is {0}");
                    VerifyTool.VerifyValue(expectedResponse.Amount, actualResponse.Amount, "The transaction amount is {0}");
                    VerifyTool.VerifyValue(expectedResponse.SubTotal, actualResponse.SubTotal, "The transaction sub-total is {0}");
                    VerifyTool.VerifyValue(expectedResponse.AddBy, actualResponse.AddBy, "The transaction added by {0}");
                    VerifyTool.VerifyValue(expectedResponse.ModBy, actualResponse.ModBy, "The transaction moded by {0}");
                    VerifyTool.VerifyValue(expectedResponse.Delete, actualResponse.Delete, "The transaction deleted by {0}");
                }
            }
            else
            {
                Assert.Fail("This is a wrong order.");
            }
        }
Beispiel #31
0
        public ActionResult processGiving(string data)
        {
            // Authenticate first
            var authError = Authenticate();

            if (authError != null)
            {
                return(authError);
            }

            // Check to see if type matches
            BaseMessage dataIn = BaseMessage.createFromString(data);

            if (dataIn.type != BaseMessage.API_TYPE_GIVING_GIVE)
            {
                return(BaseMessage.createTypeErrorReturn());
            }

            // Everything is in order, start the return
            MobilePostTransaction mpt = JsonConvert.DeserializeObject <MobilePostTransaction>(dataIn.data);

            if (mpt.amount == 0 || mpt.paymentType == 0 || mpt.peopleID == 0)
            {
                return(BaseMessage.createErrorReturn("Missing information!"));
            }

            Transaction ti = createTransaction(mpt);

            if (ti != null && ti.Id > 0)
            {
                SagePayments        sp = new SagePayments(DbUtil.Db, false);
                TransactionResponse tr = null;

                switch (mpt.paymentType)
                {
                case MobilePostTransaction.TYPE_BANK_ACCOUNT:
                    tr = sp.createVaultTransactionRequest(mpt.peopleID, mpt.amount, mpt.description, ti.Id, "B");
                    break;

                case MobilePostTransaction.TYPE_CREDIT_CARD:
                    tr = sp.createVaultTransactionRequest(mpt.peopleID, mpt.amount, mpt.description, ti.Id, "C");
                    break;
                }

                // Build return
                BaseMessage br = new BaseMessage();
                br.type = BaseMessage.API_TYPE_GIVING_GIVE;

                if (tr != null && tr.Approved)
                {
                    br.error = 0;
                    br.id    = mpt.transactionID = ti.Id;

                    sendConfirmation(mpt);
                }
                else
                {
                    DbUtil.Db.Transactions.DeleteOnSubmit(ti);
                    DbUtil.Db.SubmitChanges();

                    br.error = 1;
                    br.data  = tr.Message;
                }

                return(br);
            }
            else
            {
                return(BaseMessage.createErrorReturn("Transaction creation failed!"));
            }
        }
    /**
     * Add promoted employee from other district
    */
    public TransactionResponse storeEmployeefromOtherDistrictForPromotion(string minNumber, string districtID)
    {
        //Add List of Arguments for new employee
        IDictionary<string, object> employeeArgumentaMap = new Dictionary<string, object>();

        employeeArgumentaMap.Add("@Minute_No", minNumber);
        employeeArgumentaMap.Add("@Emp_ID", employee.EmpID);
        employeeArgumentaMap.Add("@First_Name", employee.FName);
        employeeArgumentaMap.Add("@Middle_Name", employee.MName);
        employeeArgumentaMap.Add("@Last_Name", employee.LName);
        employeeArgumentaMap.Add("@Curr_Jtitle", employee.PrevJob);
        employeeArgumentaMap.Add("@Curr_JGrade", employee.PrevJobGrade);
        employeeArgumentaMap.Add("@Exp_JGrade", employee.JobGrade);
        employeeArgumentaMap.Add("@Salary", employee.Salary);
        employeeArgumentaMap.Add("@district", districtID);
        employeeArgumentaMap.Add("@status", "Active");

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil storeToDb = new DBOperationsUtil(DbAccessConstants.spAddPromotedEmployeefromOtherDistrict, employeeArgumentaMap);

        TransactionResponse response = new TransactionResponse();

        //call store to DB mathod and get reponse.
        try
        {
            storeToDb.instertNewRecord();
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setSuccess(true);
            response.setMessage(DBOperationErrorConstants.M_EMPLOYEE_REGISTER_OK);
        }

        catch (SqlException ex)
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_EID_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_EMP_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }

        return response;
    }
Beispiel #33
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOGetEC.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            PayflowConnectionData Connection = new PayflowConnectionData();

            // Calling a GET operation is second step in PayPal Express checkout process. Once the
            // customner has logged into his/her paypal account, selected shipping address and clicked on
            // "Continue checkout", the PayPal server will redirect the page to the ReturnUrl you have
            // specified in the previous SET request.  To obtain the shipping details chosen by the
            // Customer, you will then need to do a GET operation.
            //
            // For more information on Reference Transactions, see the DOSetEC Sample for more details.

            // For Regular Express Checkout or Express Checkout Reference Transaction with Purchase.
            ECGetRequest GetRequest = new ECGetRequest("<TOKEN>");

            // For Express Checkout Reference Transaction without Purchase.
            //ECGetBARequest GetRequest = new ECGetBARequest("<TOKEN>");

            // Create the Tender.
            PayPalTender Tender = new PayPalTender(GetRequest);

            // Create a transaction.
            AuthorizationTransaction Trans = new AuthorizationTransaction
                                                 (User, Connection, null, Tender, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result.ToString());
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    // The TOKEN is needed for the DODoEC Sample.
                    Console.WriteLine("TOKEN = " + Trans.Response.ExpressCheckoutSetResponse.Token);
                    Console.WriteLine("CORRELATIONID = " + TrxnResponse.CorrelationId);
                    Console.WriteLine("EMAIL = " + Trans.Response.ExpressCheckoutGetResponse.EMail);
                    // The PAYERID is needed for the DODoEC Sample.
                    Console.WriteLine("PAYERID = " + Trans.Response.ExpressCheckoutGetResponse.PayerId);
                    Console.WriteLine("PAYERSTATUS = " + Trans.Response.ExpressCheckoutGetResponse.PayerStatus);
                    // Express Checkout Transactions and Express Checkout Reference Transactions with Purchase
                    // begin with EC, while Express Checkout Reference Transactions without Purchase begin with BA.
                    // Reference Transactions without Purchase do not return shipping information.
                    if (Trans.Response.ExpressCheckoutSetResponse.Token != null)
                    {
                        if (Trans.Response.ExpressCheckoutSetResponse.Token.StartsWith("EC"))
                        {
                            Console.WriteLine(Environment.NewLine + "Shipping Information:");
                            Console.WriteLine("FIRST = " + Trans.Response.ExpressCheckoutGetResponse.FirstName);
                            Console.WriteLine("LAST = " + Trans.Response.ExpressCheckoutGetResponse.LastName);
                            Console.WriteLine("SHIPTOSREET = " + Trans.Response.ExpressCheckoutGetResponse.ShipToStreet);
                            Console.WriteLine("SHIPTOSTREET2 = " + Trans.Response.ExpressCheckoutGetResponse.ShipToStreet2);
                            Console.WriteLine("SHIPTOCITY = " + Trans.Response.ExpressCheckoutGetResponse.ShipToCity);
                            Console.WriteLine("SHIPTOSTATE = " + Trans.Response.ExpressCheckoutGetResponse.ShipToState);
                            Console.WriteLine("SHIPTOZIP = " + Trans.Response.ExpressCheckoutGetResponse.ShipToZip);
                            Console.WriteLine("SHIPTOCOUNTRY = " + Trans.Response.ExpressCheckoutGetResponse.ShipToCountry);
                            Console.WriteLine("AVSADDR = " + Trans.Response.TransactionResponse.AVSAddr);
                        }
                        // BA_Flag is returned with Express Checkout Reference Transaction with Purchase.
                        // See the notes in DOSetEC regarding this feature.
                        if (Trans.Response.ExpressCheckoutGetResponse.BA_Flag != null)
                        {
                            Console.WriteLine(Environment.NewLine + "BA_FLAG = " + Trans.Response.ExpressCheckoutGetResponse.BA_Flag);
                            if (Trans.Response.ExpressCheckoutGetResponse.BA_Flag == "1")
                            {
                                Console.WriteLine("Buyer Agreement was created.");
                            }
                            else
                            {
                                Console.WriteLine("Buyer Agreement not was accepted.");
                            }
                        }
                    }

                    // If value is true, then the Request ID has not been changed and the original response
                    // of the original transction is returned.
                    Console.WriteLine(Environment.NewLine + "DUPLICATE = " + TrxnResponse.Duplicate);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
    // Insert Inactive Employeee into DB
    public TransactionResponse storeInactiveEmployee()
    {
        //Add List of Arguments for new employee
        IDictionary<string, object> employeeArgumentaMap = new Dictionary<string, object>();

        employeeArgumentaMap.Add("@EmpID", employee.EmpID);
        employeeArgumentaMap.Add("@FName", employee.FName);
        employeeArgumentaMap.Add("@MName", employee.MName);
        employeeArgumentaMap.Add("@LName", employee.LName);
        employeeArgumentaMap.Add("@Sex", employee.Sex);
        employeeArgumentaMap.Add("@JobTitle", employee.JobTitle);
        employeeArgumentaMap.Add("@branch", employee.Branch);
        employeeArgumentaMap.Add("@dateOfEmp", inactiveEmployee.DateOfEmployment);
        employeeArgumentaMap.Add("@dateOfTerm", inactiveEmployee.DateOfTermination);
        employeeArgumentaMap.Add("@majorCategory", inactiveEmployee.MajorCategory);
        employeeArgumentaMap.Add("@ReasonForleave", inactiveEmployee.ReasonForLeave);

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil storeToDb = new DBOperationsUtil(DbAccessConstants.spAddInactiveEmployee, employeeArgumentaMap);

        TransactionResponse response = new TransactionResponse();

        //call store to DB mathod and get reponse.
        try
        {
            storeToDb.instertNewRecord();
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setSuccess(true);
            response.setMessage(DBOperationErrorConstants.M_INACTIVE_EMPLOYEE_REGISTER_OK);
        }

        catch (SqlException ex)
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_EID_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_EMP_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

           //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_EVIL_ERROR);
            response.setMessage(DBOperationErrorConstants.M_UNKNOWN_EVIL_ERROR);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setSuccess(false);
            return response;
        }
        return response;
    }
        public PaymentResponse CreditCardPayment(CreditCardPaymentRequest req)
        {
            var resp      = new PaymentResponse();
            var RequestID = PayflowUtility.RequestId;
            PayflowConnectionData Connection = new PayflowConnectionData(Host, Port <= 0 ? 443 : Port, Timeout <= 30 ? 30 : Timeout, "", 0, "", "");
            UserInfo PaymentProcessorUser    = new UserInfo(User, Vendor, Partner, Password);
            int      trxCount = 1;
            bool     RespRecd = false;


            if (string.IsNullOrEmpty(req.InvoiceNumber))
            {
                req.InvoiceNumber = _confirmationNumberGenerator.GenerateConfirmationNumber();
            }


            Currency Amt = new Currency(req.Amount)
            {
                NoOfDecimalDigits = 0
            };
            Invoice Inv = new Invoice
            {
                Amt      = Amt,
                Comment1 = req.Comment
            };

            //Set the BillTo object into invoice.
            if (req.BillingInformation != null)
            {
                Inv.BillTo = CreateBillTo(req);
            }

            CreditCard CC = new CreditCard(req.AccountNumber, req.Expiration.Replace("/", ""));

            CC.Cvv2 = req.CVC;

            // Create Card Tender data object.
            CardTender Card = new CardTender(CC);  // credit card

            // Notice we set the request id earlier in the application and outside our loop.  This way if a response was not received
            // but PayPal processed the original request, you'll receive the original response with DUPLICATE set.
            SaleTransaction Trans = new SaleTransaction(PaymentProcessorUser, Connection, Inv, Card, RequestID);

            Trans.Verbosity = String.IsNullOrEmpty(Verbosity) ? "HIGH" : Verbosity;
            while (trxCount <= 3 && !RespRecd)
            {
                // Submit the Transaction
                Response Resp = Trans.SubmitTransaction();

                // Display the transaction response parameters.
                if (Resp != null)
                {
                    RespRecd = true;  // Got a response.

                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;

                    if (TrxnResponse != null)
                    {
                        resp = ProcessResponse(TrxnResponse);
                    }
                }
                else
                {
                    trxCount++;
                }
            }

            if (!RespRecd)
            {
                resp.Message = "Payment not processed.  Please contact Customer Service";
            }

            return(resp);
        }
    /**
     * calls Store to DB utility for the current employee.
     */
    public TransactionResponse AddHROfficerOrClerk(string SPName, string EmpID)
    {
        //Add List of Arguments for new employee
        IDictionary<string, object> paramater = new Dictionary<string, object>();

        paramater.Add("@Emp_ID", EmpID);

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil storeToDb = new DBOperationsUtil(SPName, paramater);

        TransactionResponse response = new TransactionResponse();

        //call store to DB mathod and get reponse.
        try
        {
            storeToDb.instertNewRecord();
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setSuccess(true);
            response.setMessage(DBOperationErrorConstants.M_HR_OFFICER_REGISTER_OK);
        }

        catch (SqlException ex)
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_EID_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_EMP_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }

        return response;
    }
Beispiel #37
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOVoiceAuth.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice Inv = new Invoice();

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.12));

            Inv.Amt = Amt;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            CC.Cvv2 = "123";

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);
            ///////////////////////////////////////////////////////////////////

            // Create a new Voice Authorization Transaction.
            // Some processors also require an authorization date to be sent.
            VoiceAuthTransaction Trans = new VoiceAuthTransaction("<AUTH_CODE>",
                                                                  User, Connection, Inv, Card, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
                    Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
                    Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
                    Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
                    Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match);
                }

                // Get the Fraud Response parameters.
                FraudResponse FraudResp = Resp.FraudResponse;

                // Display Fraud Response parameter
                if (FraudResp != null)
                {
                    Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
                    Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Beispiel #38
0
        internal static List <SMB1Command> GetTransactionResponse(bool transaction2Response, byte[] responseSetup, byte[] responseParameters, byte[] responseData, int maxBufferSize)
        {
            List <SMB1Command>  result = new List <SMB1Command>();
            TransactionResponse response;

            if (transaction2Response)
            {
                response = new Transaction2Response();
            }
            else
            {
                response = new TransactionResponse();
            }
            result.Add(response);
            int responseSize = TransactionResponse.CalculateMessageSize(responseSetup.Length, responseParameters.Length, responseData.Length);

            if (responseSize <= maxBufferSize)
            {
                response.Setup = responseSetup;
                response.TotalParameterCount = (ushort)responseParameters.Length;
                response.TotalDataCount      = (ushort)responseData.Length;
                response.TransParameters     = responseParameters;
                response.TransData           = responseData;
            }
            else
            {
                int    currentDataLength = maxBufferSize - (responseSize - responseData.Length);
                byte[] buffer            = new byte[currentDataLength];
                Array.Copy(responseData, 0, buffer, 0, currentDataLength);
                response.Setup = responseSetup;
                response.TotalParameterCount = (ushort)responseParameters.Length;
                response.TotalDataCount      = (ushort)responseData.Length;
                response.TransParameters     = responseParameters;
                response.TransData           = buffer;

                int dataBytesLeftToSend = responseData.Length - currentDataLength;
                while (dataBytesLeftToSend > 0)
                {
                    TransactionResponse additionalResponse;
                    if (transaction2Response)
                    {
                        additionalResponse = new Transaction2Response();
                    }
                    else
                    {
                        additionalResponse = new TransactionResponse();
                    }
                    currentDataLength = dataBytesLeftToSend;
                    responseSize      = TransactionResponse.CalculateMessageSize(0, 0, dataBytesLeftToSend);
                    if (responseSize > maxBufferSize)
                    {
                        currentDataLength = maxBufferSize - (responseSize - dataBytesLeftToSend);
                    }
                    buffer = new byte[currentDataLength];
                    int dataBytesSent = responseData.Length - dataBytesLeftToSend;
                    Array.Copy(responseData, dataBytesSent, buffer, 0, currentDataLength);
                    additionalResponse.TotalParameterCount   = (ushort)responseParameters.Length;
                    additionalResponse.TotalDataCount        = (ushort)responseData.Length;
                    additionalResponse.TransData             = buffer;
                    additionalResponse.ParameterDisplacement = (ushort)response.TransParameters.Length;
                    additionalResponse.DataDisplacement      = (ushort)dataBytesSent;
                    result.Add(additionalResponse);

                    dataBytesLeftToSend -= currentDataLength;
                }
            }
            return(result);
        }
        public void VerifyTransactions(TransactionResponse[] expectedResponse)
        {
            TransactionResponse[] actualResponses = GetTransactions();

            if (actualResponses.Length != expectedResponse.Length)
            {
                VerifyTool.VerifyValue(expectedResponse.Length, actualResponses.Length, "There are {0} transactions");
            }
            else
            {
                for (int i = 0; i < actualResponses.Length; i++)
                {
                    if (!actualResponses.Equals(expectedResponse))
                    {
                        VerifyTool.VerifyValue(expectedResponse[i].Id, actualResponses[i].Id, "The transaction id is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].Date, actualResponses[i].Date, "The transaction date is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].Type, actualResponses[i].Type, "The transaction type is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].Notes, actualResponses[i].Notes, "The transaction notes is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].Amount, actualResponses[i].Amount, "The transaction amount is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].SubTotal, actualResponses[i].SubTotal, "The transaction sub-total is {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].AddBy, actualResponses[i].AddBy, "The transaction added by {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].ModBy, actualResponses[i].ModBy, "The transaction moded by {0}");
                        VerifyTool.VerifyValue(expectedResponse[i].Delete, actualResponses[i].Delete, "The transaction deleted by {0}");
                    }
                }
            }
        }
Beispiel #40
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DORecurringAdd.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

            // Creating a profile where our customer is paying three installments of $25.75 with a shipping
            // charge of $9.95.  So, our first payment will be $25.75 + 9.95 with two more payments of $25.75 due.
            //
            // This is just one example of how you might create a new profile.

            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice Inv = new Invoice();

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.75), "USD");

            Inv.Amt = Amt;
            //Inv.PoNum = "PO12345";
            Inv.InvNum = "INV12345";

            // Set the Billing Address details.
            // Only Street and Zip are set below for AVS check; however, you would probably want
            // to include full name and address information.
            BillTo Bill = new BillTo();

            Bill.BillToStreet  = "123 Main St.";
            Bill.BillToZip     = "12345";
            Bill.BillToCountry = "US";
            Inv.BillTo         = Bill;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            // CVV2 is used for Optional Transaction (Sale or Authorization) Only.  It is not stored as
            // part of the profile, nor is it sent when payments are made.
            CC.Cvv2 = "123";

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);

            RecurringInfo RecurInfo = new RecurringInfo();

            // The date that the first payment will be processed.
            // This will be of the format mmddyyyy.
            RecurInfo.Start       = "07152008";
            RecurInfo.ProfileName = "Test_Profile";             // User provided Profile Name.

            // Specifies how often the payment occurs. All PAYPERIOD values must use
            // capital letters and can be any of WEEK / BIWK / SMMO / FRWK / MONT /
            // QTER / SMYR / YEAR
            RecurInfo.PayPeriod = "WEEK";
            RecurInfo.Term      = 2;        // Number of payments

            // Peform an Optional Transaction.
            RecurInfo.OptionalTrx = "S";              // S = Sale, A = Authorization
            // Set the amount if doing a "Sale" for the Optional Transaction.
            Currency oTrxAmt = new Currency(new decimal(25.75 + 9.95), "USD");

            RecurInfo.OptionalTrxAmt = oTrxAmt;

            // Create a new Recurring Add Transaction.
            RecurringAddTransaction Trans = new RecurringAddTransaction(
                User, Connection, Inv, Card, RecurInfo, PayflowUtility.RequestId);

            // Use ORIGID to create a profile based on the details of another transaction. See Reference Transaction.
            //Trans.OrigId = "<ORIGINAL_PNREF>";

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                }

                // Get the Recurring Response parameters.
                RecurringResponse RecurResponse = Resp.RecurringResponse;
                if (RecurResponse != null)
                {
                    String ProfileMsg;
                    if (TrxnResponse.Result == 0)
                    {
                        ProfileMsg = "Profile Created.";
                    }
                    else
                    {
                        ProfileMsg = "Error, Profile Not Created.";
                    }
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine(("Profile Status: " + ProfileMsg));
                    Console.WriteLine("Recurring Profile Reference (RPREF) = " + RecurResponse.RPRef);
                    Console.WriteLine("Recurring Profile ID (PROFILEID) = " + RecurResponse.ProfileId);

                    // Was an Optional Transaction processed?
                    if (RecurResponse.TrxResult != null)
                    {
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Optional Transaction Details:");
                        Console.WriteLine("Transaction PNREF (TRXPNREF) = " + RecurResponse.TrxPNRef);
                        Console.WriteLine("Transaction Result (TRXRESULT) = " + RecurResponse.TrxResult);
                        Console.WriteLine("Transaction Message (TRXRESPMSG) = " + RecurResponse.TrxRespMsg);
                        Console.WriteLine(("Authorization (AUTHCODE) = " + TrxnResponse.AuthCode));
                        Console.WriteLine(("Security Code Match (CVV2MATCH) = " + TrxnResponse.CVV2Match));
                        Console.WriteLine(("Street Address Match (AVSADDR) = " + TrxnResponse.AVSAddr));
                        Console.WriteLine(("Streep Zip Match (AVSZIP) = " + TrxnResponse.AVSZip));
                        Console.WriteLine(("International Card (IAVS) = " + TrxnResponse.IAVS));

                        // Was this a duplicate transaction?
                        // If this value is true, you will probably receive a result code 19, Original transaction ID not found.
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Duplicate Response:");
                        String DupMsg;
                        if (TrxnResponse.Duplicate == "1")
                        {
                            DupMsg = "Duplicate Transaction";
                        }
                        else
                        {
                            DupMsg = "Not a Duplicate Transaction";
                        }
                        Console.WriteLine("Duplicate Transaction (DUPLICATE) = " + DupMsg);
                    }
                }
                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
    /**
     * calls Store to DB utility for the current employee.
     */
    public TransactionResponse storeEmployee()
    {
        //Add List of Arguments for new employee
        IDictionary<string, object> employeeArgumentaMap = new Dictionary<string, object>();

        employeeArgumentaMap.Add("@Emp_ID", employee.EmpID);
        employeeArgumentaMap.Add("@UserId", employee.UserID);
        employeeArgumentaMap.Add("@First_Name", employee.FName);
        employeeArgumentaMap.Add("@Middle_Name", employee.MName);
        employeeArgumentaMap.Add("@Last_Name", employee.LName);
        employeeArgumentaMap.Add("@Sex", employee.Sex);
        employeeArgumentaMap.Add("@Prev_Job_Tittle", employee.PrevJob);
        employeeArgumentaMap.Add("@Job_Tittle", employee.JobTitle);
        employeeArgumentaMap.Add("@Grade", employee.JobGrade);
        employeeArgumentaMap.Add("@Salary", employee.Salary);
        employeeArgumentaMap.Add("@branch", employee.Branch);
        DateTime HDatefinal = DateTime.ParseExact(employee.Hdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        employeeArgumentaMap.Add("@HDate", HDatefinal);
        employeeArgumentaMap.Add("@MajorCategory", employee.MajorCategory);
        employeeArgumentaMap.Add("@district", employee.District);

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil storeToDb = new DBOperationsUtil(DbAccessConstants.spAddNewEmployee, employeeArgumentaMap);

        TransactionResponse response = new TransactionResponse();

        //call store to DB mathod and get reponse.
        try
        {
            storeToDb.instertNewRecord();
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setSuccess(true);
            response.setMessage(DBOperationErrorConstants.M_EMPLOYEE_REGISTER_OK);
        }

        catch (SqlException ex)
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_EID_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_EMP_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }

        return response;
    }
Beispiel #42
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOVoid.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();
            ///////////////////////////////////////////////////////////////////

            // Create a new Void Transaction.
            // The ORIGID is the PNREF no. for a previous transaction.
            VoidTransaction Trans = new VoidTransaction("<ORIGINAL_PNREF>",
                                                        User, Connection, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
                    Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
                    Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
                    Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
                }

                // Get the Fraud Response parameters.
                FraudResponse FraudResp = Resp.FraudResponse;

                // Display Fraud Response parameter
                if (FraudResp != null)
                {
                    Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
                    Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
    /**
     * Add employee remark
    */
    public TransactionResponse storeEmployeeremark(MembershipUser currentUser)
    {
        //get detail of the logged on user.
        Employee employee = EmployeeManager.getLoggedOnUser((Guid)currentUser.ProviderUserKey);
        if (employee == null)
        {
            return EmployeeManager.handleLoggedInUserCanNotBeIdentfied();
        }

        //Add List of Arguments for new employee
        IDictionary<string, object> employeeRemarkMap = new Dictionary<string, object>();

        employeeRemarkMap.Add("@EmpID", employeeRemark.EmployeeID);
        employeeRemarkMap.Add("@remarkRefNo", employeeRemark.RemarkReferanceNo);
        employeeRemarkMap.Add("@dateOfRemark", employeeRemark.DateOfRemark);
        employeeRemarkMap.Add("@remarkType", employeeRemark.RemarkType);
        employeeRemarkMap.Add("@penalityPerc", employeeRemark.PenaltyPerc);
        employeeRemarkMap.Add("@managerID", employeeRemark.ManagerID);
        employeeRemarkMap.Add("@managerPosition", employeeRemark.ManagerPosition);
        employeeRemarkMap.Add("@remarkReason", employeeRemark.RemarkReason);
        employeeRemarkMap.Add("@responsiblehrOfficerID", employee.EmpID);
        employeeRemarkMap.Add("@Branch", employeeRemark.Branch);

        //Pass Stored Procedure Name and parameter list.
        DBOperationsUtil storeToDb = new DBOperationsUtil(DbAccessConstants.spAddEmployeeRemark, employeeRemarkMap);

        TransactionResponse response = new TransactionResponse();

        //call store to DB mathod and get reponse.
        try
        {
            storeToDb.instertNewRecord();
            response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
            response.setSuccess(true);
            response.setMessage(DBOperationErrorConstants.M_EMPLOYEE_REMARK_REGISTER_OK);
        }

        catch (SqlException ex)
        {
            //Determine if the cause was duplicate KEY.
            if (ex.ToString().Contains(DBOperationErrorConstants.PK_DUPLICATE_INDICATOR))
            {
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_DUPLICATE_REF_NO_KEY_ERROR);
                response.setErrorCode(DBOperationErrorConstants.E_DUPLICATE_KEY_ERROR);
            }
            else
            {
                //Other SqlException is catched
                response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
                response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_EMP_REGISTER);
                response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
            }
        }

        //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            LoggerManager.upDateWithGenericErrorMessage(response);
        }

        return response;
    }
Beispiel #44
0
        static Guid?CreateTransactionExample(Configuration configuration)
        {
            TransactionsApi api = new TransactionsApi(configuration);

            // Please check our documentation at https://docs.transferzero.com/docs/transaction-flow/
            // for details on how transactions work

            // When adding a sender to transaction, please use either an id or external_id. Providing both will result in a validation error.
            // Please see our documentation at https://docs.transferzero.com/docs/transaction-flow/#sender

            Sender sender = new Sender(id: Guid.Parse("058de445-ffff-ffff-ffff-da9c751d14bf"));

            // You can find the various payout options at https://docs.transferzero.com/docs/transaction-flow/#payout-details

            PayoutMethodDetails ngnBankDetails = new PayoutMethodDetails(
                bankAccount: "123456789",
                bankAccountType: PayoutMethodBankAccountTypeEnum._20,
                bankCode: "082",
                firstName: "First",
                lastName: "Last"
                );

            PayoutMethod payoutMethod = new PayoutMethod(
                type: "NGN::Bank",
                details: ngnBankDetails
                );

            // Please see https://docs.transferzero.com/docs/transaction-flow/#requested-amount-and-currency
            // on what the request amount and currencies do

            Recipient recipient = new Recipient(
                requestedAmount: 10000,
                requestedCurrency: "NGN",
                payoutMethod: payoutMethod
                );

            // Similarly you can check https://docs.transferzero.com/docs/transaction-flow/#requested-amount-and-currency
            // on details about the input currency parameter

            // Find more details on external IDs at https://docs.transferzero.com/docs/transaction-flow/#external-id

            Transaction transaction = new Transaction(
                inputCurrency: "USD",
                sender: sender,
                recipients: new List <Recipient>()
            {
                recipient
            },
                externalId: "TRANSACTION-00001"
                );

            try
            {
                TransactionRequest transactionRequest = new TransactionRequest(
                    transaction: transaction
                    );
                TransactionResponse transactionResponse = api.PostTransactions(transactionRequest);
                System.Console.WriteLine("Transaction created! ID" + transactionResponse.Object.Id);
                System.Console.WriteLine(transactionResponse.Object);
                return(transactionResponse.Object.Id);
            }
            catch (ApiException e)
            {
                if (e.IsValidationError)
                {
                    TransactionResponse transactionResponse = e.ParseObject <TransactionResponse>();
                    System.Console.WriteLine("Validation Error" + transactionResponse.Object.Errors);
                }
                else
                {
                    throw e;
                }
                return(null);
            }
        }
 public static TransactionResponse handleLoggedInUserCanNotBeIdentfied()
 {
     TransactionResponse response = new TransactionResponse();
     response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
     response.setErrorCode(DBOperationErrorConstants.M_CAN_NOT_IDENTIFY_CURRENT_USER);
     response.setMessage(DBOperationErrorConstants.M_CAN_NOT_IDENTIFY_CURRENT_USER);
     return response;
 }
 private static void ShowTransactionRecord(TransactionResponse tran)
 {
     Console.WriteLine($"Ledger: {tran.Ledger}, Hash: {tran.Hash}, Fee Paid: {tran.FeeCharged}, Pt:{tran.PagingToken}");
 }
    //delete resigned employee from database
    public TransactionResponse deleteResignedEmployee()
    {
        TransactionResponse response = new TransactionResponse();
        try
        {
            IDictionary<string, object> argumentMap = new Dictionary<string, object>();
            //task referance
            argumentMap.Add("@UserId", employee.UserName);

            //Pass Stored Procedure Name and parameter list.
            DBOperationsUtil dbOperation = new DBOperationsUtil(DbAccessConstants.spDeleteEmployeeInfor, argumentMap);
            bool isDeleteOk = dbOperation.deleteRecord();

            //put the data on Transaction response
            response.Data = isDeleteOk;

            response.setSuccess(true);

            //get delete status inside the TransactionResponse.
            return response;
        }
        catch (SqlException ex)
        {
            response.setErrorCode(DBOperationErrorConstants.E_ERROR_WHILE_REMOVING_INACTIVE_EMPLOYEE);
            response.setMessage(DBOperationErrorConstants.M_UNABLE_TO_REMOVING_INACTIVE_EMPLOYEE);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setSuccess(false);
            return response;
        }

           //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
        catch (Exception ex)
        {
            //Write this exception to file for investigation of the issue later.
            logException(ex);
            response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_EVIL_ERROR);
            response.setMessage(DBOperationErrorConstants.M_UNKNOWN_EVIL_ERROR);
            response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
            response.setSuccess(false);
            return response;
        }
    }
        public async Task SendNativeAssets()
        {
            //Set network and server
            Network network = new Network("Test SDF Network ; September 2015");
            Server  server  = new Server("https://horizon-testnet.stellar.org");
            KeyPair keypair = KeyPair.Random();

            Network.UseTestNetwork();

            var sourceaccID = keypair.AccountId;

            using (var server1 = new Server("https://horizon-testnet.stellar.org"))
            {
                var friendBot = await server.TestNetFriendBot
                                .FundAccount(sourceaccID)
                                .Execute().ConfigureAwait(true);
            }

            //Source keypair from the secret seed
            KeyPair sourceKeypair = KeyPair.FromSecretSeed(keypair.SecretSeed);
            var     SourceaccTest = await server.Accounts.Account(sourceaccID);

            //Load source account data
            AccountResponse sourceAccountResponse = await server.Accounts.Account(sourceKeypair.AccountId);

            //Create source account object
            Account sourceAccount = new Account(sourceKeypair.AccountId, sourceAccountResponse.SequenceNumber);

            //Create asset object with specific amount
            //You can use native or non native ones.
            Asset  asset  = new AssetTypeNative();
            string amount = "30";

            //Load des account data
            AccountResponse descAccountResponse = await server.Accounts.Account("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT");

            //Destination keypair from the account id
            KeyPair destinationKeyPair = KeyPair.FromAccountId("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT");
            var     transactions       = await server.Transactions
                                         .ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT")
                                         .Execute().ConfigureAwait(true);

            var abc  = new TransactionResponse();
            var test = new test.MyTestApp();

            test.Main();
            var tranDetail    = server.Transactions.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT").Cursor("now");
            var paymentDetail = server.Payments.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT");
            //paymentDetail.Stream(operationres);
            //OnhresholdReached?.Invoke(this, new OperationResponse());
            Program1 abcd = new Program1();

            abcd.OnhresholdReached += Abcd_OnhresholdReached;
            abcd.OnhresholdReached += new EventHandler <OperationResponse>(this.Abcd_OnhresholdReached);

            var OperateDetail = server.Operations.ForAccount("GDLRM2QFV7GOOAZDELHFCC5RBRMX4NAZNBSTAKG6NGO4CFODY5PSCYWT");

            //Create payment operation
            PaymentOperation operation = new PaymentOperation.Builder(destinationKeyPair, asset, amount).SetSourceAccount(sourceAccount.KeyPair).Build();


            //Create transaction and add the payment operation we created
            Transaction transaction = new Transaction.Builder(sourceAccount).AddOperation(operation).Build();

            //Sign Transaction
            transaction.Sign(sourceKeypair);

            //Try to send the transaction
            try
            {
                Console.WriteLine("Sending Transaction");
                await server.SubmitTransaction(transaction).ConfigureAwait(true);

                Console.WriteLine("Success!");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Send Transaction Failed");
                Console.WriteLine("Exception: " + exception.Message);
            }
        }
 public TransactionResponse updatePromotionStatus(Promotion promotion, string promoStatus)
 {
     TransactionResponse response = new TransactionResponse();
     try
     {
         //Add List of Arguments for new employee
         IDictionary<string, object> parameters = new Dictionary<string, object>();
         DBOperationsUtil dpOperation = getDBOperationToUpdatePromotionStatus4Assignment(parameters, promotion, promoStatus);
         dpOperation.updateRecord();
         response.setMessageType(TransactionResponse.SeverityLevel.SUCESS);
         response.setSuccess(true);
     }
     catch (SqlException ex)
     {
         //Other SqlException is catched
         response.setMessageType(TransactionResponse.SeverityLevel.ERROR);
         response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_UPDATE_VACANCY);
         response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION);
         response.setSuccess(false);
     }
     //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error
     catch (Exception ex)
     {
         //Write this exception to file for investigation of the issue later.
         logException(ex);
         LoggerManager.upDateWithGenericErrorMessage(response);
     }
     return response;
 }
        public ActionResult GetResponse(string DR)
        {
            logger.Info("GetResponse Method Start" + " at " + DateTime.UtcNow);
            Order order = (Order)Session["order"];

            //Order order = db.Orders.Include("UserProfile").First(t => t.OrderId == oldOrder.OrderId);

            ResponseText responseString = new ResponseText();

            responseString.OrderId = order.OrderId;
            //esponseString.OrderId = 1;
            responseString.ResponseString = DR;
            db.ResponseText.Add(responseString);
            db.SaveChanges();

            string sQS;

            string[] aQS;
            string   pwd = WebConfigurationManager.AppSettings["SecretKey"].ToString();

            DR  = DR.Replace(' ', '+');
            sQS = Base64Decode(DR);
            DR  = EasyPay.Models.RC4.Decrypt(pwd, sQS, false);
            aQS = DR.Split('&');

            TransactionResponse response = new TransactionResponse();

            foreach (string param in aQS)
            {
                string[] aParam = param.Split('=');
                switch (aParam[0])
                {
                case "ResponseCode":
                    response.ResponseCode = aParam[1];
                    break;

                case "ResponseMessage":
                    response.ResponseMessage = aParam[1];
                    break;

                case "DateCreated":
                    response.DateCreated = Convert.ToDateTime(aParam[1]);
                    break;

                case "PaymentID":
                    response.PaymentID = Convert.ToInt32(aParam[1]);
                    break;

                case "MerchantRefNo":
                    response.MerchantRefNo = Convert.ToInt32(aParam[1]);
                    break;

                case "Amount":
                    response.Amount = Convert.ToDecimal(aParam[1]);
                    break;

                case "Mode":
                    response.Mode = aParam[1];
                    break;

                case "BillingName":
                    response.BillingName = aParam[1];
                    break;

                case "TransactionID":
                    response.TransactionID = Convert.ToInt32(aParam[1]);
                    break;

                case "IsFlagged":
                    response.IsFlagged = aParam[1].ToString();
                    break;
                }
            }

            response.OrderId = response.MerchantRefNo;
            db.Responses.Add(response);
            order = db.Orders.FirstOrDefault(x => x.OrderId == response.OrderId);
            db.Entry(order).State = EntityState.Modified;
            logger.Info("Response Code" + response.ResponseCode + " at " + DateTime.UtcNow);
            if (response.ResponseCode != null || response.ResponseCode != string.Empty)
            {
                if (response.ResponseCode == "0")
                {
                    logger.Info("Response Code is 0" + " at " + DateTime.UtcNow);
                    //successful transaction
                    if (response.IsFlagged.ToLower().Equals("no"))
                    {
                        logger.Info("Response IsFlagged" + response.IsFlagged + " at " + DateTime.UtcNow);
                        //successful transaction
                        if (response.MerchantRefNo == order.OrderId && response.Amount == order.Amount)
                        {
                            logger.Info("Merchant Reference No " + response.MerchantRefNo + " Merchant Amount " + response.Amount + " at " + DateTime.UtcNow);
                            order.Status = (int)OrderStatus.PaymentSuceess;
                            logger.Info("Order Status " + order.Status + " at " + DateTime.UtcNow);
                            //order.Remarks = "Payment Successfull";
                            order.comments = response.ResponseMessage;
                        }
                        else
                        {
                            order.Status = (int)OrderStatus.WrongOrderId;
                            logger.Info("Order Status " + order.Status + " at " + DateTime.UtcNow);
                            // response with wrong orderid
                            //order.Status = (int)OrderStatus.Pending;
                            //order.Remarks = "Payment Pending";
                            order.comments = response.ResponseMessage;
                        }
                    }
                    else
                    {
                        logger.Info("Response IsFlagged" + response.IsFlagged + " at " + DateTime.UtcNow);
                        if (response.MerchantRefNo == order.OrderId && response.Amount == order.Amount)
                        {
                            order.Status = (int)OrderStatus.PaymentSuceess;
                            logger.Info("Order Status " + order.Status + " at " + DateTime.UtcNow);
                            //order.Remarks = "Payment Successfull";
                            order.comments = response.ResponseMessage;
                        }
                        //Temporary
                        ////pending trasaction
                        //order.Status = (int)OrderStatus.IsFlaggedPayment;
                        ////order.Remarks = "Payment Pending";
                        //order.comments = response.ResponseMessage;
                    }
                }
                else
                {
                    //declined trasaction or erroroccured
                    order.Status = (int)OrderStatus.PaymentFailed;
                    logger.Info("Order Status " + order.Status + " at " + DateTime.UtcNow);
                    //order.Remarks = "Payment Failed";
                    order.comments = response.ResponseMessage;
                }
            }
            else
            {
                logger.Info("Response code is null or empty at " + DateTime.UtcNow);
                //error occured in transaction
                order.Status = (int)OrderStatus.PaymentFailed;
                logger.Info("Order Status " + order.Status + " at " + DateTime.UtcNow);
                //order.Remarks = "Payment Failed";
                order.comments = response.ResponseMessage;
            }
            db.SaveChanges();
            ViewData.Model = order;
            logger.Info("GetResponse Method End" + " at " + DateTime.UtcNow);
            return(View());
        }
    private string getDetailOfSelectedVacancy(Vacancy vacancy)
    {
        VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager();
        TransactionResponse response = new TransactionResponse();

        //get vacancy detail
        response = manager.getVacancyDetail(vacancy);
        DataTable dataTable = (DataTable)response.Data;

        return (dataTable.Rows[0]["vacancy_evaluation_form"].ToString().Trim());
    }
        /// <summary>
        /// Charges the specified payment info.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;
            Response ppResponse = null;

            var invoice = GetInvoice(paymentInfo);

            // add in spark reference code
            BrowserInfo browser = new BrowserInfo();

            browser.ButtonSource = "SparkDevelopmentNetwork_SP";
            invoice.BrowserInfo  = browser;

            var tender = GetTender(paymentInfo);

            if (tender != null)
            {
                if (paymentInfo is ReferencePaymentInfo)
                {
                    var reference     = paymentInfo as ReferencePaymentInfo;
                    var ppTransaction = new ReferenceTransaction("Sale", reference.TransactionCode, GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
                else
                {
                    var ppTransaction = new SaleTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
            }
            else
            {
                errorMessage = "Could not create tender from PaymentInfo";
            }

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        var transaction = new FinancialTransaction();
                        transaction.TransactionCode = txnResponse.Pnref;

                        // Get the stored payment method that was used so we can update it
                        //  with the latest transaction code.  We do this because Paypal
                        //  will only let us use the same transaction code in reference
                        //  transactions for up to 12 months.
                        if (paymentInfo is ReferencePaymentInfo)
                        {
                            var reference    = paymentInfo as ReferencePaymentInfo;
                            var rockContext  = new RockContext();
                            var savedAccount = new FinancialPersonSavedAccountService(rockContext)
                                               .Queryable()
                                               .Where(s =>
                                                      s.TransactionCode == reference.TransactionCode &&
                                                      s.FinancialGatewayId.HasValue &&
                                                      s.FinancialGatewayId.Value == financialGateway.Id)
                                               .FirstOrDefault();
                            if (savedAccount != null)
                            {
                                savedAccount.TransactionCode = txnResponse.Pnref;
                                rockContext.SaveChanges();
                            }
                        }

                        return(transaction);
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }
    private void BindFirstPhaseReport(int isfromAll, DropDownList selectDropDown)
    {

        lblVacancyPhase1.Visible = false;

        lblVacancyPhase1.Visible = false;
        string[] splitter = new string[] { PageConstants.GREATER_GREATER_THAN };
        string[] VacancyInfoTosplit = (selectDropDown.SelectedValue).Split(splitter, StringSplitOptions.RemoveEmptyEntries);
        currentVacancyNo = VacancyInfoTosplit[0].Trim();
        currentVacancyDate = VacancyInfoTosplit[1].Trim();
        resposibleHROfficer = VacancyInfoTosplit[3].Trim();
        Vacancy vacancy = new Vacancy();
        vacancy.VacancyNo = currentVacancyNo;
        vacancy.PostedDate = currentVacancyDate;

        //get recently selected employee
        getRecentlySelectedLateralPenalityEmployee(vacancy, isfromAll);

        //get and display the vacancy to user. 
        getVacancyReportAndDisplayToUser(vacancy, PageConstants.REPORT_PHASE1, isfromAll);


        VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager();
        TransactionResponse response = new TransactionResponse();

        //get vacancy detail
        response = manager.getVacancyDetail(vacancy);
        DataTable dataTable = (DataTable)response.Data;
        string postDate = "";
        try
        {
            postDate = String.Format("{0:MMM d, yyyy}", Convert.ToDateTime(dataTable.Rows[0]["posted_date"]));
        }
        catch (Exception)
        {
        }
        VacDetailPanel.Visible = true;
        lblVacancyPost.Text = dataTable.Rows[0]["Vancay_title"].ToString() + "  ( JG - " +
                              dataTable.Rows[0]["vacancy_for_JobGrade"].ToString() + " )";
        lblVacancyNum.Text = dataTable.Rows[0]["vacancy_No"].ToString() + " dated " + postDate;

        //lblJobDes.Text = "Specification: ";

        lblJobReq.Text = dataTable.Rows[0]["JobDescription"].ToString() + " " + dataTable.Rows[0]["JobRequirement"].ToString() + ". ";


        VacDetailAllForstPhasePanel.Visible = true;
        lblAll1stVacancyPost.Text = dataTable.Rows[0]["Vancay_title"].ToString() + "  ( JG - " +
                              dataTable.Rows[0]["vacancy_for_JobGrade"].ToString() + " )";
        lblAll1stVacancyNum.Text = dataTable.Rows[0]["vacancy_No"].ToString() + " dated " + postDate;
        //lblJobDes.Text = "Specification: ";

        lblAll1stJobReq.Text = dataTable.Rows[0]["JobDescription"].ToString() + " " + dataTable.Rows[0]["JobRequirement"].ToString() + ". ";
   
    }
        /// <summary>
        /// Adds the scheduled payment.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="schedule">The schedule.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialScheduledTransaction AddScheduledPayment(FinancialGateway financialGateway, PaymentSchedule schedule, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            var recurring = GetRecurring(schedule);

            if (paymentInfo is CreditCardPaymentInfo)
            {
                recurring.OptionalTrx = "A";
            }

            var ppTransaction = new RecurringAddTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), GetInvoice(paymentInfo), GetTender(paymentInfo),
                                                            recurring, PayflowUtility.RequestId);

            if (paymentInfo is ReferencePaymentInfo)
            {
                var reference = paymentInfo as ReferencePaymentInfo;
                ppTransaction.OrigId = reference.TransactionCode;
            }
            var ppResponse = ppTransaction.SubmitTransaction();

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        RecurringResponse recurringResponse = ppResponse.RecurringResponse;

                        if (recurringResponse != null)
                        {
                            var scheduledTransaction = new FinancialScheduledTransaction();
                            scheduledTransaction.TransactionCode    = recurringResponse.TrxPNRef;
                            scheduledTransaction.GatewayScheduleId  = recurringResponse.ProfileId;
                            scheduledTransaction.FinancialGatewayId = financialGateway.Id;

                            GetScheduledPaymentStatus(scheduledTransaction, out errorMessage);
                            return(scheduledTransaction);
                        }
                        else
                        {
                            errorMessage = "Invalid recurring response from the financial gateway";
                        }
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }
    private void bindAccessorProcessor(GridViewRowEventArgs e, DropDownList selectDropDown, GridView selectGV)
    {

        //get processor and check name

        string[] splitter = new string[] { PageConstants.GREATER_GREATER_THAN };
        string[] VacancyInfoTosplit = (selectDropDown.SelectedValue).Split(splitter, StringSplitOptions.RemoveEmptyEntries);
        currentVacancyNo = VacancyInfoTosplit[0].Trim();
        currentVacancyDate = VacancyInfoTosplit[1].Trim();
        resposibleHROfficer = VacancyInfoTosplit[3].Trim();
        Vacancy vacancy = new Vacancy();
        vacancy.VacancyNo = currentVacancyNo;
        vacancy.PostedDate = currentVacancyDate;


        VacancyRegistrationAndEvaluationManager vacancyRegEvaluationManager = new VacancyRegistrationAndEvaluationManager(vacancy);
        TransactionResponse response = new TransactionResponse();
        response = vacancyRegEvaluationManager.getVacancyDetail(vacancy);

        DataTable employeeData = (DataTable)response.Data;


        Employee employee = new Employee();
        //get list of Employee using Employee manager.
        if (employeeData != null && employeeData.Rows.Count > 0)
        {

            // Display processor and checker in the gridview footer
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                //get processor First name & Middle Name
                employee.EmpID = employeeData.Rows[0]["responsible_processor_EID"].ToString();

                EmployeeManager employeeManager = new EmployeeManager(employee);
                List<Employee> listOfEmployee = employeeManager.getEmployeeDetial();
                string fullName = null;

                foreach (Employee emply in listOfEmployee)
                {
                    fullName = emply.FName + " " + emply.MName;
                }

                e.Row.Cells[2].Text = "Processed by :";
                e.Row.Cells[2].Font.Bold = true;

                e.Row.Cells[3].Text = fullName;
                e.Row.Cells[3].Font.Bold = true;

                //get checkor First name & Middle Name
                employee.EmpID = employeeData.Rows[0]["reponsible_accessor_EID"].ToString();
                employeeManager = new EmployeeManager(employee);
                listOfEmployee = employeeManager.getEmployeeDetial();

                fullName = null;
                foreach (Employee emply in listOfEmployee)
                {
                    fullName = emply.FName + " " + emply.MName;
                }

                e.Row.Cells[7].Text = "Assessed by :";
                e.Row.Cells[7].Font.Bold = true;

                e.Row.Cells[8].Text = fullName;
                e.Row.Cells[8].Font.Bold = true;
            }
        }
        else
        {
            selectGV.ShowFooter = false;
        }
    }
        /// <summary>
        /// Authorizes the specified payment info.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Authorize(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;
            Response ppResponse = null;

            var invoice = GetInvoice(paymentInfo);

            BrowserInfo browser = new BrowserInfo();

            browser.ButtonSource = "SparkDevelopmentNetwork_SP";
            invoice.BrowserInfo  = browser;

            var tender = GetTender(paymentInfo);

            if (tender != null)
            {
                if (paymentInfo is ReferencePaymentInfo)
                {
                    var reference     = paymentInfo as ReferencePaymentInfo;
                    var ppTransaction = new ReferenceTransaction("Authorization", reference.TransactionCode, GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
                else
                {
                    var ppTransaction = new AuthorizationTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
            }
            else
            {
                errorMessage = "Could not create tender from PaymentInfo";
            }

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        var transaction = new FinancialTransaction();
                        transaction.TransactionCode = txnResponse.Pnref;
                        return(transaction);
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }
        private async void DumpExportFilesAsync(TransactionResponse response)
        {
            if (string.IsNullOrEmpty(response.TransactionData)) return;
            var orders = response.TransactionData;
            
            string fileName =string.Format("{0}_{1}{2}","export", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"),".csv");
            string selectedPath = Path.Combine(TransactionsExportPath, fileName);
            if (string.IsNullOrEmpty(selectedPath))
            {
                Messenger.Default.Send(
                         string.Format(DateTime.Now.ToString("hh:mm:ss") + ":Undefined export file path..files not dumped"));
                return;
            }
            try
            {
               if(File.Exists(selectedPath))
                    File.Delete(selectedPath);
                using (var fs = new FileStream(selectedPath, FileMode.OpenOrCreate))
                {
                    fs.Close();
                    using (var wr = new StreamWriter(selectedPath, false))
                    {
                        await wr.WriteLineAsync(orders);

                    }
                }
                var refs = response.DocRefs;
                if (refs.Any())
                    await Acknowledge(refs.Distinct().ToList());
                Messenger.Default.Send(
                           string.Format(DateTime.Now.ToString("hh:mm:ss") + string.Format("Task completed,File damped on folder path {0}",selectedPath)));
               
            }
            catch (IOException ex)
            {
                Messenger.Default.Send(
                          string.Format(DateTime.Now.ToString("hh:mm:ss") + ": File System Error \n Details=>"+ex.Message));
                
            }
            catch(Exception ex)
            {
                Messenger.Default.Send(
                           string.Format(DateTime.Now.ToString("hh:mm:ss") + ": General Error \n Details=>" + ex.Message)); 
            }
           
        }
Beispiel #58
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOSetEC.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // See the DoSaleComplete sample for more information on setting the Connection object.
            PayflowConnectionData Connection = new PayflowConnectionData();

            // Create the invoice object and set the amount value.
            Invoice Inv = new Invoice();

            Inv.Amt       = new Currency(new decimal(21.98), "USD");
            Inv.OrderDesc = "This is my Order Description";

            // **** PayPal Pay Later Service ****
            // PayPal Pay Later is a new, convenient, and secure service that allows you to offer your
            // customers promotional financing. Buyers that choose the promotional offer can defer
            // payments for purchases on participating merchant web sites, allowing them to shop now and
            // pay later.
            // The PayPal Pay Later service allows online merchants to offer promotional financing to
            // buyers at checkout - even if a buyer doesn't have a PayPal account. Promotional offers, such as
            // no payments for 90 days, give merchants new and powerful ways to market to online
            // shoppers.
            // The PayPal Pay Later service is issued by GE Money Bank, one of the world's leading
            // providers of consumer credit.
            // **** Signing Up for PayPal Pay Later ****
            // PayPal's new promotional financing is currently available to consumers and select merchants
            // in the U.S. If you are a merchant and would like to add this service, please contact your sales
            // representative for information and additional documentation.
            //
            //PayLater setPayLater = new PayLater();
            //setPayLater.ShippingMethod = "UPSGround";
            //setPayLater.ProductCategory = "E"; // Camera and Photos
            //setPayLater.PayPalCheckoutBtnType = "P";
            // You can combine up to 10 promotions for PayPal Promotional Financing.
            // L_PROMOCODE0
            //PayLaterLineItem setPayLaterLineItem = new PayLaterLineItem();
            //setPayLaterLineItem.PromoCode = "101";
            //setPayLater.PayLaterAddLineItem(setPayLaterLineItem);
            // L_PROMOCODE1
            //PayLaterLineItem setPayLaterLineItem1 = new PayLaterLineItem();
            //setPayLaterLineItem1.PromoCode = "102";
            //setPayLater.PayLaterAddLineItem(setPayLaterLineItem1);

            // **** Performing a Standard Transaction using Express Checkout ****
            //
            // Express Checkout offers your customers an easy, convenient checkout experience. It lets them
            // use shipping and billing information stored securely at PayPal to check out, so they don’t have
            // to re-enter it on your site.
            //
            // From the perspective of website development, Express Checkout works like other Payflow Pro
            // features. You submit transaction information to the server as name-value pair parameter
            // strings.
            //
            // Create the data object for Express Checkout SET operation using ECSetRequest Data Object.
            ECSetRequest SetRequest = new ECSetRequest("http://www.myreturnurl.com", "http://www.mycancelurl.com");

            // If using Pay Later, you would create the data object as below.
            //ECSetRequest setRequest = new ECSetRequest("http://www.myreturnurl.com", "http://www.mycancelurl.com", setPayLater);

            // **** Performing a Reference Transaction using Express Checkout ****
            //
            // NOTE: You must be enabled by PayPal to use reference transactions. Contact your account manager
            // or the sales department for more details.
            //
            // See the "Using Reference Transactions with Express Checkout" guide that is supplied to you
            // once your account is active with the feature.

            // *** With Making a Purchase ***
            // Say that you have implemented Express Checkout on your website. The customer logs in to
            // purchase an item of merchandise and chooses PayPal to pay for it. In the normal Express
            // Checkout flow, the customer is then redirected to PayPal to log in to verify their billing
            // information. If the customer approves payment on the Confirmation page when you are using
            // a reference transaction, you receive the billing agreement as part of the transaction.You can
            // use that billing agreement later to bill the customer a set amount on a recurring basis, such as
            // once-a-month, for future purchases. The customer doesn’t need to log into PayPal each time to
            // make a payment.
            //
            // Create the data object for Express Checkout Reference Transaction SET operation
            // with Purchase using ECSetRequest Data Object.
            //ECSetRequest SetRequest = new ECSetRequest("http://www.myreturnurl.com", "http://www.mycancelurl.com",
            //		"MerchantInitiatedBilling", "Test Description", "any", "BACustom");

            // *** Without Making a Purchase ***
            // Typically, the customer chooses a billing agreement without making a purchase when they
            // subscribe for merchandise they will pay for on a recurring schedule. If, for example, the
            // customer logs in to your website to order a magazine subscription, you set up an agreement to
            // bill the customer on a scheduled basis, say, once a month. In the billing agreement flow
            // without purchase, the customer is redirected to PayPal to log in. On the PayPal site, they
            // consent to the billing agreement. Next month, when you send the customer the first magazine
            // issue, the billing agreement authorizes you to start charging the customer’s PayPal account on
            // the agreed upon recurring basis without having the customer log in to PayPal.
            //
            // Create the data object for Express Checkout Reference Transaction SET operation
            // without Purchase using ECSetBARequest Data Object.
            //ECSetBARequest SetRequest = new ECSetBARequest("http://www.myreturnurl.com", "http://www.mycancelurl.com",
            //		"MerchantInitiatedBilling", "Test Description", "any", "BACustom");

            // Create the Tender object.
            PayPalTender Tender = new PayPalTender(SetRequest);

            // Create the transaction object.
            AuthorizationTransaction Trans = new AuthorizationTransaction
                                                 (User, Connection, Inv, Tender, PayflowUtility.RequestId);

            // Create an Order Transaction.  An Order transaction represents an agreement to pay one or more
            // authorized amounts up to the specified total over a maximum of 29 days.
            // Refer to the Express Checkout for Payflow Pro Developer's Guide regarding Orders.
            //OrderTransaction Trans = new OrderTransaction(User, Connection, Inv, Tender, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result.ToString());
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("TOKEN = " + Trans.Response.ExpressCheckoutSetResponse.Token);
                    Console.WriteLine("CORRELATIONID = " + TrxnResponse.CorrelationId);
                    // If value is true, then the Request ID has not been changed and the original response
                    // of the original transction is returned.
                    Console.WriteLine("DUPLICATE = " + TrxnResponse.Duplicate);
                }

                if (TrxnResponse.Result == 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction was Approved.");
                    Console.WriteLine(Environment.NewLine + "The next step would be to redirect to PayPal to allow customer to log");
                    Console.WriteLine("into their account to select payment.  For this demo, DO NOT CLOSE the browser");
                    Console.WriteLine("as you will need the TOKEN and/or PAYER ID from the URL for the GET and DO");
                    Console.WriteLine("samples.");
                    Console.WriteLine(Environment.NewLine + "Make sure you are logged into Developer Central (https://developer.paypal.com) before continuing.");
                    Console.WriteLine(Environment.NewLine + "Press <Enter> to redirect to PayPal.");
                    Console.ReadLine();

                    // Using the PayPal SandBox for Express Checkout:
                    // Before you can use the PayPal Sandbox with a Gateway account you'll need to do the following:
                    // To setup a PayPal Sandbox account to work with a Payflow Pro account you will need to go to
                    // https://developer.paypal.com and create an account.  Once you have access to the Sandbox then
                    // you will be able to set up test business accounts, premier accounts and personal accounts.  Please
                    // set up a test business account and personal account so you can test Express Checkout.
                    //
                    // Once you have a test business account created, create a ticket at http://www.paypal.com/mts
                    // under Contact Support and request to have your Payflow Pro (US, AU) or Websites Payments Pro
                    // Payflow Edition (UK) account modified to use the PayPal Sandbox.  Provide the e-mail ID you
                    // used when you created your account on the Sandbox.
                    //
                    // Once you are notified that your account has been updated you will then need to modify the host
                    // URLs of the Payflow Pro Express Checkout test servers to the URLs used by the Sandbox.
                    // For example, https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=<token>.

                    // If the SET operation succeeds, you will get a secure session token id in the response of this
                    // operation.  Using this token, redirect the user's browser as follows:

                    // For Regular Express Checkout or Express Checkout (Reference) with Purchase.
                    String PayPalUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";

                    // For Express Checkout (Reference) without Purchase.
                    //String PayPalUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_customer-billing-agreement&token=";

                    PayPalUrl += Trans.Response.ExpressCheckoutSetResponse.Token;
                    //Process.Start(PayPalUrl);  // Open default browser.
                    //Process.Start("iexplore.exe", PayPalUrl);
                    Process.Start("C:\\Program Files\\Mozilla Firefox\\firefox.exe", PayPalUrl);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press <Enter> to Exit ...");
            Console.ReadLine();
        }
            // Methods and other gack
            public void ContinueTransaction(TransactionResponse transactionResponse)
            {
                // nuke values that definitely won't be in the next transaction
                m_transTimestamp = null;
                m_transType = null;
                m_transSHA1Hash = null;

                TransPASRef = transactionResponse.ResultPASRef;
                TransAuthCode = transactionResponse.ResultAuthCode;
                TransOrderID = transactionResponse.ResultOrderID;
            }
        public ActionResult CreditVoid(int id, string type, decimal?amt, TransactionsModel m)
        {
            var t = CurrentDatabase.Transactions.SingleOrDefault(tt => tt.Id == id);

            if (t == null)
            {
                return(Content("notran"));
            }

            var qq = from tt in CurrentDatabase.Transactions
                     where tt.OriginalId == id || tt.Id == id
                     orderby tt.Id descending
                     select tt;
            var t0 = qq.First();
            var gw = CurrentDatabase.Gateway(t.Testing ?? false);
            TransactionResponse resp = null;
            var re = t.TransactionId;

            if (re.Contains("(testing"))
            {
                re = re.Substring(0, re.IndexOf("(testing)"));
            }

            if (type == "Void")
            {
                resp = gw.VoidCreditCardTransaction(re);
                if (!resp.Approved)
                {
                    resp = gw.VoidCheckTransaction(re);
                }

                t.Voided = resp.Approved;
                amt      = t.Amt;
            }
            else
            {
                if (t.PaymentType == PaymentType.Ach)
                {
                    resp = gw.RefundCheck(re, amt ?? 0);
                }
                else if (t.PaymentType == PaymentType.CreditCard)
                {
                    resp = gw.RefundCreditCard(re, amt ?? 0, t.LastFourCC);
                }

                t.Credited = resp.Approved;
            }

            if (!resp.Approved)
            {
                return(Content("error: " + resp.Message));
            }

            var transaction = new Transaction
            {
                TransactionId      = resp.TransactionId + (t.Testing == true ? "(testing)" : ""),
                First              = t.First,
                MiddleInitial      = t.MiddleInitial,
                Last               = t.Last,
                Suffix             = t.Suffix,
                Amt                = -amt,
                Amtdue             = t0.Amtdue + amt,
                Approved           = true,
                AuthCode           = t.AuthCode,
                Message            = t.Message,
                Donate             = -t.Donate,
                Regfees            = -t.Regfees,
                TransactionDate    = DateTime.Now,
                TransactionGateway = t.TransactionGateway,
                Testing            = t.Testing,
                Description        = t.Description,
                OrgId              = t.OrgId,
                OriginalId         = t.OriginalId,
                Participants       = t.Participants,
                Financeonly        = t.Financeonly,
                PaymentType        = t.PaymentType,
                LastFourCC         = t.LastFourCC,
                LastFourACH        = t.LastFourACH
            };

            CurrentDatabase.Transactions.InsertOnSubmit(transaction);
            CurrentDatabase.SubmitChanges();
            CurrentDatabase.SendEmail(Util.TryGetMailAddress(CurrentDatabase.StaffEmailForOrg(transaction.OrgId ?? 0)),
                                      "Void/Credit Transaction Type: " + type,
                                      $@"<table>
<tr><td>Name</td><td>{Transaction.FullName(t)}</td></tr>
<tr><td>Email</td><td>{t.Emails}</td></tr>
<tr><td>Address</td><td>{t.Address}</td></tr>
<tr><td>Phone</td><td>{t.Phone}</td></tr>
<tr><th colspan=""2"">Transaction Info</th></tr>
<tr><td>Description</td><td>{t.Description}</td></tr>
<tr><td>Amount</td><td>{-amt:N2}</td></tr>
<tr><td>Date</td><td>{t.TransactionDate.FormatDateTm()}</td></tr>
<tr><td>TranIds</td><td>Org: {t.Id} {t.TransactionId}, Curr: {transaction.Id} {transaction.TransactionId}</td></tr>
<tr><td>User</td><td>{Util.UserFullName}</td></tr>
</table>", Util.EmailAddressListFromString(CurrentDatabase.StaffEmailForOrg(transaction.OrgId ?? 0)));
            DbUtil.LogActivity("CreditVoid for " + t.TransactionId);

            return(View("List", m));
        }