Ejemplo n.º 1
0
 protected void Toolbar1_ButtonClicked(object sender, SCS.Web.UI.WebControls.ButtonEventArgs e)
 {
     if (e.CommandName.Equals("BACK"))
     {
         Response.Redirect(string.Format("displayfiles.aspx?submissionId={0}", SubmissionId));
     }
     if (e.CommandName.Equals("SAVE"))
     {
         if (gvDetails.Rows.Count == 0)
         {
             MessageBox.Show("There is no file details.");
             return;
         }
         var row              = gvDetails.Rows[0];
         var ddlOutcome       = row.FindControl("ddlOutcome") as DropDownList;
         var txtOutcomeReason = row.FindControl("txtOutcomeReason") as TextBox;
         if (ddlOutcome != null && txtOutcomeReason != null)
         {
             var detailse = new FileValidationOutcomeDetails {
                 Id                  = 0,
                 SubmissionId        = Convert.ToDecimal(SubmissionId),
                 FileId              = Convert.ToDecimal(Request["fId"]),
                 ValidationOutcomeId = Convert.ToInt32(ddlOutcome.SelectedValue),
                 SID                 = Sars.Systems.Security.ADUser.CurrentSID,
                 OutcomeReason       = string.IsNullOrEmpty(txtOutcomeReason.Text) ? null :txtOutcomeReason.Text
             };
             var saved = DBWriteManager.SaveFileValidationOutcome(detailse);
             if (saved > 0)
             {
                 MessageBox.Show(string.Format("Validation Saved as [{0}]", ddlOutcome.SelectedItem.Text));
             }
         }
     }
 }
Ejemplo n.º 2
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var fileReceivedBody             = FdrCommon.WrapHtmlElement(txtFileReceived.Text);
        var fileAcceptedBody             = FdrCommon.WrapHtmlElement(txtFileAccepted.Text);
        var fileRejectedBody             = FdrCommon.WrapHtmlElement(txtFileRejected.Text);
        var fileAcceptedWithWarningsBody = FdrCommon.WrapHtmlElement(txtFileAcceptedWithWarnings.Text);

        var saved = DBWriteManager.SaveMasterLocalFileNotificationEmailBodyTemplates(new MasterLocalFileNotificationEmailBodyTemplate
        {
            Id                       = 0,
            AcceptedBody             = fileAcceptedBody,
            AcceptedWithWarningsBody = fileAcceptedWithWarningsBody,
            RejectedBody             = fileRejectedBody,
            ReceivedBody             = fileReceivedBody,
            CreatedBy                = Sars.Systems.Security.ADUser.CurrentSID,
            DateLastModified         = DateTime.Now,
            LastModifiedBy           = Sars.Systems.Security.ADUser.CurrentSID
        });

        MessageBox.Show(saved > 0
            ? "Master/Local File Notification Email Templates saved successfully"
            : "Issues reported during saving");
        btnSave.Enabled                     = false;
        txtFileAccepted.Enabled             = false;
        txtFileRejected.Enabled             = false;
        txtFileReceived.Enabled             = false;
        txtFileAcceptedWithWarnings.Enabled = false;
    }
Ejemplo n.º 3
0
    protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        var userID = e.CommandArgument.ToString();

        string roleID  = string.Empty;
        string message = string.Empty;

        if (e.CommandName != "Page")
        {
            GridViewRow  row     = (GridViewRow)((Button)e.CommandSource).NamingContainer;
            int          index   = Convert.ToInt16(row.RowIndex);
            DropDownList ddlRole = (DropDownList)row.FindControl("ddlRole");
            if (ddlRole != null)
            {
                roleID = ddlRole.SelectedItem.Value;

                if (DBWriteManager.UpdateUserRole(userID, roleID) > 0)
                {
                    var user = row.Cells[1].Text + "-" + row.Cells[2].Text + " " + row.Cells[3].Text;
                    message = string.Format("Updated {0}'s role successfully to {1}", user, ddlRole.SelectedItem.Text);
                    MessageBox.Show(message);
                    row.Cells[6].Enabled = false;
                    bindData();
                }
            }
        }
    }
Ejemplo n.º 4
0
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        Button      btnGenerate = (Button)sender;
        GridViewRow gvRow       = (GridViewRow)btnGenerate.Parent.Parent;
        Guid        newUID      = new Guid();
        var         xmldoc      = new XmlDocument();
        XmlNode     messageSpec = xmldoc.CreateNode(XmlNodeType.Element, "MessageSpec", null);
        var         countryCode = gvRow.Cells[0].Text.Split('-')[1].Trim();
        var         country     = gvRow.Cells[0].Text.Split('-')[0].Trim();
        var         year        = int.Parse(gvRow.Cells[1].Text);

        if (ValidateRequiredFields(year))
        {
            decimal id      = 0;
            var     package = Common.GenerateNewPackage(countryCode, dpReportingPeriod.Text, ref messageSpec, id);
            if (!string.IsNullOrEmpty(package.ToString()))
            {
                var outgoingCBC = new OutGoingCBCDeclarations()
                {
                    Id              = id,
                    Country         = countryCode,
                    CBCData         = package.ToString(),
                    NSCBCData       = null,
                    StatusId        = 2,
                    Year            = year,
                    ReportingPeriod = DateTime.Parse(dpReportingPeriod.Text),
                    CreatedBy       = Sars.Systems.Security.ADUser.CurrentSID
                };

                id = DatabaseWriter.SaveOutgoingCBC(outgoingCBC, ref newUID);
                if (id > 0)
                {
                    var newPackage     = Common.GenerateNewPackage(countryCode, dpReportingPeriod.Text, ref messageSpec, id);
                    var newMessageSpec = messageSpec;
                    var nmPackage      = Common.GenerateNMPackage(countryCode, dpReportingPeriod.Text, newMessageSpec);
                    var newPackagedCBC = new OutGoingCBCDeclarations()
                    {
                        Id        = id,
                        Country   = countryCode,
                        CBCData   = newPackage.ToString(),
                        NSCBCData = nmPackage,
                        StatusId  = 2,
                        Year      = year,
                        CreatedBy = Sars.Systems.Security.ADUser.CurrentSID
                    };
                    var saved = DatabaseWriter.SaveOutgoingCBC(newPackagedCBC, ref newUID);
                }

                DBWriteManager.Insert_OutgoingPackageAuditTrail(newUID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Package for {0} generated", country));

                LoadCBC();
                MessageBox.Show(string.Format("Package for {0} was successfully generated", country));
            }
        }
    }
Ejemplo n.º 5
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var updated = DBWriteManager.UpdateUserProfile(
            txtUserName.SID,
            txtTel.Text
            );

        MessageBox.Show(updated > 0
            ? "User profile updated successfully."
            : "There was a problem updating user profile.");
    }
Ejemplo n.º 6
0
    protected void btnApprove_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        decimal id           = decimal.Parse(Request.QueryString["idx"].ToString());
        int     statusId     = int.Parse(Request.QueryString["statusIdx"].ToString());
        string  incominLocal = Request.QueryString["incLocal"].ToString();
        var     country      = gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim() + "_" + gvCBC.Rows[0].Cells[5].Text;

        if (fp.IsUserInRole("Reviewer") || fp.IsUserInRole("Approver"))
        {
            try
            {
                int      status        = fp.IsUserInRole("Reviewer") ? 3 : 5;
                bool     blnIsReviewer = fp.IsUserInRole("Reviewer") ? true : false;
                var      email         = string.IsNullOrEmpty(ADUser.CurrentUser.Mail) ? "*****@*****.**" : ADUser.CurrentUser.Mail;
                string[] senderEmail   = { email };
                string   Subject       = "";
                DBWriteManager.ApproveForeignPackage(status, id, ADUser.CurrentSID);
                var    mspec   = DBReadManager.GetMessageSpecById(id);
                string message = string.Format("Incoming Package for {0} has been approved successfully", country);
                if (blnIsReviewer)
                {
                    DBWriteManager.Insert_OutgoingPackageAuditTrail(mspec.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Incoming Package for {0} from {1} verified", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim()));
                    Subject = string.Format("Incoming Package for {0} from {1} has been verified ", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(),
                                            gvCBC.Rows[0].Cells[3].Text.Split('-')[0].Trim());
                    Common.SendEmailToRole("Approver", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(), Subject, FDRPage.Statuses.Verified, senderEmail);
                }
                else
                {
                    DBWriteManager.Insert_OutgoingPackageAuditTrail(mspec.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Incoming Package for {0} from {1} approved",
                                                                                                                                      gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(), gvCBC.Rows[0].Cells[3].Text.Split('-')[0].Trim()));
                    Subject = string.Format("Incoming Package for {0}  from {1} has been approved", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(),
                                            gvCBC.Rows[0].Cells[3].Text.Split('-')[0].Trim());
                    Common.SendEmailToRole("Reviewer", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(), Subject, FDRPage.Statuses.Approved, senderEmail);
                }
                btnApprove.Enabled = false;
                btnReject.Enabled  = false;
                MessageBox.Show(message);
                //LoadCBCHsitory(countryCode, reportingPeriod);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
Ejemplo n.º 7
0
    public void SendEmail(string messageBody, string subject, string emailAddress, byte[] attachement, string fileName, string taxrefNo, int year)
    {
        if (!Configurations.SendToEmails)
        {
            return;
        }
        var correspondance = new CorrespondenceManagementRequestStructure
        {
            RequestOperation = RequestOperation.ISSUE_CORRESPONDENCE,
            OutChannel       = CorrespondenceManagementRequestStructureOutChannel.EMAIL,
            Email            = new CorrespondenceManagementRequestStructureEmail
            {
                ToAddresses = new[] { emailAddress },
                Body        = messageBody,
                Subject     = subject,
                Attachments = attachement == null?null: new CorrespondenceManagementRequestStructureEmailAttachment[1]
                {
                    new CorrespondenceManagementRequestStructureEmailAttachment
                    {
                        Content  = attachement,//FdrCommon.GetRejectionLetter("1"),
                        Type     = DocumentType.PDF,
                        Filename = string.Format("{0}.pdf", fileName)
                    }
                }
            }
        };
        var messageId   = Guid.NewGuid();
        var message     = Sars.Systems.Serialization.XmlObjectSerializer.GetXmlWithNoDeclaration(correspondance);
        var soapMessage = FdrCommon.CreateSoapEmail(message, emailAddress, messageId.ToString());

        soapMessage = FdrCommon.FormatXml(soapMessage);
        var queueInfo = new QueueInfo
        {
            Manager        = MQConfigurationSettings.CorrespondenceOutQManagerName,
            Channel        = MQConfigurationSettings.CorrespondenceOutQChannelName,
            UseManagerName = false,
            Port           = MQConfigurationSettings.CorrespondenceOutPortNumber,
            HostName       = MQConfigurationSettings.CorrespondenceOutHostName,
            QueueName      = MQConfigurationSettings.CorrespondenceOutQName,
            CorrelationId  = messageId.ToString(),
            Message        = soapMessage
        };

        FdrMessaging.SendMessageToQueue(queueInfo);
        DBWriteManager.SaveCorrespondanceTrail(messageId.ToString(), taxrefNo, year, soapMessage);
    }
Ejemplo n.º 8
0
    protected void gvMNE_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        var command = e.CommandName;
        var id      = e.CommandArgument;

        if (command.Equals("Modify", StringComparison.InvariantCultureIgnoreCase))
        {
            Response.Redirect(string.Format("modifymnedetails.aspx?Id={0}", id));
        }

        if (command.Equals("Remove", StringComparison.InvariantCultureIgnoreCase))
        {
            var sid = Sars.Systems.Security.ADUser.CurrentSID;
            DBWriteManager.DeleteMultinational(Convert.ToDecimal(id), sid);
            MessageBox.Show("Record Deleted successfully");
            LoadMNEList();
        }
    }
Ejemplo n.º 9
0
    public void SendSms(string cellNo, string taxrefNo, string message, int year)
    {
        if (!Configurations.SendToSms)
        {
            return;
        }
        if (Convert.ToInt64(cellNo) == 0)
        {
            //MessageBox.Show(string.Format("SMS will not be sent to this number {0}", cellNo));
            return;
        }
        var correspondance = new CorrespondenceManagementRequestStructure
        {
            RequestOperation = RequestOperation.ISSUE_CORRESPONDENCE,
            OutChannel       = CorrespondenceManagementRequestStructureOutChannel.SMS,
            SMS = new CorrespondenceManagementRequestStructureSMS
            {
                CellularNos = new[] { cellNo },
                Message     = message
            }
        };

        var messageId   = Guid.NewGuid();
        var corXml      = XmlObjectSerializer.GetXmlWithNoDeclaration(correspondance);
        var soapMessage = FdrCommon.CreateSoapSms(corXml, taxrefNo, messageId.ToString());

        soapMessage = FdrCommon.FormatXml(soapMessage);
        var queueInfo = new QueueInfo
        {
            Manager        = MQConfigurationSettings.CorrespondenceOutQManagerName,
            Channel        = MQConfigurationSettings.CorrespondenceOutQChannelName,
            UseManagerName = false,
            Port           = MQConfigurationSettings.CorrespondenceOutPortNumber,
            HostName       = MQConfigurationSettings.CorrespondenceOutHostName,
            QueueName      = MQConfigurationSettings.CorrespondenceOutQName,
            CorrelationId  = messageId.ToString(),
            Message        = soapMessage
        };

        FdrMessaging.SendMessageToQueue(queueInfo);
        DBWriteManager.SaveCorrespondanceTrail(messageId.ToString(), taxrefNo, year, soapMessage);
    }
Ejemplo n.º 10
0
    protected void btnVoid_Click(object sender, EventArgs e)
    {
        Guid        newUid  = new Guid();
        Button      btnVoid = (Button)sender;
        GridViewRow gvRow   = (GridViewRow)btnVoid.Parent.Parent;
        var         email   = ADUser.CurrentUser.Mail;

        string[] senderEmail = { email };
        var      countryCode = gvRow.Cells[0].Text.Split('-')[1].Trim();
        var      reportingPeriod = gvRow.Cells[1].Text; var outCBC = DBReadManager.OutGoingCBCDeclarationsDetails(countryCode, reportingPeriod);
        var      id = string.IsNullOrEmpty(outCBC.Id.ToString()) ? 0 : outCBC.Id;
        var      reportP = DateTime.Parse(reportingPeriod).ToString("yyyy-MM-ddTHH:mm:ss");
        Guid     uid     = new Guid();

        if (outCBC != null)
        {
            var prepareVoidPackage = PrepareNMVoidPackage(id, countryCode, outCBC.NMCBC, reportingPeriod);
            var nmPackage          = prepareVoidPackage;
            uid = outCBC.UID;
            var voidedCBC = new OutGoingCBCDeclarations()
            {
                Id              = id,
                Country         = countryCode,
                CBCData         = prepareVoidPackage,
                StatusId        = 8,
                Year            = int.Parse(reportingPeriod.Substring(0, 4)),
                UID             = uid,
                ActionId        = 3,
                NSCBCData       = nmPackage,
                ReportingPeriod = DateTime.Parse(reportP),
                CreatedBy       = Sars.Systems.Security.ADUser.CurrentSID
            };
            decimal saved = DatabaseWriter.SaveOutgoingCBC(voidedCBC, ref uid);
            DBWriteManager.ApproveOutgoingPackage(id, countryCode, reportingPeriod, 8, ADUser.CurrentSID);
            DBWriteManager.Insert_OutgoingPackageAuditTrail(outCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} Pending Void Review", gvRow.Cells[0].Text.Split('-')[0].Trim()));
            var Subject = "Outgoing Package pending void review ";
            Common.SendEmailToRole("Reviewer", outCBC.CountryName, Subject, FDRPage.Statuses.Voided, senderEmail);
            MessageBox.Show("Package pending void review");
            LoadCBC();
        }
    }
Ejemplo n.º 11
0
    protected void btnAllocate_Click(object sender, EventArgs e)
    {
        if (ddlRoles.SelectedIndex == 0)
        {
            MessageBox.Show("Please select user");
            return;
        }
        var submissionId = Request["submissionId"];
        var sid          = ddlRoles.SelectedValue;
        int allocationId = DBWriteManager.AllocateCase(submissionId);

        if (allocationId > 0)
        {
            DBWriteManager.SaveAllocationDetails(allocationId, submissionId, sid);
            MessageBox.Show("Case allocated successfully");
        }
        else
        {
            MessageBox.Show("Could not allocate case");
        }
    }
Ejemplo n.º 12
0
    protected void btnCorrect_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["ccode"] != null && Request.QueryString["period"] != null)
        {
            FDRPage  fPage           = new FDRPage();
            Guid     newUid          = new Guid();
            var      country         = Request.QueryString["ccode"].ToString();
            var      reportingPeriod = Request.QueryString["period"].ToString();
            var      outCBC          = DBReadManager.OutGoingCBCDeclarationsDetails(country, reportingPeriod);
            decimal  id          = string.IsNullOrEmpty(outCBC.Id.ToString()) ? 0 : outCBC.Id;
            var      package     = Common.GenerateCorrectionPackage(country, reportingPeriod);
            var      email       = ADUser.CurrentUser.Mail;
            string[] senderEmail = { email };
            if (!string.IsNullOrEmpty(package.ToString()))
            {
                var outgoingCBC = new OutGoingCBCDeclarations()
                {
                    Id        = id,
                    Country   = country,
                    CBCData   = package.ToString(),
                    StatusId  = 7,
                    Year      = int.Parse(reportingPeriod.Substring(0, 4)),
                    CreatedBy = Sars.Systems.Security.ADUser.CurrentSID
                };
                decimal saved = DatabaseWriter.SaveOutgoingCBC(outgoingCBC, ref newUid);
                DBWriteManager.ApproveOutgoingPackage(id, country, reportingPeriod, 7, ADUser.CurrentSID);
                DBWriteManager.Insert_OutgoingPackageAuditTrail(outCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} corrected", gvCBC.Rows[0].Cells[0].Text.Split('-')[0].Trim()));

                var Subject = "Outgoing CBC Report has been corrected ";
                Common.SendEmailToRole("Reviewer", outCBC.CountryName, Subject, FDRPage.Statuses.Corrected, senderEmail);
                LoadCBC(country, reportingPeriod);
                MessageBox.Show("Package has been corrected successfully");
            }
            else
            {
                MessageBox.Show("No package was corrected");
            }
        }
    }
Ejemplo n.º 13
0
    public void SendLetter(decimal submissionId, string taxrefNo, int year, string letterContent, string letterHead, bool isAcceptance, string userSid)
    {
        if (!Configurations.SendToEfiling)
        {
            return;
        }
        var currentUser = Sars.Systems.Security.ADUser.CurrentUser;

        if (currentUser == null)
        {
            return;
        }
        var correspondance = new CorrespondenceManagementRequestStructure {
            OutChannel       = CorrespondenceManagementRequestStructureOutChannel.EFL,
            RequestOperation = RequestOperation.ISSUE_CORRESPONDENCE,
            TaxRef           = new TaxRefStructure {
                TaxRefNo  = taxrefNo,
                TypeOfTax = TypeOfTaxType.INCOME_TAX
            },
            TaxYear = year.ToString()
        };
        RegistrationQueryDetails registration = null;

        try{
            registration = new RegistrationQueryDetails();
            registration.LookUpRegistrationDetails(taxrefNo);
            if (!registration.DetailsFound)
            {
                MessageBox.Show(registration.Message);
                return;
            }
        }
        catch (Exception) {
        }
        if (registration == null)
        {
            return;
        }

        if (!registration.DetailsFound)
        {
            MessageBox.Show(string.Format("Letter could not be sent because FDR could not get registration details for the number {0} \n U3TM reason : {1}", taxrefNo, registration.Message));
            return;
        }
        if (registration.PreferredAddress == null)
        {
            MessageBox.Show("Letter could not be sent because FDR could not get registration address.");
            return;
        }
        var sarsSysgenltr = new SARS_SYSGENLTR {
            ADDRESSEE_DETAILS = new SARS_SYSGENLTRADDRESSEE_DETAILS {
                //ADDRESS_FIELD_F001 = "What is Here",
                //ADDRESS_FIELD_F002 = "Pretoria",
                //ADDRESS_FIELD_F003 = "299 Bronkhorst street",
                //ADDRESS_FIELD_F004 = "QA TESTING",
                //ADDRESS_FIELD_F005 = "Brooklyn",
                //ADDRESS_FIELD_F006 = "2000",
                //ADDRESS_FIELD_F007 = ""

                ADDRESS_FIELD_F001 = registration.RegistrationName,
                ADDRESS_FIELD_F002 = "",
                ADDRESS_FIELD_F003 = string.Format("{0} {1}", registration.PreferredAddress.StreetNo, registration.PreferredAddress.StreetName),
                ADDRESS_FIELD_F004 = registration.PreferredAddress.Suburb,
                ADDRESS_FIELD_F005 = registration.PreferredAddress.City,
                ADDRESS_FIELD_F006 = registration.PreferredAddress.PostalCode,
                ADDRESS_FIELD_F007 = ""
            },
            FORM_INFORMATION = new FORM_INFORMATION {
                FORM_ID = "CBC_LET_GEN",
                GUID    = new GlobalUniqueIDStructure {
                    UniqueIdentifier = Guid.NewGuid().ToString()
                },
                TIMESTAMP   = DateTime.Now,
                TAX_REF_NO  = taxrefNo,
                TAX_YEAR    = year.ToString(),
                LANGUAGE    = "english",
                FORM_TYPE   = isAcceptance ? "CBCACC" : "CBCREJ",
                CASE_NUMBER = string.Empty
            },
            CONTACT_DETAILS = new SARS_SYSGENLTRCONTACT_DETAILS {
                HeaderLabel        = "Contact Detail",
                ADDRESS_CD01       = "SARS Head Office",
                TEL_NO_CD02        = currentUser.Telephone,
                WEB_ADDRESS_CD03   = "SARS online: www.sars.gov.za",
                TOLL_FREE_NO_CD04  = "",
                FAX_NO_CD05        = "",
                EMAIL_ADDRESS_CD06 = currentUser.Name
            },
            LETTER_CONTENT = new SARS_SYSGENLTRLETTER_CONTENT {
                CONTENT = letterContent.Replace(Environment.NewLine, "")
            },
            DETAILS = new SARS_SYSGENLTRDETAILS {
                TAXREF_NO = new SARS_SYSGENLTRDETAILSTAXREF_NO {
                    TAXREF_FIELD_F004 = taxrefNo,
                    TAXREF_LABEL_L003 = "Tax Reference No.:"
                },
                DATE = new SARS_SYSGENLTRDETAILSDATE {
                    DATE_LABEL_L008 = "Date:",
                    DATE_FIELD_F009 = DateTime.Now.ToString("yyyy-MM-dd")
                },
                ENQUIRY_NOTE = new SARS_SYSGENLTRDETAILSENQUIRY_NOTE {
                    NOTE_LABEL_L005 = "Always quote this reference number when contacting SARS"
                }
            },
            LETTER_HEADER = new SARS_SYSGENLTRLETTER_HEADER
            {
                LETTER_HEADER_LABEL = letterHead
            },
            LETTER_NAME_HEADER = new SARS_SYSGENLTRLETTER_NAME_HEADER {
                LETTER_NAME = string.Empty //letterHead.ToUpper()
            }
            //,
            //Paragraphs = new string[2]
            //{
            //    "Paragraph 1",
            //    "Paragraph 2"
            //},
        };

        var letterDetails = Sars.Systems.Serialization.XmlObjectSerializer.GetXmlWithNoDeclaration(sarsSysgenltr, "SARS", "http://www.sars.gov.za/forms/").Replace(Environment.NewLine, "");
        var letters       = new List <CorrespondenceManagementRequestStructureLetter> {
            new CorrespondenceManagementRequestStructureLetter {
                Content         = string.Format("<![CDATA[{0}]]>", letterDetails),
                TemplateDetails = new TemplateDetailsStructure {
                    Language = LanguageType.ENGLISH,
                    Name     = "SARS_SysGenOutLet_RO_E_v2012.01.05"
                },
                Type = isAcceptance ? "CBCACC" : "CBCREJ"
            }
        };

        correspondance.Letters = letters.ToArray();
        var messageId   = Guid.NewGuid();
        var corXml      = XmlObjectSerializer.GetXmlWithNoDeclaration(correspondance);
        var soapMessage = FdrCommon.CreateSoapLetter(corXml, taxrefNo, messageId.ToString());

        soapMessage = FdrCommon.FormatXml(soapMessage).Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;lt;", "<").Replace("&amp;gt;", ">");
        var queueInfo = new QueueInfo {
            Manager        = MQConfigurationSettings.CorrespondenceOutQManagerName,
            Channel        = MQConfigurationSettings.CorrespondenceOutQChannelName,
            UseManagerName = false,
            Port           = MQConfigurationSettings.CorrespondenceOutPortNumber,
            HostName       = MQConfigurationSettings.CorrespondenceOutHostName,
            QueueName      = MQConfigurationSettings.CorrespondenceOutQName,
            CorrelationId  = messageId.ToString(),
            Message        = soapMessage
        };

        FdrMessaging.SendMessageToQueue(queueInfo);
        DBWriteManager.SaveLetter(submissionId, soapMessage, taxrefNo, year, userSid);
        DBWriteManager.SaveCorrespondanceTrail(messageId.ToString(), taxrefNo, year);
    }
Ejemplo n.º 14
0
    protected void btnAddComments_Click(object sender, EventArgs e)
    {
        var hiddenValue = Parent.FindControl("hdnDone") as HiddenField;
        var mpeMe       = Parent.FindControl("ModalPopupExtender1") as AjaxControlToolkit.ModalPopupExtender;

        hiddenValue.Value = txtComments.Text;
        var gvCBC = Parent.FindControl("gvCBC") as GridView;

        if (!string.IsNullOrEmpty(txtComments.Text))
        {
            var      email       = ADUser.CurrentUser.Mail;
            string[] senderEmail = { email };
            string   Subject     = "";
            if (Request.QueryString["idx"] == null)
            {
                return;
            }

            if (Request.QueryString["idx"] == "0")
            {
                var countryCode = Request.QueryString["xCountry"].ToString();

                if (gvCBC != null)
                {
                    string ReportingPeriod = gvCBC.Rows[0].Cells[4].Text;
                    var    outCBC          = DBReadManager.OutGoingCBCDeclarationsDetails(countryCode, ReportingPeriod);
                    var    comments        = new Comments()
                    {
                        OutGoingCBCDeclarationsID = outCBC.Id,
                        Notes   = txtComments.Text,
                        AddedBy = ADUser.CurrentSID
                    };
                    if (SaveComments(comments, 2) > 0)
                    {
                        DBWriteManager.ApproveOutgoingPackage(outCBC.Id, countryCode, ReportingPeriod, 4, ADUser.CurrentSID);
                        Subject = "Outgoing CBC Package has been rejected";
                        FDR.DataLayer.DBWriteManager.Insert_OutgoingPackageAuditTrail(outCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} has been rejected", outCBC.CountryName));
                        Common.SendEmailToRole("Reviewer", outCBC.CountryName, Subject, FDRPage.Statuses.Rejected, senderEmail);
                        MessageBox.Show(string.Format("Outgoing Package for {0} has been successfully rejected", outCBC.CountryName));
                    }
                }
            }
            else
            {
                if (Request.QueryString["idx"] != null)
                {
                    string  ReportingPeriod = gvCBC.Rows[0].Cells[6].Text;
                    decimal msgSpecId       = decimal.Parse(Request.QueryString["idx"].ToString());
                    var     comments        = new Comments()
                    {
                        OutGoingCBCDeclarationsID = msgSpecId,
                        Notes   = txtComments.Text,
                        AddedBy = ADUser.CurrentSID
                    };
                    if (SaveComments(comments, 1) > 0)
                    {
                        DBWriteManager.ApproveForeignPackage(4, msgSpecId, ADUser.CurrentSID);
                        var mspec = DBReadManager.GetMessageSpecById(msgSpecId);
                        DBWriteManager.Insert_OutgoingPackageAuditTrail(mspec.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Incoming Package for {0} from {1} rejected",
                                                                                                                                          gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(), gvCBC.Rows[0].Cells[3].Text.Split('-')[0].Trim()));
                        Subject = string.Format("Incoming Package for {0} has been rejected", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim());
                        Common.SendEmailToRole("Reviewer", gvCBC.Rows[0].Cells[4].Text.Split('-')[0].Trim(), Subject, FDRPage.Statuses.Approved, senderEmail);
                        MessageBox.Show(string.Format("Incoming Foreign Package for {0} has been rejected successfully", gvCBC.Rows[0].Cells[3].Text.Split('-')[0]));
                    }
                }
            }
            txtComments.Text = "";
            var btnApprove = Parent.FindControl("btnApprove") as Button;
            var btnReject  = Parent.FindControl("btnReject") as Button;
            btnReject.Enabled  = false;
            btnApprove.Enabled = false;
        }

        else
        {
            MessageBox.Show("Please Enter comments");
            if (mpeMe != null)
            {
                mpeMe.Show();
            }
        }
    }
Ejemplo n.º 15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var message = File.ReadAllText(@"D:\SARS\INCOMING\USA.xml");

            var applicationInformationStructure = new Sars.ESBSchema.ApplicationInformation.v31.
                                                  ApplicationInformationStructure
            {
                ApplicationInformationResult =
                    new Sars.ESBSchema.ApplicationInformation.v31.
                    ApplicationInformationStructureApplicationInformationResult[1]
            };


            var incomingMessage = new IncomingMessage(HttpContext.Current);
            //var message = incomingMessage.Message;
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            message = message.Replace("ns0:", "esb:");



            var dataset = new RecordSet();
            dataset.ReadXml(new StringReader(message));

            if (dataset.HasRows)
            {
                if (dataset.Tables.Contains("MessageIdentification") &&
                    dataset.Tables.Contains("CountryByCountryReportManagementRequest"))
                {
                    //var messageIdentification = dataset.Tables["MessageIdentification"];
                    var countryByCountryReportManagementRequest =
                        dataset.Tables["CountryByCountryReportManagementRequest"];

                    //var fileName = countryByCountryReportManagementRequest.Rows[0]["Filename"].ToString();
                    var destination = countryByCountryReportManagementRequest.Rows[0]["Destination"].ToString();
                    //var requestOperation = countryByCountryReportManagementRequest.Rows[0]["RequestOperation"].ToString();
                    var fileContent = countryByCountryReportManagementRequest.Rows[0]["FileContent"].ToString();

                    var fileBuffer = fileContent.Base64StringToByteArray();
                    if (Request.PhysicalApplicationPath != null)
                    {
                        var zipFolder = Path.Combine(Request.PhysicalApplicationPath,
                                                     SARSDataSettings.Settings.TempFolder,
                                                     DateTime.Now.ToFileTime().ToString());
                        if (!Directory.Exists(zipFolder))
                        {
                            Directory.CreateDirectory(zipFolder);
                        }
                        var zipFile = Path.Combine(zipFolder, string.Format("{0}.ZIP", DateTime.Now.ToFileTime()));
                        File.WriteAllBytes(zipFile, fileBuffer);

                        Sars.Systems.Compression.ZipExtraction.ExtractZipFile(zipFile, zipFolder);
                        var files = new DirectoryInfo(zipFolder).GetFiles("*.*").ToList();

                        var payLoadFiles  = files.Where(f => f.Name.Contains("Payload")).ToList();
                        var metaDataFiles = files.Where(f => f.Name.Contains("Metadata")).ToList();
                        if (!payLoadFiles.Any())
                        {
                            return;
                        }
                        if (!metaDataFiles.Any())
                        {
                            return;
                        }
                        var payloadData = File.ReadAllText(payLoadFiles[0].FullName);

                        if (string.IsNullOrEmpty(payloadData))
                        {
                            return;
                        }
                        var doc = new XmlDocument();
                        var originalMessageDocument = new XmlDocument();
                        doc.LoadXml(payloadData);
                        originalMessageDocument.LoadXml(message);

                        var cbCXmlNodeList = doc.GetElementsByTagName("CbCStatusMessage_OECD", "*");
                        var headerNodeList = originalMessageDocument.GetElementsByTagName("Header", "*");
                        var countryByCountryReportManagementRequestNodeList =
                            originalMessageDocument.GetElementsByTagName("CountryByCountryReportManagementRequest", "*");
                        if (cbCXmlNodeList.Count == 0 || headerNodeList.Count == 0 ||
                            countryByCountryReportManagementRequestNodeList.Count == 0)
                        {
                            //Common.LogEvent("XmlNodeList CbCXml = xmlDoc.GetElementsByTagName(\"CBC_OECD\", \" * \"); yielded zero elements");
                            return;
                        }
                        var statusXml = cbCXmlNodeList[0].OuterXml;
                        var headerXml = headerNodeList[0].OuterXml;
                        var countryByCountryReportManagementRequestXml = countryByCountryReportManagementRequestNodeList[0].OuterXml;


                        var schenaVal = _client.ValidateSchema(Configurations.CbCStatusValidationServiceID, statusXml);
                        if (!schenaVal.IsValid)
                        {
                            applicationInformationStructure.ApplicationInformationResult[0] =
                                new
                                ApplicationInformationStructureApplicationInformationResult
                            {
                                Code        = "9999",
                                Description = schenaVal.ErrorXml,
                                MessageType = MessageTypeEnum.ERROR
                            };
                            var messageToSend = CreateXml(headerXml, applicationInformationStructure, countryByCountryReportManagementRequestXml);
                            SendMessage(messageToSend, incomingMessage, _client);
                            return;
                        }

                        if (!destination.Equals("ZA", StringComparison.CurrentCultureIgnoreCase))
                        {
                            var code          = "9999";
                            var returnMessage = "MESSAGE DESTINATION NOT ZA";
                            RespondToB2Bi(
                                applicationInformationStructure
                                , code
                                , returnMessage
                                , true
                                , headerXml
                                , countryByCountryReportManagementRequestXml
                                , incomingMessage);
                            return;
                        }
                        if (string.IsNullOrEmpty(fileContent))
                        {
                            var code          = "9999";
                            var returnMessage = "FILE CONTENT EMPTY";
                            RespondToB2Bi(
                                applicationInformationStructure
                                , code
                                , returnMessage
                                , true
                                , headerXml
                                , countryByCountryReportManagementRequestXml
                                , incomingMessage);
                            return;
                        }

                        var statusMessage =
                            Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <CbCStatusMessage_OECD>(
                                statusXml);
                        if (statusMessage == null)
                        {
                            var code          = "9999";
                            var returnMessage = "XML COULD NOT BE DESERIALISED";
                            RespondToB2Bi(
                                applicationInformationStructure
                                , code
                                , returnMessage
                                , true
                                , headerXml
                                , countryByCountryReportManagementRequestXml
                                , incomingMessage);
                            return;
                        }

                        try
                        {
                            SaveMessageToDisc(statusMessage, message);
                        }
                        catch (Exception ex)
                        {
                            LogError(ex);
                        }
                        var originalMessageRefId = statusMessage.CbCStatusMessage.OriginalMessage.OriginalMessageRefID;
                        if (!string.IsNullOrEmpty(originalMessageRefId))
                        {
                            var indexOfDesh = originalMessageRefId.IndexOf("-", StringComparison.Ordinal);
                            if (indexOfDesh == -1)
                            {
                                var code          = "9999";
                                var returnMessage = "MessageRefId not correct";
                                RespondToB2Bi(
                                    applicationInformationStructure
                                    , code
                                    , returnMessage
                                    , true
                                    , headerXml
                                    , countryByCountryReportManagementRequestXml
                                    , incomingMessage);
                                return;
                            }
                            var origionalUid = originalMessageRefId.Substring(indexOfDesh + 3, 36);

                            Guid uidGuid;
                            if (!Guid.TryParse(origionalUid, out uidGuid))
                            {
                                var code          = "9999";
                                var returnMessage = "originalMessageRefId is not correct";
                                RespondToB2Bi(
                                    applicationInformationStructure
                                    , code
                                    , returnMessage
                                    , true
                                    , headerXml
                                    , countryByCountryReportManagementRequestXml
                                    , incomingMessage);
                                return;
                            }
                            //uidGuid = Guid.Parse("EF663F3E-E9DF-4FE3-8EAD-8BECCECF42AC");

                            DBWriteManager.Insert_OutgoingPackageAuditTrail
                            (
                                uidGuid,
                                null,
                                string.Format("Status Message received from {0} - {1}",
                                              statusMessage.MessageSpec.TransmittingCountry,
                                              statusMessage.MessageSpec.MessageRefId)
                            );

                            DBWriteManager.Insert_OutgoingPackageAuditTrail
                            (
                                uidGuid,
                                null,
                                "Incoming status update validation successful."
                            );
                            DBWriteManager.UpdatePackageWithStatusFromeOtherCountries
                            (
                                uidGuid
                                , statusXml
                                , statusMessage.CbCStatusMessage.ValidationResult.Status.ToString()
                            );

                            var validationErrors = statusMessage.CbCStatusMessage.ValidationErrors;
                            if (validationErrors.FileError != null && validationErrors.FileError.Any())
                            {
                                var numErrors = 0;
                                foreach (var fileErrorType in validationErrors.FileError)
                                {
                                    var code             = fileErrorType.Code;
                                    var errorDescription = fileErrorType.Details.Value;
                                    numErrors += DBWriteManager.Insert_OutgoingPackage_File_ReturnErrors(
                                        uidGuid,
                                        code,
                                        errorDescription
                                        );
                                }
                                DBWriteManager.Insert_OutgoingPackageAuditTrail
                                (
                                    uidGuid,
                                    null,
                                    string.Format("{0} File Validation Error(s) Found", numErrors)
                                );
                            }
                            DBWriteManager.Insert_OutgoingPackageAuditTrail
                            (
                                uidGuid,
                                null,
                                string.Format("File Status is : {0}", statusMessage.CbCStatusMessage.ValidationResult.Status)
                            );
                            if (validationErrors.RecordError != null && validationErrors.RecordError.Any())
                            {
                                var numErrors = 0;
                                foreach (var recordError in validationErrors.RecordError)
                                {
                                    var code             = recordError.Code;
                                    var errorDescription = recordError.Details.Value;
                                    var docRef           = string.Join(" | ", recordError.DocRefIDInError);
                                    numErrors += DBWriteManager.Insert_OutgoingPackage_Record_ReturnErrors(
                                        uidGuid,
                                        code,
                                        errorDescription,
                                        docRef
                                        );
                                }
                                DBWriteManager.Insert_OutgoingPackageAuditTrail
                                (
                                    uidGuid,
                                    null,
                                    string.Format("{0} Record Validation Error(s) Found", numErrors)
                                );
                            }
                            applicationInformationStructure.ApplicationInformationResult[0] = new ApplicationInformationStructureApplicationInformationResult
                            {
                                Code        = "0000",
                                Description = "Successful",
                                MessageType = MessageTypeEnum.INFORMATION
                            };
                            var successMessageToSend = CreateXml(headerXml, applicationInformationStructure,
                                                                 countryByCountryReportManagementRequestXml);
                            SendMessage(successMessageToSend, incomingMessage, _client);
                        }
                        Directory.Delete(zipFolder, true);
                    }
                }
            }
        }
        catch (Exception exception)
        {
            LogError(exception);
        }
        finally
        {
            _client.Close();
        }
    }
Ejemplo n.º 16
0
        void GetResponse()
        {
            MQQueue queue;

            try
            {
                // mq properties
                properties = new Hashtable();
                properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
                properties.Add(MQC.HOST_NAME_PROPERTY, hostName);
                properties.Add(MQC.PORT_PROPERTY, port);
                properties.Add(MQC.CHANNEL_PROPERTY, channelName);

                // create connection
                queueManager = new MQQueueManager(queueManagerName, properties);

                // accessing queue
                queue = queueManager.AccessQueue(queueNameRes, MQC.MQOO_BROWSE + MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);

                // creating a message object
                message = new MQMessage();
                MQGetMessageOptions mqGetMsgOpts = new MQGetMessageOptions();
                mqGetMsgOpts.Options = MQC.MQGMO_BROWSE_FIRST;

                try
                {
                    queue.Get(message, mqGetMsgOpts);
                    MQGetMessageOptions mqGetNextMsgOpts = new MQGetMessageOptions();
                    mqGetNextMsgOpts.Options = MQC.MQGMO_BROWSE_NEXT;

                    while (true)
                    {
                        try
                        {
                            string messageText = message.ReadString(message.MessageLength);

                            byte[] byteConent = new byte[message.MessageLength];
                            message.ReadFully(ref byteConent, 0, message.MessageLength);

                            string str = Encoding.Default.GetString(byteConent);

                            var doc = new XmlDocument();
                            doc.LoadXml(str);

                            var ns = new XmlNamespaceManager(doc.NameTable);
                            ns.AddNamespace("esb", "http://www.egovernment.gov.za/GMD/MessageIdentification/xml/schemas/version/7.1");
                            ns.AddNamespace("cbcMgt", "http://www.sars.gov.za/enterpriseMessagingModel/CountryByCountryReportManagement/xml/schemas/version/1.2");

                            var header  = doc.SelectSingleNode("//esb:MessageIdentification", ns);
                            var request = doc.SelectSingleNode("//cbcMgt:CountryByCountryReportManagementRequest", ns);

                            if (header != null && request != null)
                            {
                                /*//Validate header xml
                                 * XmlReaderSettings settingsHeader = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.ESBHeaderV7.1.xsd"));
                                 * var readerHeader = XmlReader.Create(header.OuterXml, settingsHeader);
                                 * while (readerHeader.Read());
                                 * readerHeader.Close();
                                 *
                                 * //Validate Body xml
                                 * XmlReaderSettings settingsRequest = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.SARSCountryByCountryReportManagementV1.2.xsd"));
                                 * var readerRequest = XmlReader.Create(request.OuterXml, settingsRequest);
                                 * while (readerRequest.Read());
                                 * readerRequest.Close();*/

                                //Parse XML to objects
                                var headerReq = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <MessageIdentificationStructure>(header.OuterXml);
                                var subReq    = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <CountryByCountryReportManagementRequestStructure>(request.OuterXml);

                                var    fragments = UnzipToString(subReq.FileContent, subReq.Filename); //File.ReadAllText(string.Format("D:\\Sars\\Incoming\\{0}.xml", subReq.Filename.Replace(".zip", "")));
                                string fullxml   = "";

                                foreach (string s in fragments)
                                {
                                    fullxml += s;
                                }

                                var myRootedXml = "<root>" + fullxml + "</root>";

                                XmlDocument xmlDoc = new XmlDocument();
                                xmlDoc.LoadXml(myRootedXml);

                                //Get CBC OECD data
                                XmlNodeList    xmlNodeList = xmlDoc.GetElementsByTagName("CBC_OECD", "*"); // xmlDoc.GetElementsByTagName("cbc:CBC_OECD");
                                List <XmlNode> nodees      = new List <XmlNode>(xmlNodeList.Cast <XmlNode>());

                                string cbcXML = nodees[0].OuterXml;

                                //Validate CBC OECD xml
                                XmlReaderSettings settingsOECD = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.CbcXML_v1.0.1.xsd"));
                                var readerOECD = XmlReader.Create(cbcXML, settingsOECD);
                                while (readerOECD.Read())
                                {
                                    ;
                                }
                                readerOECD.Close();

                                //Add validation errors
                                statusMessage.CbCStatusMessage.ValidationErrors.FileError = validationErrors.ToArray();

                                bool valErrors    = validationErrors.Count() > 0;
                                var  valErrorList = validationErrors;
                                validationErrors = new List <FileError_Type>();

                                var appResult = new ApplicationInformationStructureApplicationInformationResult
                                {
                                    Code        = valErrors ? "50007" : "0000",
                                    Description = valErrors ? string.Join(",", valErrorList) : "Processed",
                                    MessageType = valErrors ? MessageTypeEnum.ERROR : MessageTypeEnum.INFORMATION
                                };

                                //Get Response XML
                                string responseXML = CreateResponseXml(header.OuterXml, appResult);

                                //Put response XML to Queue
                                PutFile(queueNameReceiveRes, Encoding.ASCII.GetBytes(responseXML));

                                if (valErrors)
                                {
                                    throw new Exception("Validation errors occured: " + string.Join(",", valErrorList));
                                }

                                //Cast cbcXML to object
                                var cbcOECD = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <CBC_OECD>(cbcXML);

                                if (cbcOECD == null)
                                {
                                    throw new Exception("Couldn't cast cbcOECD data to object");
                                }

                                //Create Message Spec
                                statusMessage.MessageSpec = new CbcStatusMessage.MessageSpec_Type()
                                {
                                    SendingCompanyIN          = cbcOECD.MessageSpec.SendingEntityIN,
                                    TransmittingCountry       = (CbcStatusMessage.CountryCode_Type)Enum.Parse(typeof(CbcStatusMessage.CountryCode_Type), cbcOECD.MessageSpec.TransmittingCountry.ToString()),
                                    ReceivingCountry          = (CbcStatusMessage.CountryCode_Type)Enum.Parse(typeof(CbcStatusMessage.CountryCode_Type), cbcOECD.MessageSpec.ReceivingCountry.ToString()),
                                    MessageType               = CbcStatusMessage.MessageType_EnumType.CbCMessageStatus,
                                    Warning                   = "",
                                    MessageRefId              = cbcOECD.MessageSpec.MessageRefId,
                                    MessageTypeIndic          = CbCMessageTypeIndic_EnumType.CbCMessageStatus,
                                    MessageTypeIndicSpecified = true,
                                    ReportingPeriod           = cbcOECD.MessageSpec.ReportingPeriod,
                                    Timestamp                 = DateTime.Now
                                };

                                //Add original message information
                                statusMessage.CbCStatusMessage.OriginalMessage.OriginalMessageRefID                      = cbcOECD.MessageSpec.MessageRefId;
                                statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSSendingTimeStamp          = DateTime.Now;
                                statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSSendingTimeStampSpecified = true;
                                statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.UncompressedFileSizeKBQty    = "0";
                                statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSTransmissionID            = "";

                                var recordErrors = new List <RecordError_Type>();

                                foreach (var item in cbcOECD.CbcBody)
                                {
                                    foreach (var bodyItem in item.CbcReports)
                                    {
                                        var docRefId = bodyItem.DocSpec.DocRefId;

                                        //Check if docRefId exists if exists add to record error
                                        //recordErrors.Add(new RecordError_Type() { Code = "80000", Details = new ErrorDetail_Type() { Value = "DocRefID already used" }, DocRefIDInError = new[] { docRefId } });

                                        //Check format of docrefid if not correct add to record error
                                        //recordErrors.Add(new RecordError_Type() { Code = "80001", Details = new ErrorDetail_Type() { Value = "DocRefID format" }, DocRefIDInError = new[] { docRefId } });

                                        var corrDocRefID = bodyItem.DocSpec.CorrDocRefId;

                                        //Check if docRefid exist if NOT exist add to record error
                                        //recordErrors.Add(new RecordError_Type() { Code = "80002", Details = new ErrorDetail_Type() { Value = "CorrDocRefId unknown" }, DocRefIDInError = new[] { docRefId } });
                                    }
                                }

                                //Add record errors
                                statusMessage.CbCStatusMessage.ValidationErrors.RecordError = recordErrors.ToArray();

                                //Get File Metadata
                                xmlNodeList = xmlDoc.GetElementsByTagName("CTSSenderFileMetadata");
                                nodees      = new List <XmlNode>(xmlNodeList.Cast <XmlNode>());

                                //Get File metadata xml
                                string sender = nodees[0].OuterXml;

                                //Deserialize File Metadata to object
                                XmlSerializer             CTSSenderFileMetadata = new XmlSerializer(typeof(CTSSenderFileMetadataType));
                                CTSSenderFileMetadataType senderReq;

                                using (TextReader sr = new StringReader(sender))
                                {
                                    senderReq = (CTSSenderFileMetadataType)CTSSenderFileMetadata.Deserialize(sr);
                                }

                                //Save CBC OECD Data to DB
                                var cbcr = DBWriteManager.SaveIncomingCBCDeclaration(0, senderReq.CTSSenderCountryCd.ToString(), int.Parse(senderReq.TaxYear), cbcXML);

                                statusMessage.CbCStatusMessage.ValidationResult.Status = FileAcceptanceStatus_EnumType.Accepted;

                                XmlSerializer xsSubmit = new XmlSerializer(typeof(CbCStatusMessage_OECD));

                                var xml = "";

                                using (var sww = new StringWriter())
                                {
                                    using (XmlWriter writer = XmlWriter.Create(sww))
                                    {
                                        xsSubmit.Serialize(writer, statusMessage);
                                        xml = sww.ToString();
                                    }
                                }

                                PutFile(queueNameStatusMessage, Encoding.Default.GetBytes(xml));

                                eventLog1.WriteEntry("got incoming file: " + headerReq.universalUniqueID);

                                //Remove message from the Queue
                                mqGetMsgOpts.Options = MQC.MQGMO_MSG_UNDER_CURSOR;
                                queue.Get(message, mqGetMsgOpts);
                            }
                            else
                            {
                                if (header == null)
                                {
                                    eventLog1.WriteEntry("Error (Incoming File): No header message found", EventLogEntryType.Error);
                                }

                                if (request == null)
                                {
                                    eventLog1.WriteEntry("Error (Incoming File): No request message found", EventLogEntryType.Error);
                                }

                                //Application Results failed schema validation
                                var appResult = new ApplicationInformationStructureApplicationInformationResult
                                {
                                    Code        = "50007",
                                    Description = "Failed Schema Validation",
                                    MessageType = MessageTypeEnum.ERROR
                                };

                                //Get Response XML
                                string responseXML = CreateResponseXml(header.OuterXml, appResult);

                                //Put response XML to Queue
                                PutFile(queueNameReceiveRes, Encoding.ASCII.GetBytes(responseXML));
                            }

                            //Get next Message
                            message = new MQMessage();
                            queue.Get(message, mqGetNextMsgOpts);
                        }
                        catch (MQException mqe)
                        {
                            if (mqe.ReasonCode == 2033)
                            {
                                //eventLog1.WriteEntry("No message available");
                                break;
                            }
                            else
                            {
                                eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            eventLog1.WriteEntry(string.Format("Exception caught (Incoming file): {0}", ex.Message), EventLogEntryType.Error);
                            message = new MQMessage();
                            queue.Get(message, mqGetNextMsgOpts);
                        }
                    }
                }
                catch (MQException mqe)
                {
                    if (mqe.ReasonCode == 2033)
                    {
                        //No message available do nothing
                        //eventLog1.WriteEntry("No message available");
                    }
                    else
                    {
                        eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error);
                    }
                }

                // closing queue
                queue.Close();

                // disconnecting queue manager
                queueManager.Disconnect();
            }
            catch (MQException mqe)
            {
                eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error);
                eventLog1.WriteEntry(mqe.StackTrace, EventLogEntryType.Error);
            }
        }
Ejemplo n.º 17
0
    protected void btnApprove_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        var countryCode = Request.QueryString["xCountry"].ToString();
        var period      = Request.QueryString["Period"].ToString();

        if (string.IsNullOrEmpty(countryCode) && string.IsNullOrEmpty(period))
        {
            return;
        }
        if (fp.IsUserInRole("Reviewer") || fp.IsUserInRole("Approver"))
        {
            try
            {
                string reportingPeriod = period;
                var    outCBC          = DBReadManager.OutGoingCBCDeclarationsDetails(countryCode, reportingPeriod);
                int    statusId        = fp.IsUserInRole("Reviewer") ? 3 : 5;

                string Subject = "";
                var    email   = string.IsNullOrEmpty(ADUser.CurrentUser.Mail) ? "*****@*****.**" : ADUser.CurrentUser.Mail;
                // DBWriteManager.ApproveOutgoingPackage(outCBC.Id, countryCode, reportingPeriod, statusId, ADUser.CurrentSID);
                string[] senderEmail = { email };
                if (fp.IsUserInRole("Reviewer"))
                {
                    try
                    {
                        DBWriteManager.Insert_OutgoingPackageAuditTrail(outCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} verified", outCBC.CountryName));
                        Subject = string.Format("Outgoing Package for {0} has been verified ", outCBC.CountryName);
                        Common.SendEmailToRole("Approver", outCBC.CountryName, Subject, FDRPage.Statuses.Verified, senderEmail);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    try
                    {
                        DBWriteManager.Insert_OutgoingPackageAuditTrail(outCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} approved", outCBC.CountryName));
                        Subject = string.Format("Outgoing Package for {0} has been approved", outCBC.CountryName);
                        Common.SendEmailToRole("Reviewer", outCBC.CountryName, Subject, FDRPage.Statuses.Approved, senderEmail);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                LoadCBCHsitory(countryCode, reportingPeriod);
                MessageBox.Show(Subject + " successfully");
                if (fp.IsUserInRole("Reviewer"))
                {
                    if (statusId > 2)
                    {
                        btnApprove.Enabled = false;
                    }
                }
                else
                {
                    if (statusId > 3)
                    {
                        btnApprove.Enabled = false;
                        btnReject.Enabled  = true;
                    }
                }
                btnApprove.Enabled = false;
                btnReject.Enabled  = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
Ejemplo n.º 18
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int j = 0, k = 0;
        var listOfFiles = new List <FileValidationOutcomeDetails>();

        foreach (GridViewRow row in gvMasterFiles.Rows)
        {
            var ddlOutcome       = row.FindControl("ddlOutcome") as DropDownList;
            var txtOutcomeReason = row.FindControl("txtOutcomeReason") as TextBox;
            if (ddlOutcome != null && txtOutcomeReason != null)
            {
                ddlOutcome.BackColor = Color.Transparent;
                if (ddlOutcome.SelectedIndex <= 0)
                {
                    ddlOutcome.BackColor = Color.Red;
                    k++;
                    break;
                }
                var dataKey = gvMasterFiles.DataKeys[row.RowIndex];
                if (dataKey != null)
                {
                    var fileId = Convert.ToDecimal(dataKey.Value);
                    listOfFiles.Add(new FileValidationOutcomeDetails {
                        Id                  = 0,
                        SubmissionId        = Convert.ToDecimal(SubmissionId),
                        FileId              = fileId,
                        ValidationOutcomeId = Convert.ToInt32(ddlOutcome.SelectedValue),
                        SID                 = Sars.Systems.Security.ADUser.CurrentSID,
                        OutcomeReason       = string.IsNullOrEmpty(txtOutcomeReason.Text) ? null : txtOutcomeReason.Text
                    }
                                    );
                }
            }
        }

        foreach (GridViewRow row in gvLocalFiles.Rows)
        {
            var ddlOutcome       = row.FindControl("ddlOutcome") as DropDownList;
            var txtOutcomeReason = row.FindControl("txtOutcomeReason") as TextBox;
            if (ddlOutcome != null && txtOutcomeReason != null)
            {
                ddlOutcome.BackColor = Color.Transparent;
                if (ddlOutcome.SelectedIndex <= 0)
                {
                    ddlOutcome.BackColor = Color.Red;
                    j++;
                    break;
                }
                var dataKey = gvLocalFiles.DataKeys[row.RowIndex];
                if (dataKey != null)
                {
                    var fileId = Convert.ToDecimal(dataKey.Value);
                    listOfFiles.Add(
                        new FileValidationOutcomeDetails {
                        Id                  = 0,
                        SubmissionId        = Convert.ToDecimal(SubmissionId),
                        FileId              = fileId,
                        ValidationOutcomeId = Convert.ToInt32(ddlOutcome.SelectedValue),
                        SID                 = Sars.Systems.Security.ADUser.CurrentSID,
                        OutcomeReason       = string.IsNullOrEmpty(txtOutcomeReason.Text) ? null : txtOutcomeReason.Text
                    }
                        );
                }
            }
        }

        if (k > 0)
        {
            tbMain.ActiveTabIndex = 0;
            MessageBox.Show("Please select validation outcome for all the files.");
            return;
        }
        if (j > 0)
        {
            tbMain.ActiveTabIndex = 1;
            MessageBox.Show("Please select validation outcome for all the files.");
            return;
        }
        if (listOfFiles.Any())
        {
            var numSaved = 0;
            foreach (var detailse in listOfFiles)
            {
                numSaved += DBWriteManager.SaveFileValidationOutcome(detailse);
            }
            if (_fileSubmission == null)
            {
                _fileSubmission = DBReadManager.GeFileSubmissionById(Convert.ToDecimal(SubmissionId));
            }
            if (numSaved == (gvLocalFiles.Rows.Count + gvMasterFiles.Rows.Count))
            {
                btnSave.Enabled   = false;
                btnSubmit.Enabled = false;
                MessageBox.Show("Validation submitted successfully");
            }

            var status   = 0;
            var accepted = listOfFiles.Count(a => a.ValidationOutcomeId == 1);
            var rejected = listOfFiles.Count(a => a.ValidationOutcomeId == 2);
            if (accepted == listOfFiles.Count())
            {
                // accepted = 3
                status = 3;
                try{
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactMobileNumber) && _fileSubmission.ContactMobileNumber.IsValid(StringValidationType.CellularNumber))
                    {
                        var smsBody = DBReadManager.GetMasterLocalFileNotificationSmsBodyTemplate(2);
                        if (!string.IsNullOrEmpty(smsBody))
                        {
                            var service = new FDRQueueService();
                            service.SendSms(
                                _fileSubmission.ContactMobileNumber
                                , _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                                );
                            DBWriteManager.SaveSentSmsCommunications(
                                _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                                );
                        }
                    }
                }
                catch (Exception) {
                    ;
                }
                try{
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactEmail))
                    {
                        byte[] attachment  = null;//FdrCommon.GetFileAcceptenceLetter(SubmissionId);
                        var    service     = new FDRQueueService();
                        var    messageBody = string.Format(DBReadManager.GetMasterLocalFileNotificationEmailBodyTemplate(2), _fileSubmission.TaxRefNo);
                        service.SendEmail
                        (
                            messageBody
                            , "CBC File validation outcome"
                            , _fileSubmission.ContactEmail
                            , null
                            , "CBC File validation outcome"
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                        );
                    }
                }
                catch (Exception) {
                    ;
                }

                try{
                    var attachment = FdrCommon.GetEfilingAcceptanceLetter(_fileSubmission.Year);
                    if (!string.IsNullOrEmpty(attachment))
                    {
                        var service = new FDRQueueService();
                        service.SendLetter
                        (
                            _fileSubmission.SubmissionId
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                            , attachment
                            , "Acceptance of Master Files and Local Files"
                            , true
                            , Sars.Systems.Security.ADUser.CurrentSID
                        );
                    }
                }
                catch (Exception)
                {
                    ;
                }
            }
            else if (rejected == listOfFiles.Count())
            {
                //rejected = 4
                status = 4;
                try{
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactMobileNumber) && _fileSubmission.ContactMobileNumber.IsValid(StringValidationType.CellularNumber))
                    {
                        var smsBody = DBReadManager.GetMasterLocalFileNotificationSmsBodyTemplate(3);
                        if (!string.IsNullOrEmpty(smsBody))
                        {
                            var service = new FDRQueueService();
                            service.SendSms
                            (
                                _fileSubmission.ContactMobileNumber
                                , _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                            );

                            DBWriteManager.SaveSentSmsCommunications(
                                _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                                );
                        }
                    }
                }
                catch (Exception) {
                    ;
                }
                try{
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactEmail))
                    {
                        //var attachment = FdrCommon.GetFileRejectionLetter(SubmissionId);
                        var service     = new FDRQueueService();
                        var messageBody = string.Format(
                            DBReadManager.GetMasterLocalFileNotificationEmailBodyTemplate(3),
                            _fileSubmission.TaxRefNo);
                        service.SendEmail(
                            messageBody
                            , "CBC File validation outcome"
                            , _fileSubmission.ContactEmail
                            , null
                            , "CBC File validation outcome"
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                            );
                    }
                }
                catch (Exception) {
                    ;
                }

                //SEND EFILING REJECTION LETTERS
                try{
                    var attachment = FdrCommon.GetEfilingRejectionLetter(_fileSubmission.TaxRefNo, _fileSubmission.Year, Convert.ToDecimal(SubmissionId));
                    if (!string.IsNullOrEmpty(attachment))
                    {
                        var service = new FDRQueueService();
                        service.SendLetter
                        (
                            _fileSubmission.SubmissionId
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                            , attachment
                            , "Rejection of Master Files and Local Files"
                            , false
                            , Sars.Systems.Security.ADUser.CurrentSID
                        );
                    }
                }
                catch (Exception exception) {
                    MessageBox.Show(exception.ToString());
                }
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactMobileNumber) && _fileSubmission.ContactMobileNumber.IsValid(StringValidationType.CellularNumber))
                    {
                        var smsBody = DBReadManager.GetMasterLocalFileNotificationSmsBodyTemplate(4);
                        if (!string.IsNullOrEmpty(smsBody))
                        {
                            var service = new FDRQueueService();
                            service.SendSms
                            (
                                _fileSubmission.ContactMobileNumber
                                , _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                            );
                            DBWriteManager.SaveSentSmsCommunications(
                                _fileSubmission.TaxRefNo
                                , string.Format(smsBody, _fileSubmission.TaxRefNo)
                                , _fileSubmission.Year
                                );
                        }
                    }
                }
                catch (Exception)
                {
                    ;
                }
                try
                {
                    if (!string.IsNullOrEmpty(_fileSubmission.ContactEmail))
                    {
                        //var attachment = FdrCommon.GetFileRejectionLetter(SubmissionId);
                        var service     = new FDRQueueService();
                        var messageBody = string.Format(
                            DBReadManager.GetMasterLocalFileNotificationEmailBodyTemplate(4),
                            _fileSubmission.TaxRefNo);
                        service.SendEmail(
                            messageBody
                            , "CBC File validation outcome"
                            , _fileSubmission.ContactEmail
                            , null
                            , "CBC File validation outcome"
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                            );
                    }
                }
                catch (Exception)
                {
                    ;
                }

                //SEND EFILING ACCEPTANCE LETTERS

                try
                {
                    var attachment = FdrCommon.GetEfilingRejectionLetter(_fileSubmission.TaxRefNo, _fileSubmission.Year, Convert.ToDecimal(SubmissionId));
                    if (!string.IsNullOrEmpty(attachment))
                    {
                        var service = new FDRQueueService();
                        service.SendLetter
                        (
                            _fileSubmission.SubmissionId
                            , _fileSubmission.TaxRefNo
                            , _fileSubmission.Year
                            , attachment
                            , "Rejection of Master Files and Local Files"
                            , false
                            , Sars.Systems.Security.ADUser.CurrentSID
                        );
                    }
                }
                catch (Exception)
                {
                    ;
                }
                //Accepted With Warnings = 5
                status = 5;
            }
            if (status != 0)
            {
                DBWriteManager.ChangeSubmissionStatus(Convert.ToDecimal(SubmissionId), status);
            }
        }
        else
        {
            MessageBox.Show("No validation was submitted");
        }
    }
Ejemplo n.º 19
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var listOfFiles = new List <FileValidationOutcomeDetails>();

        const int submissionStatus = 2; //In Progress

        foreach (GridViewRow row in gvLocalFiles.Rows)
        {
            var ddlOutcome       = row.FindControl("ddlOutcome") as DropDownList;
            var txtOutcomeReason = row.FindControl("txtOutcomeReason") as TextBox;
            if (ddlOutcome != null && txtOutcomeReason != null)
            {
                ddlOutcome.BackColor = Color.Transparent;
                if (ddlOutcome.SelectedIndex <= 0)
                {
                    ddlOutcome.BackColor = Color.Red;
                    continue;
                }
                var dataKey = gvLocalFiles.DataKeys[row.RowIndex];
                if (dataKey != null)
                {
                    var fileId = Convert.ToDecimal(dataKey.Value);
                    listOfFiles.Add(
                        new FileValidationOutcomeDetails
                    {
                        Id                  = 0,
                        SubmissionId        = Convert.ToDecimal(SubmissionId),
                        FileId              = fileId,
                        ValidationOutcomeId = Convert.ToInt32(ddlOutcome.SelectedValue),
                        SID                 = Sars.Systems.Security.ADUser.CurrentSID
                        ,
                        OutcomeReason = txtOutcomeReason.Text
                    }
                        );
                }
            }
        }
        foreach (GridViewRow row in gvMasterFiles.Rows)
        {
            var ddlOutcome       = row.FindControl("ddlOutcome") as DropDownList;
            var txtOutcomeReason = row.FindControl("txtOutcomeReason") as TextBox;
            if (ddlOutcome != null && txtOutcomeReason != null)
            {
                ddlOutcome.BackColor = Color.Transparent;
                if (ddlOutcome.SelectedIndex <= 0)
                {
                    ddlOutcome.BackColor = Color.Red;
                    continue;
                }
                var dataKey = gvMasterFiles.DataKeys[row.RowIndex];
                if (dataKey != null)
                {
                    var fileId = Convert.ToDecimal(dataKey.Value);
                    listOfFiles.Add(
                        new FileValidationOutcomeDetails
                    {
                        Id                  = 0,
                        SubmissionId        = Convert.ToDecimal(SubmissionId),
                        FileId              = fileId,
                        ValidationOutcomeId = Convert.ToInt32(ddlOutcome.SelectedValue),
                        SID                 = Sars.Systems.Security.ADUser.CurrentSID,
                        OutcomeReason       = txtOutcomeReason.Text
                    }
                        );
                }
            }
        }
        if (listOfFiles.Any())
        {
            listOfFiles.ForEach(detailse => DBWriteManager.SaveFileValidationOutcome(detailse));
            MessageBox.Show("Validation saved successfully");
            DBWriteManager.ChangeSubmissionStatus(Convert.ToDecimal(SubmissionId), submissionStatus);
        }
        else
        {
            DBWriteManager.ChangeSubmissionStatus(Convert.ToDecimal(SubmissionId), submissionStatus);
            MessageBox.Show("File validations saved successfully.");
        }
    }
Ejemplo n.º 20
0
 protected void btnGetMNEList_Click(object sender, EventArgs e)
 {
     DBWriteManager.TruncateMNEList();
     UploadFile.ProcessFile();
     MessageBox.Show(UploadFile.Message);
 }
Ejemplo n.º 21
0
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        var _sql =
            @"SELECT TOP 1 [MessageSpec_ID] ,[CBCReport]   FROM [FDR].[dbo].[X_MessageSpec] where [MessageSpec_ID] not in (select [MessageSpec_ID] from [dbo].[X_AdditionalInfo]) and [CBCReport] is not null";

        using (var data = new RecordSet(_sql, QueryType.TransectSQL, null))
        {
            if (data.HasRows)
            {
                foreach (DataRow row in data.Tables[0].Rows)
                {
                    var messageSpecId = Convert.ToDecimal(row["MessageSpec_ID"]);
                    var cbcXml        = row["CBCReport"].ToString();
                    var cbcMessage    = XmlObjectSerializer.ConvertXmlToObject <CBC_OECD>(cbcXml);
                    if (cbcMessage == null)
                    {
                        continue;
                    }

                    foreach (var cbcBodyType in cbcMessage.CbcBody)
                    {
                        if (cbcBodyType.AdditionalInfo != null)
                        {
                            foreach (var addInfo in cbcBodyType.AdditionalInfo)
                            {
                                var additionalInfoId = 0M;
                                additionalInfoId = DBWriteManager.Save_X_AdditionalInfo(
                                    additionalInfoId
                                    , addInfo.DocSpec.DocTypeIndic.ToString()
                                    , addInfo.DocSpec.DocRefId
                                    , addInfo.DocSpec.CorrMessageRefId
                                    , addInfo.DocSpec.CorrDocRefId
                                    , addInfo.OtherInfo
                                    , messageSpecId
                                    );
                                if (additionalInfoId > 0)
                                {
                                    if (addInfo.ResCountryCode != null)
                                    {
                                        foreach (var countryCodeType in addInfo.ResCountryCode)
                                        {
                                            DBWriteManager.X_AdditionalInfo_ResCountryCode(
                                                0M
                                                , countryCodeType.ToString()
                                                , additionalInfoId
                                                );
                                        }
                                    }
                                    if (addInfo.SummaryRef != null)
                                    {
                                        foreach (var cbcSummary in addInfo.SummaryRef)
                                        {
                                            DBWriteManager.Save_X_AdditionalInfo_SummaryRef(
                                                0M
                                                , cbcSummary.ToString()
                                                , additionalInfoId
                                                );
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
Ejemplo n.º 22
0
    protected void btnGenerateSingle_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        try
        {
            Button      btnGenerate = (Button)sender;
            GridViewRow gvRow       = (GridViewRow)btnGenerate.Parent.Parent;
            Guid        newUID      = new Guid();
            var         xmldoc      = new XmlDocument();
            XmlNode     messageSpec = xmldoc.CreateNode(XmlNodeType.Element, "MessageSpec", xmldoc.NamespaceURI);
            var         countryCode = gvRow.Cells[0].Text.Split('-')[1].Trim();
            var         country     = gvRow.Cells[0].Text.Split('-')[0].Trim();
            var         period      = ddlReportingPeriod.SelectedIndex == 0? gvRow.Cells[1].Text: ddlReportingPeriod.SelectedValue;
            var         year        = int.Parse(gvRow.Cells[2].Text);
            if (ValidateRequiredFields(period))
            {
                decimal id         = 0;
                var     outgoinCBC = DBReadManager.OutGoingCBCDeclarationsDetails(countryCode, period);
                if (outgoinCBC != null)
                {
                    id = outgoinCBC.Id;
                    var newPackage     = Common.GenerateNewPackage(countryCode, period, ref messageSpec, id);
                    var newMessageSpec = messageSpec;
                    var nmPackage      = newPackage;
                    var newPackagedCBC = Utils.GetOutgoingCBCR(newPackage, countryCode, year,
                                                               DateTime.Parse(period), Sars.Systems.Security.ADUser.CurrentSID,
                                                               nmPackage, id);
                    var saved = DatabaseWriter.SaveOutgoingCBC(newPackagedCBC, ref newUID);
                    if (saved > 0)
                    {
                        DBWriteManager.Insert_OutgoingPackageAuditTrail(newUID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} generated", country));
                    }
                    else
                    {
                        DBWriteManager.Insert_OutgoingPackageAuditTrail(outgoinCBC.UID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} generated", country));
                    }
                    LoadCBC();
                    MessageBox.Show(string.Format("Package for {0} was successfully generated", country));
                    return;
                }

                var package = Common.GenerateNewPackage(countryCode, period, ref messageSpec, id);
                if (!string.IsNullOrEmpty(package.ToString()))
                {
                    var outgoingCBC = Utils.GetOutgoingCBCR(package.ToString(), countryCode, year,
                                                            DateTime.Parse(period), Sars.Systems.Security.ADUser.CurrentSID,
                                                            null, id);
                    id = DatabaseWriter.SaveOutgoingCBC(outgoingCBC, ref newUID);
                    if (id > 0)
                    {
                        var newPackage     = Common.GenerateNewPackage(countryCode, period, ref messageSpec, id);
                        var newMessageSpec = messageSpec;
                        var nmPackage      = newPackage;
                        var newPackagedCBC = Utils.GetOutgoingCBCR(newPackage, countryCode, year,
                                                                   DateTime.Parse(period), Sars.Systems.Security.ADUser.CurrentSID,
                                                                   nmPackage, id);
                        var saved = DatabaseWriter.SaveOutgoingCBC(newPackagedCBC, ref newUID);
                    }

                    DBWriteManager.Insert_OutgoingPackageAuditTrail(newUID, Sars.Systems.Security.ADUser.CurrentSID, string.Format("Outgoing Package for {0} generated", country));

                    LoadCBC();
                    MessageBox.Show(string.Format("Outgoing Package for {0} was successfully generated", country));
                }
                else
                {
                    MessageBox.Show("No package was generated");
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }