Pages

Thursday, November 1, 2012

Insert bulk data in SQL Server using XML in ASP.Net

protected void InsertFlexyDetails(string BecRefID)
        {
            int errRet = 0;
            try
            {
                IList<Entities.EmployeeCompensation> lstEmployeeCompensation = new List<Entities.EmployeeCompensation>();
               
               
                string strXML = string.Empty;

                objEmpComp = new BusinessLayer.EmployeeCompensation();
               
                foreach (DataGridItem dgItem in grdComponent.Items)
                {
                    if (dgItem.ItemType == ListItemType.Item || dgItem.ItemType == ListItemType.AlternatingItem)
                    {
                        DropDownList ddlFlexyAmount = (DropDownList)dgItem.FindControl("ddlFlexyAmount");
                        TextBox txtFlexyAmount = (TextBox)dgItem.FindControl("txtFlexyAmount");
                        Label lblFcID = (Label)dgItem.FindControl("lblFcID");

                        entEmpComp = new Entities.EmployeeCompensation();
                        entEmpComp.Id = Convert.ToInt32(lblFcID.Text);                       
                        if (ddlFlexyAmount.Visible == true)
                        {
                            entEmpComp.Amount = Convert.ToInt32(ddlFlexyAmount.SelectedValue);
                        }
                        else if (txtFlexyAmount.Visible == true)
                        {
                            entEmpComp.Amount = Convert.ToInt32(txtFlexyAmount.Text);
                        }
                        lstEmployeeCompensation.Add(entEmpComp);
                    }
                }

                errRet = objEmpComp.InsertCompensation(lstEmployeeCompensation);  
            }
            catch
            {
                throw;
            }
        }
public int InsertCompensation(IList<Entities.EmployeeCompensation> lstEmployeeCompensation)
        {
            int retVal = 0;
            string strFlexiAmntXML = string.Empty;
            try
            {
                if (lstEmployeeCompensation.Count > 0)
                {
                    strFlexiAmntXML = "<FlexiComponentDetails>";
                    for (int i = 0; i <= lstEmployeeCompensation.Count - 1; i++)
                    {
                        strFlexiAmntXML += "<FlexiComponent>";
                        strFlexiAmntXML += "<FC_ID>" + lstEmployeeCompensation[i].Id + "</FC_ID>";
                        strFlexiAmntXML += "<EC_Amount>" + lstEmployeeCompensation[i].Amount + "</EC_Amount>";
                        strFlexiAmntXML += "</FlexiComponent>";
                    }
                    strFlexiAmntXML += "</FlexiComponentDetails>";
                }

                DataAccess.EmployeeCompensation empCompensation = new DataAccess.EmployeeCompensation();
                retVal = empCompensation.InsertCompensation(strFlexiAmntXML);
            }
            catch (Exception ex)
            {

            }
            return retVal;
        }
public int InsertCompensation(string strFlexiAmntXML)
        {
            int errRet = 0;
            try
            {
                DbCommand cmd = dbHelper.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Insert_FlexiComponents";
               
                DbParameterBuilder.Add(cmd, "InputXML", DbType.String, ParameterDirection.Input, strFlexiAmntXML);
                errRet = dbHelper.ExecuteNonQuery(cmd);
            }
            catch (Exception ex)
            {
                errRet = 1;
            }

            return errRet;
        }

CREATE PROCEDURE [dbo].[sp_Insert_FlexiComponents]
 -- Add the parameters for the stored procedure here
 @InputXML AS VARCHAR(MAX)
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
 
  DECLARE @XML AS XML
       
        DECLARE @AmountTable TABLE
        (
            ID INT IDENTITY(1,1),
            EC_FC_ID int,
            EC_Amount int
        )
       
        SELECT @XML = @InputXML
       
        INSERT INTO @AmountTable (EC_FC_ID, EC_Amount)
        SELECT M.Item.query('./FC_ID').value('.','INT') EC_FC_ID,
               M.Item.query('./EC_Amount').value('.','INT') EC_Amount
        FROM @XML.nodes('/FlexiComponentDetails/FlexiComponent') AS M(Item)
END

Eanble Disable control on checkbox click

<script type="text/javascript">
        function EnableControl(val) {
            var sbmt = document.getElementById("<%=btnSubmit.ClientID %>");

            if (val.checked == true) {
                sbmt.disabled = false;
            }
            else {
                sbmt.disabled = true;
            }
        }
       
       
    </script>
<div style="float: left;">
            <asp:CheckBox ID="chkAgree" runat="server" Text="I Agree" onclick="EnableControl(this)"
                Checked="false" />&nbsp;&nbsp;&nbsp;
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></div>

Show/hide control if a certain selection is made in previous drop down

<script type="text/javascript">
   
    function function1(colors) {
        var col = (colors.options[colors.selectedIndex].value);
        if (col == 0 || col == 2) {
            document.getElementById("<%=divStatus.ClientID %>").style.display = "none";
        }
        else {
            document.getElementById("<%=divStatus.ClientID %>").style.display = "block";
        }
        //alert("SelectedIndex value = " + col);
    }
</script>
<asp:DropDownList ID="ddlReport" runat="server" Width="164px" onchange="function1(this);" >
                    <asp:ListItem Text="--Select--" Selected="True" Value="0" />
                    <asp:ListItem Text="Allocation Status" Value="1" />
                    <asp:ListItem Text="Compensation Structure" Value="2" />
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfvReport" runat="server" ControlToValidate="ddlReport"
                    InitialValue="0" ErrorMessage="*"></asp:RequiredFieldValidator>
<div id="divStatus" runat="server"  style="margin-top: 7em;display:none"></div>

Save Customer Product details with subreport in .pdf on button click

 protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dtEmployeeDetail = report.GetEmployeeDetailCompensation(2, 4, "a");
                if (dtEmployeeDetail.Rows.Count > 0)
                {
                    strSubmitDate = dtEmployeeDetail.Rows[0]["EAP_ClosedOn"].ToString();
                    ReportDataSource datasource = new ReportDataSource("DataSet1", dtEmployeeDetail);
                    ReportViewer ReportViewer1 = new ReportViewer();
                    ReportViewer1.Reset();

                    ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/EmpReports/rptEmployeeCompensationDetails.rdlc");
                    ReportViewer1.LocalReport.EnableExternalImages = true;
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(datasource);
                    ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
                    ReportViewer1.LocalReport.Refresh();
                    string fileName = "EmpCompensationDetails_" + Convert.ToDateTime(DateTime.Now).ToString("MMddyyyyhhmm") + ".pdf";
                    //string fileName = Server.MapPath("~/EmpReports/TempReportOutputs/EmpCompensationDetails_") + Convert.ToDateTime(DateTime.Now).ToString("MMddyyyyhhmm") + ".pdf";
                   // bool success = ByteArrayToFile(fileName, GetExportedBytes(ReportViewer1.LocalReport, ReportFormat.PDF));
                    //if (success)
                    //{
                        try
                        {
                            SendMail(fileName, GetExportedBytes(ReportViewer1.LocalReport,ReportFormat.PDF));
                           
                        }
                        catch (Exception ex)
                        {
                            System.IO.File.Delete(fileName);
                        }
                   // }
                }
            }
            catch (Exception ex)
            {
            }
        }
 void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
          
                DataTable dtEmployeeCompensation = report.GetEmployeeCompensationStructure(2,4, "a");
                if (dtEmployeeCompensation.Rows.Count > 0)
                {
                    // string strParameter = e.Parameters["BecRef"].Values[0].ToString();
                    ReportDataSource rdS = new ReportDataSource("DataSet1", dtEmployeeCompensation);
                    e.DataSources.Add(rdS);
                }
        }
private void SendMail(string fileName, byte[] _ByteArray)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(_ByteArray);
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, fileName);
                   
            //BusinessLayer.Mail mail = new BusinessLayer.Mail();
            //mail.EmailSend("from", "to", "bcc", "subject", CreateEmailBody(), new System.Net.Mail.Attachment(fileName));
           
        }
public static byte[] GetExportedBytes(LocalReport lr, ReportFormat fmt)
        {
            byte[] toReturn = null;
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string filenameExtension;
            toReturn = lr.Render(fmt.ToString(), null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
            return toReturn;
        }
public enum ReportFormat
        {
            PDF,
            Word,
            Excel,
            Image
        }
//Save bytes in a File

public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        //{
        //    try
        //    {
        //        // Open file for reading
        //        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        //        // Writes a block of bytes to this stream using data from a byte array.
        //        _FileStream.Write(_ByteArray, 0, _ByteArray.Length);
        //        // close file stream .
        //        _FileStream.Close();
        //        return true;
        //    }
        //    catch (Exception _Exception)
        //    {
        //        // Error            
        //        //lblMsg.Text = string.Format("Exception caught in process: {0}", _Exception.ToString());
        //    }
        //    return false;
        //}