using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AeBusinessLayer.ClassFiles;
using System.Xml.Xsl;
using System.Data.OleDb;
using System.Xml;
using System.IO;
using AeBusinessLayer;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Threading;
public partial class InvoiceManagement_InvoicesCreated : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            btnCancelInvoice.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            btnCancelRun.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            btnExecuteRun.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            btnCreateHTML.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            btnCreateXml.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            btnCreateInvoice.Attributes.Add("onclick", "getConfirmationForDelete(‘" + this.hdnFlag.ClientID.ToString() + "’)");
            AeSharedLibrary.clsSession.UserSession SessionStruct;
            SessionStruct = (AeSharedLibrary.clsSession.UserSession)Session["UserInformation"];
            AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
            DataSet _dsEmail = _batch.SelectToInvoiceDetails(SessionStruct.BillId);
            if (_dsEmail.Tables[0].Rows.Count > 0)
            {
                btnCancelInvoice.Visible = true;
                btnCreateInvoice.Visible = true;
                btnCreateXml.Visible = true;
                btnCreateHTML.Visible = true;
                btnCancelRun.Visible = true;
                gvInvoiceDetails.Visible = true;
                lblMessage.Visible = false;
                Panel8.Visible = true;
                Label1.Visible = true;
                chkBoxAlls.Visible = true;
                ViewState["EmailInvoice"] = _dsEmail.Tables[0];
                gvInvoiceDetails.DataSource = _dsEmail.Tables[0].DefaultView;
                gvInvoiceDetails.DataBind();
            }
            else
            {
                btnCancelInvoice.Visible = false;
                btnCreateInvoice.Visible = false;
                btnCreateXml.Visible = false;
                Label1.Visible = false;
                btnCreateHTML.Visible = false;
                btnCancelRun.Visible = false;
                chkBoxAlls.Visible = false;
                lblMessage.Visible = true;
                Panel8.Visible = false;
                lblMessage.Text = "Please Execute Run for creating invoices";
                gvInvoiceDetails.Visible = false;
            }
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Server.Transfer("~/InvoiceManagement/BatchSummary.aspx");
    }
    protected void gvInvoiceDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "InvoiceId")
        {
            LinkButton btn = (LinkButton)e.CommandSource;
            int TransId = Convert.ToInt32(btn.Text.ToString());
            SessionInfo(TransId, "~/InvoiceManagement/InvoicesCreated.aspx", "~/InvoiceManagement/TransactionDetails.aspx", string.Empty);
        }
    }
    protected void SessionInfo(int TransId, string PagePath, string NewPath, string MessageString)
    {
        AeSharedLibrary.clsSession.UserSession SessionStruct;
        SessionStruct = (AeSharedLibrary.clsSession.UserSession)Session["UserInformation"];
        SessionStruct.transId = TransId;
        SessionStruct.MessageString = MessageString;
        SessionStruct.PagePath = PagePath;
        Session["UserInformation"] = SessionStruct;
        Server.Transfer(NewPath);
    }
    protected void btnExecuteRun_Click(object sender, EventArgs e)
    {
        if (gvInvoiceDetails.Rows.Count == 0)
        {
            if (this.hdnFlag.Value == "OK")
            {
                AeSharedLibrary.clsSession.UserSession SessionStruct;
                SessionStruct = (AeSharedLibrary.clsSession.UserSession)Session["UserInformation"];
                int BillId = SessionStruct.BillId;
                //Add Confirmation Box here -Pawan
                AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
                _batch.ExecuteForBillRunToCreateInvoices(BillId);
                SessionInfo(0, "~/InvoiceManagement/InvoicesCreated.aspx", "~/Message/Message.aspx", "Execute run has been completed.");
            }
            else
            {
                //do not do anything.
            }
        }
        else if (gvInvoiceDetails.Rows.Count > 0)
        {
            if (this.hdnFlag.Value == "OK")
            {
                CheckBox chk;
                int Checked = 0;
                foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
                {
                    chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
                    if (chk.Checked == true)
                    {
                        Checked++;
                        int BillRunId = Convert.ToInt32(rowItem.Cells[1].Text.Trim().ToString());
                        AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
                        _batch.ExecuteForBillRunToCreateInvoices(BillRunId);
                    }
                }
                if (Checked == 0)
                {
                    AeSharedLibrary.clsMessage.Show("Select to Execute Bill Run");
                }
                else
                {
                    SessionInfo(0, "~/InvoiceManagement/InvoicesCreated.aspx", "~/Message/Message.aspx", "Execute run has been completed.");
                }
            }
            else
            {
                // do not do anything.
            }
        }
    }
    protected void btnCancelInvoice_Click(object sender, EventArgs e)
    {
        if (this.hdnFlag.Value == "OK")
        {
            CheckBox chk;
            int Checked = 0;
            foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
            {
                chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
                if (chk.Checked == true)
                {
                    Checked++;
                    LinkButton bill = (LinkButton)(rowItem.Cells[5].FindControl("lnkInvoice"));
                    int InvoiceId = Convert.ToInt32(bill.Text.Trim().ToString());
                    AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
                    _batch.CancelInvoices(InvoiceId);
                }
            }
            if (Checked == 0)
            {
                AeSharedLibrary.clsMessage.Show("Select to Cancel Invoice(s)");
            }
            else
            {
                SessionInfo(0, "~/InvoiceManagement/InvoicesCreated.aspx", "~/Message/Message.aspx", "Cancel Invoice has been completed.");
            }
        }
        else
        {
            //do not do anything
        }
    }
    protected void btnCancelRun_Click(object sender, EventArgs e)
    {
        if (this.hdnFlag.Value == "OK")
        {
            CheckBox chk;
            int Checked = 0;
            foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
            {
                chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
                if (chk.Checked == true)
                {
                    Checked++;
                    int billRunId = Convert.ToInt32(rowItem.Cells[1].Text.Trim().ToString());
                    AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
                    _batch.CancelBillRun(billRunId);
                }
            }
            if (Checked == 0)
            {
                AeSharedLibrary.clsMessage.Show("Select to Cancel bill run");
            }
            else
            {
                SessionInfo(0, "~/InvoiceManagement/InvoicesCreated.aspx", "~/Message/Message.aspx", "Cancel bill run has been completed.");
            }
        }
        else
        {
            // do not do anything
        }
    }
    protected void btnCreateInvoice_Click(object sender, EventArgs e)
    {
        if (this.hdnFlag.Value == "OK")
        {
            CheckBox chk;
            int Checked = 0;
            foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
            {
                chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
                if (chk.Checked == true)
                {
                    Checked++;
                    int billRunId = Convert.ToInt32(rowItem.Cells[1].Text.Trim().ToString());
                    string customerId = Convert.ToString(rowItem.Cells[4].Text.Trim().ToString());
                    int partnerid = Convert.ToInt32(rowItem.Cells[3].Text.Trim().ToString());
                    AeBusinessLayer.ClassFiles.BatchSummary _batch = new AeBusinessLayer.ClassFiles.BatchSummary();
                    _batch.CreateInvoice(billRunId, customerId, partnerid);
                }
            }
            if (Checked == 0)
            {
                AeSharedLibrary.clsMessage.Show("Select to Create Invoices");
            }
            else
            {
                SessionInfo(0, "~/InvoiceManagement/InvoicesCreated.aspx", "~/Message/Message.aspx", "Create Invoice(s) has been completed.");
            }
        }
        else
        {
            // do not do anything
        }
    }
    private void InsertHTMLStatus(int NoofHTMLstobeProcessed, int billRunId)
    {
        AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
        int retValue = _batch.InsertInvoiceProcessStatusFORHTML(NoofHTMLstobeProcessed, billRunId);
        if (retValue == 1)
        {
            //AeSharedLibrary.clsMessage.Show("opps ……………………..");
        }
        else if (retValue == 0)
        {
            AeSharedLibrary.clsMessage.Show("Error has been occurred");
        }
    }
    private void InsertXMLStatus(int NoofXmlstobeProcessed, int billRunId)
    {
        AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
        int retValue = _batch.InsertInvoiceProcessStatus(NoofXmlstobeProcessed, billRunId);
        if (retValue == 1)
        {
            //AeSharedLibrary.clsMessage.Show("opps ……………………..");
        }
        else if (retValue == 0)
        {
            AeSharedLibrary.clsMessage.Show("Error has been occurred");
        }
    }
    private void UpdateXMLStatus()
    {
        // Status ,  , XMLSProcessed , IsErrorForXML , ErrorForXML , XMLProcessStatus , ModifiedOn(getdate()) ,
        AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
        DataSet dsInvoiceStatusId = _batch.SelectTopInvoiceStatusId();
        int Err;
        if (dsInvoiceStatusId.Tables[0].Rows.Count > 0)
        {
            int InvoiceProcessStatusId = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString());
            int XMLSProcessed = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][1].ToString());
            int RetValue = _batch.UpdateInvoiceProcessStatus(InvoiceProcessStatusId, null, "Completed", 0, "Completed", 0, null);
            if (RetValue == 1)
            {
                //AeSharedLibrary.clsMessage.Show("opps ……………………..");
            }
            else if (RetValue == 0)
            {
                AeSharedLibrary.clsMessage.Show("Error has been occurred");
            }
        }
    }
    private void UpdateHTMLStatus()
    {
        AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
        DataSet dsInvoiceStatusId = _batch.SelectTopInvoiceStatusId();
        int Err;
        if (dsInvoiceStatusId.Tables[0].Rows.Count > 0)
        {
            int InvoiceProcessStatusId = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString());
            int XMLSProcessed = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][1].ToString());
            int RetValue = _batch.UpdateInvoiceProcessStatus(InvoiceProcessStatusId, null, "Completed", 0, "Completed", 0, null);
            if (RetValue == 1)
            {
                //AeSharedLibrary.clsMessage.Show("opps ……………………..");
            }
            else if (RetValue == 0)
            {
                AeSharedLibrary.clsMessage.Show("Error has been occurred");
            }
        }
    }
    protected void btnCreateXml_Click(object sender, EventArgs e)
    {
        AeBusinessLayer.ClassFiles.CreateXml _createXml = new AeBusinessLayer.ClassFiles.CreateXml();
        if (this.hdnFlag.Value == "OK")
        {
            CheckBox chk;
            int XMLStobeProcessed = 0;
            foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
            {
                chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
                if (chk.Checked == true)
                {
                    XMLStobeProcessed += 1;
                }
            }
            if (XMLStobeProcessed > 0)
            {
                int billRunId = Convert.ToInt32(gvInvoiceDetails.Rows[0].Cells[1].Text.Trim().ToString());
                InsertXMLStatus(XMLStobeProcessed, billRunId);
                AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
                DataSet dsInvoiceStatusId = _batch.SelectTopInvoiceStatusId();
                int InvoiceProcessStatusId = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString());
                Thread td = new Thread(new ThreadStart(NewThisTime));               
                td.IsBackground = true;
                td.Start();
                NewThisTime();
                AeSharedLibrary.clsSession.UserSession SessionStruct;
                SessionStruct = (AeSharedLibrary.clsSession.UserSession)Session["UserInformation"];
                SessionStruct.transId = InvoiceProcessStatusId;
                Session["UserInformation"] = SessionStruct;
                string popupScript = "<script language=javascript> window.open(‘../InvoiceManagement/ASyncXML.aspx’,’_blank’,’height=300,width=600,top=150,left=150,status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,copyhistory=false’)</script>";
                ClientScript.RegisterStartupScript(this.GetType(), "callpopup", popupScript);
            }
            else
            {
            }
        }
        else
        {
        }
    }
    protected void NewThisTime()
    {
        CheckBox chk;
        foreach (GridViewRow rowItem in gvInvoiceDetails.Rows)
        {
            chk = (CheckBox)(rowItem.Cells[0].FindControl("chkBoxChild"));
            if (chk.Checked == true)
            {
                int PartnerId = Convert.ToInt32(rowItem.Cells[3].Text.Trim().ToString());
                int billRunId = Convert.ToInt32(rowItem.Cells[1].Text.Trim().ToString());
                int billRunDetailId = Convert.ToInt32(rowItem.Cells[2].Text.Trim().ToString());
                LinkButton bill = (LinkButton)(rowItem.Cells[5].FindControl("lnkInvoice"));
                int billId = Convert.ToInt32(bill.Text);
                int InvoiceId = billId;
                string CustomerId = Convert.ToString(rowItem.Cells[4].Text.Trim());
                //Reset pool for the selected customer id here.
                AeBusinessLayer.ClassFiles.InvoiceCreated _invoice = new InvoiceCreated();
                int rtvalue = _invoice.ResetPool(CustomerId);
                if (rtvalue == 0)
                {
                    AeSharedLibrary.clsEmail.SendNewCustomerEmail("pawan.kumar@affinityexpress.co.in", "System is unable to reset the pool value", "Resetting Pool Value", null);
                }
                AeBusinessLayer.ClassFiles.XML _xml = new XML();
                _xml.CreateXML(PartnerId, InvoiceId, CustomerId, billRunId, billRunDetailId);
            }
        }
    }
    protected void btnCreateHTML_Click(object sender, EventArgs e)
    {
        if (this.hdnFlag.Value == "OK")
        {
            forhtml();
        }
    }
    protected void NewforHTML()
    {
        string _OutputDirectory = string.Empty;
        CheckBox chk;
        foreach (GridViewRow roowitem in gvInvoiceDetails.Rows)
        {
            chk = (CheckBox)(roowitem.Cells[0].FindControl("chkBoxChild"));
            if (chk.Checked == true)
            {
                LinkButton btn = (LinkButton)roowitem.Cells[5].FindControl("lnkInvoice");
                string str = btn.Text.ToString();
                int invoiceid = Convert.ToInt32(str);
                int partnerid = Convert.ToInt32(roowitem.Cells[3].Text);
                int billRunId = Convert.ToInt32(gvInvoiceDetails.Rows[0].Cells[1].Text.Trim().ToString());
                BatchSummary _incoivehtml = new BatchSummary();
                DataSet _dsinvoice = _incoivehtml.SelectinvoiceForHtmldetails(invoiceid);
                string customer_id = _dsinvoice.Tables[0].Rows[0]["customer_id"].ToString();
                DateTime dat = Convert.ToDateTime(_dsinvoice.Tables[0].Rows[0]["invoice_start_date"].ToString());
                DateTime date = dat;
                string Fillexml = string.Empty;
                try
                {
                    if (dat.Month.ToString().Length == 1)
                    {
                        if (dat.Day.ToString().Length == 1)
                            Fillexml = @"C:\Invoices\" + dat.Year + "-0" + dat.Month + "-0" + dat.Day + @"\" + partnerid + @"\" + "Inv" + invoiceid + ".xml";
                        else
                            Fillexml = @"C:\Invoices\" + dat.Year + "-0" + dat.Month + "-" + dat.Day + @"\" + partnerid + @"\" + "Inv" + invoiceid + ".xml";
                    }
                    else
                    {
                        if (dat.Day.ToString().Length == 1)
                            Fillexml = @"C:\Invoices\" + dat.Year + "-" + dat.Month + "-0" + dat.Day + @"\" + partnerid + @"\" + "Inv" + invoiceid + ".xml";
                        else
                            Fillexml = @"C:\Invoices\" + dat.Year + "-" + dat.Month + "-" + dat.Day + @"\" + partnerid + @"\" + "Inv" + invoiceid + ".xml";
                    }
                    string pathhtml = @"C:\Invoices\Emails\";
                    string targetfile = pathhtml + "\\" + date.Year + "-" + date.Month + "-" + date.Day + @"\" + partnerid + "\\" + invoiceid + ".html";
                    //string xslfile = "\\10.0.0.229\\Emails\\styleSheets\\" + "InternalToEmailFormatOne.xsl";
                    XsltArgumentList args = new XsltArgumentList();
                    args.AddParam("partnerid", "", partnerid);
                    args.AddParam("invoiceid", "", invoiceid);
                    _OutputDirectory = pathhtml + date.Year + "-" + date.Month + "-" + date.Day + @"\" + partnerid + "\\";
                    if (!Directory.Exists(_OutputDirectory))
                        Directory.CreateDirectory(_OutputDirectory);
                    //int retValue = transform(xslfile, Fillexml, args, targetfile);    — Replaced by code below Pawan.
                    XmlDocument transformDoc = new XmlDocument();
                    string str1 = @"\\10.0.0.229\\Emails\\styleSheets\\InternalToEmailFormatOne.xsl";
                    transformDoc.Load(str1);
                    XmlDocument sourceDoc = new XmlDocument();
                    sourceDoc.Load(Fillexml);
                    StreamWriter writer = new StreamWriter(targetfile, false, System.Text.Encoding.UTF8);
                    XslTransform trans = new XslTransform();
                    XmlUrlResolver resolver = new XmlUrlResolver();
                    GC.Collect();
                    trans.Load(transformDoc, resolver, System.AppDomain.CurrentDomain.Evidence);
                    trans.Transform(sourceDoc, args, writer, resolver);
                    writer.Flush();
                    writer.Close();
                    DataSet dsInvoiceStatusId = _incoivehtml.SelectTopInvoiceStatusId();
                    int Retz = _incoivehtml.UpdateInvoiceProcessStatusFORHTML(Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString()), "InProgress", 0, null, "In Progress", 0, null); 
                }
                catch (Exception exec)
                {
                    BatchSummary _bat = new BatchSummary();
                    DataSet dsInvoiceStatusId = _bat.SelectTopInvoiceStatusId();
                    BatchSummary _batch = new BatchSummary();
                    int returnValue = _batch.InsertIntoErrForHTMLGeneration(Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString()), exec.Message.ToString(), billRunId, partnerid, customer_id, invoiceid);
                }
            }
        }
    }
    protected void forhtml()
    {
        string _OutputDirectory = string.Empty;
        CheckBox chk;
        int totalNoOfHTMS = 0;
        foreach (GridViewRow roowitem in gvInvoiceDetails.Rows)
        {
            chk = (CheckBox)(roowitem.Cells[0].FindControl("chkBoxChild"));
            if (chk.Checked == true)
            {
                totalNoOfHTMS += 1;
            }
        }
        if (totalNoOfHTMS > 0)
        {
            int billRunId = Convert.ToInt32(gvInvoiceDetails.Rows[0].Cells[1].Text.Trim().ToString());
            InsertHTMLStatus(totalNoOfHTMS, billRunId);
            AeBusinessLayer.ClassFiles.BatchSummary _batch = new BatchSummary();
            DataSet dsInvoiceStatusId = _batch.SelectTopInvoiceStatusId();
            int InvoiceProcessStatusId = Convert.ToInt32(dsInvoiceStatusId.Tables[0].Rows[0][0].ToString());
            Thread td = new Thread(new ThreadStart(NewThisTime));               
            td.IsBackground = true;
            td.Start();
            NewforHTML();
            AeSharedLibrary.clsSession.UserSession SessionStruct;
            SessionStruct = (AeSharedLibrary.clsSession.UserSession)Session["UserInformation"];
            SessionStruct.transId = InvoiceProcessStatusId;
            Session["UserInformation"] = SessionStruct;
            string popupScript = "<script language=javascript> window.open(‘../InvoiceManagement/AsyncHTML.aspx’,’_blank’,’height=300,width=600,top=150,left=150,status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,copyhistory=false’)</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "callpopup", popupScript);
        }
    }
    protected int transform(string xslfile, string sourcefile, XsltArgumentList args, string targetfile)
    {
        XmlDocument transformDoc = new XmlDocument();
        try
        {
            string str = @"\\10.0.0.229\\Emails\\styleSheets\\InternalToEmailFormatOne.xsl";
            transformDoc.Load(str);
            XmlDocument sourceDoc = new XmlDocument();
            sourceDoc.Load(sourcefile);
            StreamWriter writer = new StreamWriter(targetfile, false, System.Text.Encoding.UTF8);
            XslTransform trans = new XslTransform();
            XmlUrlResolver resolver = new XmlUrlResolver();
            GC.Collect();
            trans.Load(transformDoc, resolver, System.AppDomain.CurrentDomain.Evidence);
            trans.Transform(sourceDoc, args, writer, resolver);
            writer.Flush();
            writer.Close();
        }
        catch (System.Exception e)
        {
            return 0;
        }
        return 1;
    }
}
Advertisements