Friday, February 18, 2011

Download file from griedview cell link in asp.net

1. Add gridview

<asp:GridView ID="GridView1" runat="server" SkinID="gridviewSkin" DataKeyNames="UploadID,UserId,AllocatedTo,AllocatedforQC"
                    OnRowCommand="GridView1_RowCommand" 
                    OnRowDataBound="GridView1_RowDataBound"
                    OnPageIndexChanging="GridView1_PageIndexChanging">
                    <Columns>
                        <asp:BoundField  HeaderText="Job#" DataField="uploadID" /> 
                        <asp:TemplateField HeaderText="Client Name-Uploaded By/ <br>Uploaded Date/<br>Duration/<br>File Size/<br>" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="left">
                            <ItemTemplate>
                                <b><%#Eval("ClientName")%></b>-<%#Eval("FullName")%><img src="images/spacer.gif" alt="" width="10"  height="13px" /><br />
                               
                                <%#Eval("CLIENT_UPLOAD_DATE")%><img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
                               
                                <%#Eval("Duration")%> [HH:MM:SS]<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
                               
                                <%#Eval("fileSize")%> kb<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
                            </ItemTemplate>
                        </asp:TemplateField>
                         <asp:BoundField  HeaderText="Transcribe By" DataField="ALLOCATEDTONAME" />
                       <asp:TemplateField HeaderText="Transcription File" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
                            <ItemTemplate>
                                <asp:LinkButton Text='<img src="Images/downloadaudio.gif" alt="" border="0">' runat="server" ID="lnkDownload" CommandArgument='<%#Eval("CLIENT_UPLOAD_FILENAME") %>' CommandName="lnkDownload" BorderStyle="None" BorderWidth="0"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Download File(s)<br> for QC" HeaderStyle-Width="2%" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:Image ID="FileImage1" CssClass="handcursor" runat="server" ImageUrl="Images/downloaddoc.gif" onclick='<%#Eval("UPLOADID", "return ShowPopup(\"{0}\")")%>' />
                        </ItemTemplate>
                            <HeaderStyle Width="2%"></HeaderStyle>
                            <ItemStyle Wrap="true" />
                        </asp:TemplateField>
                       <%--<asp:TemplateField HeaderText="Upload" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
                            <ItemTemplate>
                            <asp:LinkButton ID="lnkUpload" runat="server" Text="Upload" ></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>--%>
                        <asp:TemplateField HeaderText="Accept/Reject QC" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
                            <ItemTemplate>
                            <%--<asp:LinkButton ID="lnkAcceptQC" runat="server" Text="Release to QC" CommandArgument='<%#Eval("UploadID") %>' CommandName="AcceptQC"></asp:LinkButton>--%>
                                <asp:LinkButton ID="lnkAccept" runat="server" Text="Release to Client" OnClientClick="return confirmB();"  CommandArgument='<%#Eval("UploadID") %>' CommandName="Accept"></asp:LinkButton>
                                <br /><br />
                                <asp:LinkButton ID="lnkReject" runat="server" Text="Reject" CommandArgument='<%#Eval("UploadID") %>' CommandName="Reject"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                       
                        <asp:BoundField HeaderText="Status" HeaderStyle-Width="10%" DataField="STATUS" ItemStyle-HorizontalAlign="Center">
                            <HeaderStyle Width="8%"></HeaderStyle>
                            <ItemStyle Wrap="true" />
                        </asp:BoundField>
                    </Columns>
                </asp:GridView>

2. add code in code behind

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
 if (e.CommandName.Equals("lnkDownload"))
        {
           
            string strFilePath = System.Configuration.ConfigurationManager.AppSettings["uploadDictationFolder"].ToString();
            //+ "/" + e.CommandArgument.ToString()
           DownloadFile(e.CommandArgument.ToString(),strFilePath);
            //Response.Write(strFilePath);
         
        }
}

    public int DownloadFile(string fileName, string Path)
        {
            HttpResponse response = HttpContext.Current.Response;
            FileInfo file = null;
            int messageToReturn = 0;
            string path = Path + "\\" + fileName;
            try
            {
                file = new FileInfo(path);
                if (file.Exists)
                {
                    response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
                    response.AddHeader("Content-Length", file.Length.ToString());
                    response.ContentType = GetContentType(file);
                    response.TransmitFile(file.FullName);
                    response.Buffer = true;
                    response.End();
                    messageToReturn = (int)FileHandlerEnum.Success;
                    messageToReturn = (int)FileHandlerEnum.Success;
                }
                else
                {
                    messageToReturn = (int)FileHandlerEnum.FailedFileNotExist;
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //file = null;
                //response.End();
            }
            return messageToReturn;
        }

Dynamically Renaming or re-writing ASPX page name in asp.net

1. Add global.asax file and include this code
here i will rename MP4B.aspx and will put logo and content of page dynamically
 void Application_BeginRequest(object sender, EventArgs e)
    {
        string fullOrigionalpath = Request.Url.ToString();
        if (fullOrigionalpath.Contains("/Mobile4Business/"))
        {
            Context.RewritePath("/Mobile4Business/MP4B.aspx");
        }
       
    } 

 private string GetPageName(string url)
    {
        int startIndex = url.LastIndexOf('/');
        startIndex = startIndex + 1;
        int endindex = url.LastIndexOf('?');
        if (endindex == -1)
        { endindex = url.Length;
        }
        return url.Substring(startIndex, (endindex - startIndex));
    }

2.  write code in code behind ....Here you can use your own code for binding page
 protected void Page_Load(object sender, EventArgs e)
    {
      
      if(!IsPostBack)
     {
            string fullOrigionalpath = Request.RawUrl.ToString();
            string rawURL = GetPageName(fullOrigionalpath);
            string[] RID = rawURL.Split('.');
             Session["RID"] = Convert.ToString( Convert.ToInt32(RID[0]));
            fillpageinfo();
        
      }
    }
    private void fillpageinfo()
    {
       
           SqlDataReader dr;
           dr = objReseller.GetRsellerDetails();
           if(dr.HasRows)
            {
                dr.Read();
                HtmlImage RLogo1 = (HtmlImage)this.Page.FindControl("RLogo");
                RLogo1.Src = "..\\images\\" + dr["LogoFileName"].ToString();
                ResellerPageText.InnerHtml = dr["PageContent"].ToString();
          
            }
     
      
    }

 private string GetPageName(string url)
    {
        int startIndex = url.LastIndexOf('/');
        startIndex = startIndex + 1;
        int endindex = url.LastIndexOf('?');
        if (endindex == -1)
        {
            endindex = url.Length;
        }
        return url.Substring(startIndex, (endindex - startIndex));
    }

Progress bar using Ajax

1. Add Scipt manager
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

2.Add update panel and add ajax progress in it and file upload control in it
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                                    <td class="middleFormField2">
                                        <asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
                                        <asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
                                            color="#FF0000">*</font></strong>
                                    </td>
                                    <td align="left" class="middleFormField2">
                                        <table>
                                            <tr>
                                                <td valign="top">
                                                    <asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
                                                        <ProgressTemplate>
                                                            <div style="visibility: hidden" id="progressBarDiv">
                                                                <font style="color: #000000" color="#336633" size="2"></font>
                                                                <img src="images/preloader.gif" />
                                                            </div>
                                                        </ProgressTemplate>
                                                    </asp:UpdateProgress>
                                                </td>
                                                <td>
                                                    <asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
                                                    <asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
                                                        Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
                                                        SetFocusOnError="true" ValidationGroup="client" />
                                                    <asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
                                                    <div style="visibility: hidden" id="progressBarDivText">
                                                        <font style="color: Purple" size="1">Processing, Please Wait...</font>
                                                    </div>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
<tr>
                                    <td colspan="2" valign="top" class="middleFormField">
                                        <div align="center">
                                            <asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
                                                CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
                                                OnClientClick="javascript:showWait();" ValidationGroup="client" />
                                        </div>
                                    </td>
                                </tr>
</table>
</ContentTemplate>
 <Triggers>
                <asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
            </Triggers>
        </asp:UpdatePanel>
</asp:UpdatePanel>

3.Add Javascript which will fire on submit button
 <script language="javascript" type="text/javascript">
 function showWait() {
            var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
            if (FUpload.value.length > 0) {
                $get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
            }
            var div = document.getElementById('progressBarDiv');
            div.style.visibility = 'visible';
            document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';1. Add Scipt manager
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

2.Add update panel and add ajax progress in it and file upload control in it
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                                    <td class="middleFormField2">
                                        <asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
                                        <asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
                                            color="#FF0000">*</font></strong>
                                    </td>
                                    <td align="left" class="middleFormField2">
                                        <table>
                                            <tr>
                                                <td valign="top">
                                                    <asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
                                                        <ProgressTemplate>
                                                            <div style="visibility: hidden" id="progressBarDiv">
                                                                <font style="color: #000000" color="#336633" size="2"></font>
                                                                <img src="images/preloader.gif" />
                                                            </div>
                                                        </ProgressTemplate>
                                                    </asp:UpdateProgress>
                                                </td>
                                                <td>
                                                    <asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
                                                    <asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
                                                        Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
                                                        SetFocusOnError="true" ValidationGroup="client" />
                                                    <asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
                                                    <div style="visibility: hidden" id="progressBarDivText">
                                                        <font style="color: Purple" size="1">Processing, Please Wait...</font>
                                                    </div>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
<tr>
                                    <td colspan="2" valign="top" class="middleFormField">
                                        <div align="center">
                                            <asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
                                                CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
                                                OnClientClick="javascript:showWait();" ValidationGroup="client" />
                                        </div>
                                    </td>
                                </tr>
</table>
</ContentTemplate>
 <Triggers>
                <asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
            </Triggers>
        </asp:UpdatePanel>
</asp:UpdatePanel>

3.Add Javascript which will fire on submit button
 <script language="javascript" type="text/javascript">
 function showWait() {
            var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
            if (FUpload.value.length > 0) {
                $get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
            }
            var div = document.getElementById('progressBarDiv');
            div.style.visibility = 'visible';
            document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';
            var div1 = document.getElementById('progressBarDivText');
            div1.style.visibility = 'visible';
            //document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
        }
</script>

            var div1 = document.getElementById('progressBarDivText');
            div1.style.visibility = 'visible';
            //document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
        }
</script>

Monday, February 7, 2011

use of Outer Apply for joining function with existing query and Retriving collective information

1.Create a fuction like this

CREATE FUNCTION GetWarrantNotesDetails (@WarrantID varchar(22))   
   RETURNS @WarrantDetails Table   
     (  Remarks     varchar(1000)   
      , NoteDate  datetime   
      , AddedBy varchar(36)   
    )   
 AS   
   BEGIN   
       INSERT INTO @WarrantDetails (Remarks, NoteDate, AddedBy)   
        SELECT TOP(1) Remarks, NoteDate,[exec].cname   
        FROM warrant_notes iNNER JOIN [exec] ON   
       cast(warrant_notes.AddedBy as varbinary) = cast(dbo.[exec].cid as varbinary)      
      WHERE  WarrantID=@WarrantID AND AddedBy<>'Admin' ORDER BY NoteDate DESC   
     RETURN   
   END

2.call above mention fucntion in a query for Retriving its value
SELECT     SP_Case.warrantId, UPPER(Defendant_Master.DefendantName) AS 'Defendant Name', UPPER((client.Cname1)) AS 'Client Name',
                      CONVERT(varchar(20), StatusUpdateOn, 103) AS StatusUpdatedOn, UPPER(LEFT(STATUS_MASTER.STATUS_DESC, 255)) AS 'Status Description',
                      ISNULL(dbo.SP_Case.SpecialInstruction, '') AS 'SpecialInstruction', UPPER(ISNULL(report.DebtorType, ''))
                      AS DebtorType/*dbo.client.cltel1 AS 'Client Telephone1',dbo.client.cltel2 AS 'Client Telephone2',ISNULL(dbo.client.clmobile,'') AS 'Client Mobile'*/ ,
                      Defendant_Phone.Phone1 AS 'DebtorPhone1', defendant_phone.Phone2 AS 'DebtorPhone2', defendant_phone.Mobile AS 'DebtorMobile',
                      Defendant_Address.PCode,
                      ISNULL((dbo.Defendant_Address.Add1 + dbo.Defendant_Address.Add2 + dbo.Defendant_Address.Add3 + dbo.Defendant_Address.Add4), '')
                      AS 'Defendant Address', SP_Case.clientrefNo AS 'Client Reference Number', CASE WHEN CONVERT(VARCHAR(20), ISNULL(report.FirstVisitDT, ''), 103)
                      = '01/01/1900' THEN '' ELSE CONVERT(VARCHAR(20), ISNULL(report.FirstVisitDT, ''), 103) END AS 'FirstVisitDT', ISNULL(dbo.report.ArFirstVisit, '')
                      AS 'ArFirstVisit', CASE WHEN CONVERT(VARCHAR(20), ISNULL(report.SecondVisitDT, ''), 103) = '01/01/1900' THEN '' ELSE CONVERT(VARCHAR(20),
                      ISNULL(report.SecondVisitDT, ''), 103) END AS 'SecondVisitDT', ISNULL(dbo.report.ArSecondVisit, '') AS 'ArSecondVisit',
                      CASE WHEN CONVERT(VARCHAR(20), ISNULL(report.ThirdVisitDT, ''), 103) = '01/01/1900' THEN '' ELSE CONVERT(VARCHAR(20),
                      ISNULL(report.ThirdVisitDT, ''), 103) END AS 'ThirdVisitDT', ISNULL(dbo.report.ArThirdVisit, '') AS 'ArThirdVisit', ISNULL(dbo.report.Recommendation, '')
                      AS 'RID', ISNULL(DebtorIncomeExpenditure.DPSalary, '') AS 'Defendant Salary', WN.Remarks, CONVERT(VARCHAR(20), WN.Notedate, 103)
                      AS 'NoteDate', UPPER(WN.AddedBy) AS 'Added By', dbo.GetBalanceOutStanding(sp_case.Warrantid) AS 'Balance Outstanding',
                      CONVERT(VARCHAR(20), dbo.SP_Case.EntryDate, 103) AS 'Entry Date', UPPER(ISNULL(dbo.report.mnuTypeOfPremises, '')) AS 'Class',
                      UPPER(ISNULL(report.OfficerName, '')) AS 'Officer Name', ISNULL(t .PaymentAmount, 0) AS 'Payment Amount', ISNULL(t .Frequency, '') AS 'Frequency',
                      ISNULL(t .LastPaymentDate, '') AS 'Last Payment Date', ISNULL(t .PlanCreateDate, '') AS 'Plan Create Date', ISNULL(INV.DESCRIPTION, '')
                      AS 'DESCRIPTION', ISNULL(INV.Valuation, '') AS 'Valuation', LEFT(dbo.STATUS_MASTER.STATUS_CODE, 255) AS 'Status Code'
FROM         SP_Case OUTER APPLY GetWarrantNotesDetails(dbo.SP_Case.WarrantID) AS WN OUTER APPLY GetInventory(dbo.SP_Case.WarrantID)
                      AS INV INNER JOIN
                      Defendant_Master ON cast(SP_Case.WarrantID AS varbinary) = cast(Defendant_Master.WarrantID AS varbinary) INNER JOIN
                      client ON cast(client.CID AS varbinary) = cast(SP_Case.CClientId AS varbinary) INNER JOIN
                      Defendant_Address ON cast(Defendant_Address.Def_Id AS varbinary) = cast(Defendant_Master.CID AS varbinary) INNER JOIN
                      Defendant_Phone ON cast(Defendant_Phone.Def_Id AS varbinary) = cast(Defendant_Master.CID AS varbinary) INNER JOIN
                      STATUS_MASTER ON cast(STATUS_MASTER.STATUS_ID AS varbinary) = cast(SP_Case.Status AS varbinary) LEFT OUTER JOIN
                      report ON cast(report.WarrantID AS varbinary) = cast(SP_Case.WarrantID AS varbinary) LEFT OUTER JOIN
                      DebtorIncomeExpenditure ON cast(DebtorIncomeExpenditure.WarrantRefNo AS varbinary) = cast(dbo.SP_Case.WarrantID AS varbinary)
                      LEFT OUTER JOIN
                          (SELECT     Paymentplan.Warrantid, isnull(cast(dbo.Payplan_Installment.InstallmentAmount AS decimal(8, 2)), 0) AS PaymentAmount,
                                                   ISNULL(Payplan_Installment.Frequency, '') AS Frequency, CASE WHEN CONVERT(VARCHAR(20), ISNULL(Payplan_Installment.DateTo, ''),
                                                   103) = '01/01/1900' THEN '' ELSE CONVERT(VARCHAR(20), ISNULL(Payplan_Installment.DateTo, ''), 103) END AS LastPaymentDate,
                                                   CASE WHEN CONVERT(VARCHAR(20), ISNULL(Payplan_Installment.CreatedDate, ''), 103)
                                                   = '01/01/1900' THEN '' ELSE CONVERT(VARCHAR(20), ISNULL(Payplan_Installment.CreatedDate, ''), 103) END AS PlanCreateDate
                            FROM          Paymentplan INNER JOIN
                                                   Payplan_Installment ON cast(Paymentplan.Pid AS varbinary) = cast(Payplan_Installment.pid AS varbinary)
                            WHERE      isactive = 'Y'/*Paymentplan.Warrantid like 'SPC%' and    */ ) t ON cast(t .WarrantId AS varbinary) = cast(SP_Case.WarrantID AS varbinary)