SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru pinch's Avatar
    Join Date
    Mar 2005
    Posts
    688
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problems Writing to Output Stream

    I am using a free excel library from CarlogAg to write an xml file into the output stream of the Response object. In order to make this happen, I just handle the Click event of a Linkbutton, ultimately building the spreadsheet and adding it to the data stream. I do all of this in the code-behind of an existing page because the data that I load into my spreadsheet depends on some of the control values on the page.

    The problem I'm encountering is that, although the spreadsheet data is properly streamed into the Response object, the entire html output of the page is added to the end of the stream. Not surprisingly, Excel screams when you try to open it.

    Is there any way to stop the data stream once I finish writing my workbook to it?

    Here is the .aspx page:

    Code ASP:
    <%@ Page Title="Manage Users" Language="C#" MasterPageFile="~/PageContainer.master" AutoEventWireup="true" CodeFile="ManageUsers.aspx.cs" Inherits="USMC.EPAS.UI.ManageUsers" %>
    <%@ Register src="~/usercontrols/UnitSelector.ascx" tagname="UnitSelector" tagprefix="epas" %>
    <%@ Register Namespace="USMC.EPAS.MyControls" TagPrefix="epas" %>
     
     
    <asp:Content ID="Content1" ContentPlaceHolderID="cphPageContent" Runat="Server">
     
     
    <div class="manageUsers">
     
      <%--Standard Controls--%>
      <table class="standardControls">
        <tr>
          <%--Left Side--%>
          <td>
            <table>
              <tr>
                <td class="label">Unit: </td>
                <td>
                  <asp:Label runat="server" ID="labWorkSection" Visible="false" />
                  <epas:UnitSelector ID="usUnitSelector" runat="server" ShowWorksiteMessage="false"/>
                </td>
              </tr>
            </table>
          </td>
          <%--Right Side--%>
          <td class="rAlign">
            <table class="buttonTable">
              <tr>
                <td>
                  <%--Delete Checked Users--%>
                  <asp:LinkButton runat="server" ID="lbDeleteCheckedUsers" PostBackUrl="~/admin/users/ManageUsers.aspx" 
                    onclick="lbDeleteCheckedUsers_Click" OnClientClick="return window.confirm('Are you sure you want to permanently delete the checked users?  You will not be able to retrieve these users\' information once they are deleted.');" >
                    <asp:Image ID="Image1" runat="server" ImageUrl="~/images/icons/smalldelete.gif" /> Delete Checked Users
                  </asp:LinkButton>
                </td>
              </tr>
              <tr>
                <td>
                  <%--Export--%>
                  <asp:LinkButton runat="server" ID="lbExportTo3n" 
                    onclick="lbExport_Click">
                    <asp:Image runat="server" ImageUrl="~/images/icons/export.gif" /> Export
                    <asp:HyperLink runat="server" Target="_blank" NavigateUrl="~/admin/users/Test.aspx" Text="test" />
                  </asp:LinkButton>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
     
      <br />
     
      <%--The subnavigation tabs--%>
      <ul id="subNav">
        <li>
          <asp:LinkButton runat="server" ID="lbActive" CommandArgument="Active" onclick="lbPersonnelState_Click">Active</asp:LinkButton>    
        </li>
        <li>
          <asp:LinkButton runat="server" ID="lbArchived" CommandArgument="Archived" onclick="lbPersonnelState_Click">Archived</asp:LinkButton>
        </li>
      </ul>
     
     
      <%--This container holds all data inside of the sub navigation--%>
      <div class="subNavBody">
     
        <%--This table holds the controls for the gridview--%>
        <asp:Panel runat="server" ID="gridControls">
          <table class="gridControls">
            <tr>
              <td style="vertical-align:bottom;">
                Displaying records 
                <asp:Label runat="server" ID="labFirstRecord" CssClass="boldText" /> through
                <asp:Label runat="server" ID="labLastRecord" CssClass="boldText" /> of
                <asp:Label runat="server" ID="labTotalRecords" CssClass="boldText" />
              </td>
              <td style="text-align:right;">
                <%--Records Per Page--%>
                <asp:Literal runat="server" ID="litRecordsPerPage" Text="Records Per Page" />
                <asp:DropDownList runat="server" ID="ddlPageSize" AutoPostBack="true" 
                  onselectedindexchanged="ddlPageSize_SelectedIndexChanged">
                  <asp:ListItem Value="25" Selected="True">25</asp:ListItem>
                  <asp:ListItem Value="50">50</asp:ListItem>
                  <asp:ListItem Value="100">100</asp:ListItem>
                  <asp:ListItem Value="0">All</asp:ListItem>
                </asp:DropDownList>
              </td>
            </tr>
          </table>
        </asp:Panel>
     
     
        <%--Manage Users Grid--%>
        <asp:GridView runat="server" ID="gvUsers" AutoGenerateColumns="False" SkinID="Professional"
          CssClass="standardGrid" DataKeyNames="PersonnelID" DataSourceID="odsUserSummaries" 
          onrowdatabound="gvUsers_RowDataBound" AllowPaging="true" Width="100%" AllowSorting="true" 
          ondatabound="gvUsers_DataBound" PagerStyle-Font-Bold="true" 
          PagerSettings-Position="Bottom" oninit="gvUsers_Init">
          <Columns>
            <asp:TemplateField>
              <ItemTemplate>
                <epas:CheckBoxButton runat="server" ID="cbDeleteUser"/>
                <asp:Image runat="server" ID="imaCheckBoxFaded" ImageUrl="~/images/gridviewbuttons/CheckBox_Faded.gif" style="margin-left:4px;" />
              </ItemTemplate>
            </asp:TemplateField>
            <%--Full Name--%>
            <asp:TemplateField HeaderText="Name" SortExpression="Name" HeaderStyle-CssClass="sortableHeader">
              <ItemTemplate>
                <asp:Label runat="server" ID="labFullNameLastFirst" />
                <asp:Image runat="server" ID="imaEditor" ImageUrl="~/images/icons/editor.gif" Visible="false" CssClass="tAlign"/>
                <asp:Image runat="server" ID="imaManager" ImageUrl="~/images/icons/manager.gif" Visible="false" CssClass="tAlign"/>
                <asp:Image runat="server" ID="imaAdministrator" ImageUrl="~/images/icons/administrator.gif" Visible="false" CssClass="tAlign"/>
                <asp:Image runat="server" ID="imaSuperuser" ImageUrl="~/images/icons/superuser.gif" Visible="false" CssClass="tAlign"/>
                <asp:Image runat="server" ID="imaWebmaster" ImageUrl="~/images/icons/webmaster.gif" Visible="false" CssClass="tAlign"/>
              </ItemTemplate>
            </asp:TemplateField>
     
            <%--<asp:BoundField DataField="FullNameLastFirst" HeaderText="Name" SortExpression="Name" />--%>
            <asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" HeaderStyle-CssClass="sortableHeader"/>
            <asp:BoundField DataField="Command" HeaderText="Command" SortExpression="Command" HeaderStyle-CssClass="sortableHeader"/>
            <asp:BoundField DataField="Department" HeaderText="Department" />
            <asp:BoundField DataField="Section" HeaderText="Section" />
            <%--Estimated Date of Departure--%>
            <asp:TemplateField SortExpression="EDD" HeaderStyle-CssClass="acronymHeader">
              <HeaderTemplate>
                <asp:LinkButton runat="server" ToolTip="Estimated Date of Departure" CommandName="Sort" CommandArgument="EDD">EDD</asp:LinkButton>
              </HeaderTemplate>
              <ItemTemplate>
                <asp:Label runat="server" ID="labEstimatedDateOfDeparture" />
              </ItemTemplate>
            </asp:TemplateField>
            <%--Archived Timestamp--%>
            <asp:TemplateField HeaderText="Archived">
              <ItemTemplate>
                <asp:Label runat="server" ID="labArchived" />
              </ItemTemplate>
            </asp:TemplateField>
     
            <%--This is a hack because ImageButtons cause double postbacks--%>
            <asp:TemplateField>
              <ItemTemplate>
                <%--Edit User--%>
                <asp:HyperLink runat="server" ID="hlEditUser" ToolTip="Click to edit this user's data.">
                  <asp:Image ID="Image2" runat="server" ImageUrl="~/images/gridviewbuttons/Edit.gif" />
                </asp:HyperLink>
                <asp:Image runat="server" ID="imaEditUserFaded" ImageUrl="~/images/gridviewbuttons/Edit_Faded.gif"/>
                <%--Delete--%>
                <asp:ImageButton runat="server" ID="ibDelete" ImageUrl="~/images/gridviewbuttons/Delete.gif" ToolTip="Click to permanently delete this user." 
                  CommandArgument='<%# Eval("PersonnelID") %>' OnCommand="ibDelete_Command" OnClientClick="return window.confirm('Are you sure you want to permanently delete this user?  You will not be able to retrieve this user\'s information once they are deleted.');" />
                <asp:Image runat="server" ID="imaDeleteFaded" ImageUrl="~/images/gridviewbuttons/Delete_Faded.gif"/>
                <%--Archive--%>
                <asp:ImageButton runat="server" ID="ibArchive" ImageUrl="~/images/gridviewbuttons/Archive.gif" ToolTip="click to archive this user." 
                  CommandArgument='<%# Eval("PersonnelID") %>' OnCommand="ibArchive_Command" OnClientClick="return window.confirm('Are you sure you want to archive this user?');" />
                <asp:Image runat="server" ID="imaArchiveFaded" ImageUrl="~/images/gridviewbuttons/Archive_Faded.gif"/>
                <%--Activate--%>
                <asp:ImageButton runat="server" ID="ibActivate" ImageUrl="~/images/gridviewbuttons/Activate.gif" ToolTip="click to activate this user." 
                  CommandArgument='<%# Eval("PersonnelID") %>' OnCommand="ibActivate_Command" OnClientClick="return window.confirm('Are you sure you want to activate this user?');" />
                <asp:Image runat="server" ID="imaActivateFaded" ImageUrl="~/images/gridviewbuttons/Activate_Faded.gif"/>
              </ItemTemplate>
            </asp:TemplateField>
          </Columns>
          <EmptyDataTemplate>
            <asp:Label runat="server" ID="labNoPersonnel" />
          </EmptyDataTemplate>  
        </asp:GridView>
      </div>
     
     
      <asp:ObjectDataSource runat="server" ID="odsUserSummaries" SelectMethod="GetUserSummaries" 
        TypeName="USMC.EPAS.BLL.Personnel.UserSummary" SelectCountMethod="GetUserSummaryCount"  
        onselecting="odsUserSummaries_Selecting" EnablePaging="true" SortParameterName="SortParam" 
        onselected="odsUserSummaries_Selected">
        <SelectParameters>
          <asp:Parameter Name="startingNodeID" Type="Int32" />
          <asp:Parameter Name="archived" Type="Boolean" />
        </SelectParameters>
      </asp:ObjectDataSource>
     
    </div>
     
     
     
    </asp:Content>


    And the code-behind:

    Code ASP:
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using USMC.EPAS.BLL.Personnel;
    using USMC.EPAS.MyControls;
    using CarlosAg.ExcelXmlWriter;
     
    namespace USMC.EPAS.UI
    {
      public partial class ManageUsers : BasePage
      {
     
        public bool ShowingArchivedPersonnel
        {
          get {
            return (ViewState["ShowingArchivedPersonnel"] == null) ? false : (bool)ViewState["ShowingArchivedPersonnel"]; 
          }
          set { ViewState["ShowingArchivedPersonnel"] = value; }
        }
     
     
        protected void Page_Load(object sender, EventArgs e)
        {
          if (!IsPostBack)
          {
            PageContainer myMaster = (PageContainer)Page.Master;
            myMaster.TitleType = PageContainer.TitleTypes.ADMIN;
            // initialize the property sub nav item
            lbActive.CssClass = "here";
            // load the page size based on the ddl
            gvUsers.PageSize = int.Parse(ddlPageSize.SelectedValue);
          }
     
          usUnitSelector.NodeEvent += new Globals.NodeChangeEventHandler(userControl_NodeHandler);
        }
     
        public void userControl_NodeHandler(object sender, Globals.NodeChangedEventArgs e)
        {
          gvUsers.PageIndex = 0;
          gvUsers.DataBind();
        }
     
        protected void ibDelete_Command(object sender, CommandEventArgs e)
        {
          // Delete the user from the membership system
          int relevantPersonnelID = Convert.ToInt32(e.CommandArgument);
          string relevantPersonnelEID = Personnel.GetPersonnelEID(Convert.ToInt32(e.CommandArgument));
     
          Membership.DeleteUser(relevantPersonnelEID);
          // Delete the user from the DB
          Personnel.DeletePerson(relevantPersonnelID);
          // Rebind the data
          gvUsers.DataBind();
        }
     
        protected void ibArchive_Command(object sender, CommandEventArgs e)
        {
          Personnel.ArchivePerson(Convert.ToInt32(e.CommandArgument));
          gvUsers.DataBind();
        }
     
        protected void ibActivate_Command(object sender, CommandEventArgs e)
        {
          Personnel.ActivatePerson(Convert.ToInt32(e.CommandArgument));
          gvUsers.DataBind();
        }
     
        protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
          // if we're binding to a data row, manipulate the controls within
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
            // Get the Data Item
            UserSummary userSummary = (UserSummary)e.Row.DataItem;
            // Get the necessary controls
            Label labArchived = (Label)e.Row.FindControl("labArchived");
            Label labEstimatedDateOfDeparture = (Label)e.Row.FindControl("labEstimatedDateOfDeparture");
            HyperLink hlEditUser = (HyperLink)e.Row.FindControl("hlEditUser");
            Image imaEditUserFaded = (Image)e.Row.FindControl("imaEditUserFaded");
            ImageButton ibArchive = (ImageButton)e.Row.FindControl("ibArchive");
            Image imaArchiveFaded = (Image)e.Row.FindControl("imaArchiveFaded");
            ImageButton ibActivate = (ImageButton)e.Row.FindControl("ibActivate");
            Image imaActivateFaded = (Image)e.Row.FindControl("imaActivateFaded");
            ImageButton ibDelete = (ImageButton)e.Row.FindControl("ibDelete");
            Image imaDeleteFaded = (Image)e.Row.FindControl("imaDeleteFaded");
            CheckBoxButton cbDeleteUser = (CheckBoxButton)e.Row.FindControl("cbDeleteUser");
            Image imaCheckBoxFaded = (Image)e.Row.FindControl("imaCheckBoxFaded");
            Label labFullNameLastFirst = (Label)e.Row.FindControl("labFullNameLastFirst");
            Image imaEditor = (Image)e.Row.FindControl("imaEditor");
            Image imaManager = (Image)e.Row.FindControl("imaManager");
            Image imaAdministrator = (Image)e.Row.FindControl("imaAdministrator");
            Image imaSuperuser = (Image)e.Row.FindControl("imaSuperuser");
            Image imaWebmaster = (Image)e.Row.FindControl("imaWebmaster");
     
            // full name
            labFullNameLastFirst.Text = userSummary.FullNameLastFirst;
     
            // role
            switch (userSummary.Role)
            {
              case "Editor":
                imaEditor.Visible = true;
                imaEditor.ToolTip = userSummary.FirstName + " is an Editor.";
                break;
              case "Manager":
                imaManager.Visible = true;
                imaManager.ToolTip = userSummary.FirstName + " is a Manager.";
                break;
              case "Administrator":
                imaAdministrator.Visible = true;
                imaAdministrator.ToolTip = userSummary.FirstName + " is an Administrator.";
                break;
              case "Superuser":
                imaSuperuser.Visible = true;
                imaSuperuser.ToolTip = userSummary.FirstName + " is a Superuser.";
                break;
              case "Webmaster":
                imaWebmaster.Visible = true;
                imaWebmaster.ToolTip = userSummary.FirstName + " is a Webmaster.";
                break;
            }
     
            // set the Archived Timestamp field
            if (userSummary.ArchivedTimestamp != DateTime.MaxValue)
            {
              labArchived.Text = userSummary.ArchivedTimestamp.ToShortDateString();
            }
            else
            {
              labArchived.Text = String.Empty;
            }
     
            // estimated date of departure
            labEstimatedDateOfDeparture.Text = userSummary.EstimatedDateOfDeparture.ToShortDateString();
     
     
            // configure the edit user hyperlink
            hlEditUser.NavigateUrl = "~/admin/users/edituser/EditUserPersonal.aspx?PersonnelID=" + userSummary.PersonnelID;
     
            // if we're processing non-archived users
            if (!this.ShowingArchivedPersonnel)
            {
              // if we're processing ourself, fade the buttons
              if (userSummary.PersonnelID == this.CurrentUserPersonnelID)
              {
                // hide the appropriate buttons
                ibArchive.Visible = false;
                ibActivate.Visible = false;
                ibDelete.Visible = false;
                hlEditUser.Visible = false;
                cbDeleteUser.Visible = false;
                imaActivateFaded.Visible = false;
                // display the appropriate messages            
                imaEditUserFaded.ToolTip = "You cannot edit yourself.";
                imaDeleteFaded.ToolTip = "You cannot delete yourself.";
                imaArchiveFaded.ToolTip = "You cannot archive yourself.";
                imaCheckBoxFaded.ToolTip = "You cannot delete yourself.";
              }
              // if we're processing a user in a role greater than our own, fade the buttons
              else if (this.CompareRoles(this.CurrentUserRole, this.GetUserRole(userSummary.EID)) < 0)
              {
                // hide the appropriate buttons
                ibArchive.Visible = false;
                ibActivate.Visible = false;
                ibDelete.Visible = false;
                hlEditUser.Visible = false;
                cbDeleteUser.Visible = false;
                imaActivateFaded.Visible = false;
                // display the appropriate messages            
                imaEditUserFaded.ToolTip = "You cannot edit someone in a higher role than your own.";
                imaDeleteFaded.ToolTip = "You cannot delete someone in a higher role than your own.";
                imaArchiveFaded.ToolTip = "You cannot archive someone in a higher role than your own.";
                imaCheckBoxFaded.ToolTip = "You cannot delete someone in a higher role than your own.";
              }
              // if we're processing a privileged user (Editor & Above)
              else if (this.CompareRoles("Editor", this.GetUserRole(userSummary.EID)) <= 0)
              {
                // hide the appropriate buttons
                ibArchive.Visible = false;
                ibActivate.Visible = false;
                ibDelete.Visible = false;
                //hlEditUser.Visible = false;
                imaEditUserFaded.Visible = false;
                cbDeleteUser.Visible = false;
                imaActivateFaded.Visible = false;
                // display the appropriate messages            
                imaDeleteFaded.ToolTip = "You cannot delete privileged personnel.";
                imaArchiveFaded.ToolTip = "You cannot archive privileged personnel.";
                imaCheckBoxFaded.ToolTip = "You cannot delete privileged personnel.";
              }
              else
              {
                imaEditUserFaded.Visible = false;
                imaDeleteFaded.Visible = false;
                imaArchiveFaded.Visible = false;
                imaActivateFaded.Visible = false;
                ibActivate.Visible = false;
                imaCheckBoxFaded.Visible = false;
              }
            }
            else
            {
              ibArchive.Visible = false;
              imaArchiveFaded.Visible = false;
              imaDeleteFaded.Visible = false;
              imaActivateFaded.Visible = false;
              imaEditUserFaded.Visible = false;
              imaCheckBoxFaded.Visible = false;
            }
     
     
            // add some command variables
            cbDeleteUser.CommandArgument = ((UserSummary)e.Row.DataItem).PersonnelID.ToString();
     
            // if this person works in the root, MARFORRES unit, we need to manually plug-in the root
            // name so that people will be aware of where they work
            if (userSummary.CommandHierarchyNodeID == CommandHierarchyNode.GetCommandHierarchyRootNode().NodeID)
            {
              TableCell commandCell = e.Row.Cells[3];
              TableCell departmentCell = e.Row.Cells[4];
              TableCell sectionCell = e.Row.Cells[5];
              commandCell.ColumnSpan = 3;
              commandCell.Text = "MARFORRES root";
              commandCell.Attributes["style"] = "font-style:italic;";
              departmentCell.Visible = false;
              sectionCell.Visible = false;
     
            }
     
          }
          else if (e.Row.RowType == DataControlRowType.EmptyDataRow)
          {
            Label labNoPersonnel = (Label)e.Row.FindControl("labNoPersonnel");
            if (this.ShowingArchivedPersonnel)
            {
              labNoPersonnel.Text = "There are no archived personnel to display.";
            }
            else
            {
              labNoPersonnel.Text = "There are no personnel to display.";
            }
     
          }
     
        }
     
        protected void gvUsers_DataBound(object sender, EventArgs e)
        {
          // hide the archived date if we're not viewing archived personnel
          if (this.ShowingArchivedPersonnel == false)
          {
            gvUsers.Columns[7].Visible = false;
          }
          else
          {
            gvUsers.Columns[7].Visible = true;
          }
        }
     
        protected void lbDeleteCheckedUsers_Click(object sender, EventArgs e)
        {
          foreach(GridViewRow row in gvUsers.Rows)  
          {
            CheckBoxButton cbDeleteUser = (CheckBoxButton)row.FindControl("cbDeleteUser");
            if(cbDeleteUser.Checked) 
            {
              if (cbDeleteUser.CommandArgument != String.Empty)
              {
                // Delete the user from the membership system
                Membership.DeleteUser(Personnel.GetPersonnelEID(int.Parse(cbDeleteUser.CommandArgument)));
                // Delete the user from the DB
                Personnel.DeletePerson(int.Parse(cbDeleteUser.CommandArgument));
              }
            }
          }
          //BindPagedData(usUnitSelector.SelectedNodeID, this.PersonnelState, gvUsers.PageIndex, int.Parse(ddlPageSize.SelectedValue));
          gvUsers.PageIndex = 0;
          gvUsers.DataBind();
        }
     
        protected void lbPersonnelState_Click(object sender, EventArgs e)
        {
          LinkButton clickedLinkButton = (LinkButton)sender;
          switch (clickedLinkButton.CommandArgument)
          {
            case "Active":
              this.ShowingArchivedPersonnel = false;
              // set the proper class on the tab
              lbArchived.CssClass = String.Empty;
              lbActive.CssClass = "here";
              // show/hide the appropriate message
              //labActive.Visible = true;
              //labArchived.Visible = false;
              // bind the gridview
              gvUsers.PageIndex = 0;
              gvUsers.DataBind();
              break;
            case "Archived":
              this.ShowingArchivedPersonnel = true;
              //BindPagedData(usUnitSelector.SelectedNodeID, this.PersonnelState, gvUsers.PageIndex, int.Parse(ddlPageSize.SelectedValue));
              // set the proper class on the tab
              //lbActive.Attributes.Clear();
              lbActive.CssClass = String.Empty;
              lbArchived.CssClass = "here";
              // show/hide the appropriate message
              //labActive.Visible = false;
              //labArchived.Visible = true;
              // bind the gridview
              gvUsers.PageIndex = 0;
              gvUsers.DataBind();
              break; 
          }
        }
     
     
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
          if (ddlPageSize.SelectedValue != "0")
          {
            gvUsers.AllowPaging = true;
            gvUsers.PageSize = int.Parse(ddlPageSize.SelectedValue);
            gvUsers.PageIndex = 0;
          }
          else
          {
            gvUsers.AllowPaging = false;
          }
          gvUsers.DataBind();
        }
     
        protected void odsUserSummaries_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
          e.InputParameters["StartingNodeID"] = usUnitSelector.SelectedNodeID;
          e.InputParameters["Archived"] = this.ShowingArchivedPersonnel;
        }
     
     
        protected void odsUserSummaries_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
          //int summaries = Convert.ToInt32(e.ReturnValue);
          if(e.ReturnValue.GetType() == typeof(List<UserSummary>))  
          {
            int firstRecord = 0;
            int lastRecord = 0;
            int totalRecords = 0;
     
            List<UserSummary> summaries = (List<UserSummary>)e.ReturnValue;
            totalRecords = summaries.Count;
     
            //if (totalRecords < 10)
            //{
            //  ddlPageSize.Visible = false;
            //  litRecordsPerPage.Visible = false;
            //}
            //else
            //{
            //  ddlPageSize.Visible = true;
            //  litRecordsPerPage.Visible = true;
            //}
     
            if (totalRecords > 0)
            {
              gridControls.Visible = true;
              if (gvUsers.AllowPaging == true)
              {
                // First Record
                firstRecord = gvUsers.PageSize * gvUsers.PageIndex + 1;
                labFirstRecord.Text = firstRecord.ToString();
                // Last Record
                lastRecord = firstRecord + totalRecords - 1;
                //int lastRecord = firstRecord + gvUsers.PageSize - 1;
                labLastRecord.Text = lastRecord.ToString();
                // Total Records
                totalRecords = UserSummary.GetUserSummaryCount(usUnitSelector.SelectedNodeID, this.ShowingArchivedPersonnel);
                labTotalRecords.Text = totalRecords.ToString();
              }
              else
              {
                labFirstRecord.Text = "1";
                labLastRecord.Text = totalRecords.ToString();
                labTotalRecords.Text = totalRecords.ToString();
              }
            }
            else
            {
              gridControls.Visible = false;
            }
     
     
          }
     
        }
     
     
        protected void gvUsers_Init(object sender, EventArgs e)
        {
          gvUsers.Sort("Name", SortDirection.Ascending);
        }
     
     
        protected void lbExport_Click(object sender, EventArgs e)
        {
          Workbook book = new Workbook();
     
          // Specify which Sheet should be opened and the size of window by 
          book.ExcelWorkbook.ActiveSheetIndex = 1;
          book.ExcelWorkbook.WindowTopX = 100;
          book.ExcelWorkbook.WindowTopY = 200;
          book.ExcelWorkbook.WindowHeight = 7000;
          book.ExcelWorkbook.WindowWidth = 8000;
     
          // Some optional properties of the Document
          book.Properties.Author = "ePAS Application";
          book.Properties.Title = "Manage Users";
          book.Properties.Created = DateTime.Now;
     
          // Create the Default Style for all cells
          WorksheetStyle defaultStyle = book.Styles.Add("DefaultStyle");
          defaultStyle.Font.FontName = "Tahoma";
          defaultStyle.Font.Size = 10;
          defaultStyle.Borders.Add(StylePosition.Top, LineStyleOption.Continuous, 1);
          defaultStyle.Borders.Add(StylePosition.Right, LineStyleOption.Continuous, 1);
          defaultStyle.Borders.Add(StylePosition.Bottom, LineStyleOption.Continuous, 1);
          defaultStyle.Borders.Add(StylePosition.Left, LineStyleOption.Continuous, 1);
     
          // Create the Title Style
          WorksheetStyle titleStyle = book.Styles.Add("TitleStyle");
          titleStyle.Font.Size = 14;
          titleStyle.Font.Bold = true;
          titleStyle.Alignment.Horizontal = StyleHorizontalAlignment.Center;
          titleStyle.Font.Color = "Black";
          titleStyle.Interior.Color = "#aaaaaa";
          titleStyle.Interior.Pattern = StyleInteriorPattern.Solid;
          titleStyle.Borders.Add(StylePosition.Top, LineStyleOption.Continuous, 1);
          titleStyle.Borders.Add(StylePosition.Right, LineStyleOption.Continuous, 1);
          titleStyle.Borders.Add(StylePosition.Bottom, LineStyleOption.Continuous, 1);
          titleStyle.Borders.Add(StylePosition.Left, LineStyleOption.Continuous, 1);
     
          // Create the Header Style
          WorksheetStyle headerStyle = book.Styles.Add("HeaderStyle");
          headerStyle.Font.FontName = "Tahoma";
          headerStyle.Font.Size = 10;
          headerStyle.Font.Bold = true;
          headerStyle.Alignment.Horizontal = StyleHorizontalAlignment.Center;
          headerStyle.Font.Color = "Black";
          headerStyle.Interior.Color = "#cccccc";
          headerStyle.Interior.Pattern = StyleInteriorPattern.Solid;
          headerStyle.Borders.Add(StylePosition.Top, LineStyleOption.Continuous, 1);
          headerStyle.Borders.Add(StylePosition.Right, LineStyleOption.Continuous, 1);
          headerStyle.Borders.Add(StylePosition.Bottom, LineStyleOption.Continuous, 1);
          headerStyle.Borders.Add(StylePosition.Left, LineStyleOption.Continuous, 1);
     
          // Create an Italic Style
          WorksheetStyle italicStyle = book.Styles.Add("ItalicStyle");
          italicStyle.Font.Italic = true;
          italicStyle.Borders.Add(StylePosition.Top, LineStyleOption.Continuous, 1);
          italicStyle.Borders.Add(StylePosition.Right, LineStyleOption.Continuous, 1);
          italicStyle.Borders.Add(StylePosition.Bottom, LineStyleOption.Continuous, 1);
          italicStyle.Borders.Add(StylePosition.Left, LineStyleOption.Continuous, 1);
     
     
     
          Worksheet sheet = book.Worksheets.Add("Manage Users");
     
          sheet.Table.Columns.Add(new WorksheetColumn(90));
          sheet.Table.Columns.Add(new WorksheetColumn(75));
          sheet.Table.Columns.Add(new WorksheetColumn(40));
          sheet.Table.Columns.Add(new WorksheetColumn(40));
          sheet.Table.Columns.Add(new WorksheetColumn(60));
          sheet.Table.Columns.Add(new WorksheetColumn(110));
          sheet.Table.Columns.Add(new WorksheetColumn(110));
          sheet.Table.Columns.Add(new WorksheetColumn(60));
     
     
          WorksheetRow titleRow = sheet.Table.Rows.Add();
     
          string personnelState = String.Empty;
          switch (this.ShowingArchivedPersonnel)
          {
            case false:
              personnelState = "Active";
              break;
            case true:
              personnelState = "Archived";
              break;
          }
          WorksheetCell titleCell = titleRow.Cells.Add("Manage Users (" + personnelState + ")  -  " + DateTime.Now.ToString("d") + " " + DateTime.Now.ToString("HH:mm"));
          titleCell.MergeAcross = 7;
          titleCell.StyleID = "TitleStyle";
     
     
     
          WorksheetRow row = sheet.Table.Rows.Add();
          row.Cells.Add(new WorksheetCell("Last Name", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("First Name", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Middle", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Rank", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Command", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Department", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Section", "HeaderStyle"));
          row.Cells.Add(new WorksheetCell("Est. DOD", "HeaderStyle"));
     
          List<UserSummary> summaries = new List<UserSummary>();
          int firstRecord = gvUsers.PageSize * gvUsers.PageIndex + 1;
          if (ddlPageSize.SelectedValue != "0")
          {
            summaries = UserSummary.GetUserSummaries(usUnitSelector.SelectedNodeID, this.ShowingArchivedPersonnel, firstRecord, gvUsers.PageSize, gvUsers.SortExpression);
          }
          else
          {
            summaries = UserSummary.GetUserSummaries(usUnitSelector.SelectedNodeID, this.ShowingArchivedPersonnel, firstRecord, 0, gvUsers.SortExpression);
          }
     
     
          for (int i = 0; i < summaries.Count; i++)
          {
            row = sheet.Table.Rows.Add();
            // Name
            row.Cells.Add(new WorksheetCell(summaries[i].LastName, "DefaultStyle"));
            row.Cells.Add(new WorksheetCell(summaries[i].FirstName, "DefaultStyle"));
            row.Cells.Add(new WorksheetCell(summaries[i].MiddleInitial, "DefaultStyle"));
            // Rank
            row.Cells.Add(new WorksheetCell(summaries[i].Rank, "DefaultStyle"));
            // Command
            if (summaries[i].Command != String.Empty)
            {
              row.Cells.Add(new WorksheetCell(summaries[i].Command, "DefaultStyle"));
              // Department
              row.Cells.Add(new WorksheetCell(summaries[i].Department, "DefaultStyle"));
              // Section
              row.Cells.Add(new WorksheetCell(summaries[i].Section, "DefaultStyle"));
            }
            else
            {
              WorksheetCell cell = row.Cells.Add("MARFORRES root");
              cell.MergeAcross = 2;
              cell.StyleID = "ItalicStyle";
              //row.Cells.Add(cell);
            }
            // Estimated Date of Departure
            row.Cells.Add(new WorksheetCell(summaries[i].EstimatedDateOfDeparture.ToShortDateString(), "DefaultStyle"));
          }
     
          //string fileLocation = HttpContext.Current.Server.MapPath("~/exports");
          //fileLocation += "\\Manage Users.xls";
          //string fileLocation = "C:\\TEMP\\Manage Users.xls";
          //string fileLocation = "C:\\Brad\\work\\Projects\\ePAS\\Applications\\EPAS\\EPAS_Web\\exports\\Manage Users.xls";
          //book.Save(fileLocation);
     
     
          Response.ContentType = "application/vnd.ms-excel";
          Response.Charset = String.Empty;
          Page.EnableViewState = false;
          Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
          Response.Clear();
          book.Save(Response.OutputStream);
        }
     
      }
    }

  2. #2
    SitePoint Evangelist
    Join Date
    Apr 2008
    Location
    Dublin, Ireland
    Posts
    461
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Response.End?

  3. #3
    SitePoint Mentor NightStalker-DNS's Avatar
    Join Date
    Jul 2004
    Location
    Cape Town, South Africa
    Posts
    2,880
    Mentioned
    48 Post(s)
    Tagged
    0 Thread(s)
    I agree. Response.End() should do the trick after your save method call. Basically tells the response to stop after this and not carry on.

  4. #4
    SitePoint Guru pinch's Avatar
    Join Date
    Mar 2005
    Posts
    688
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That was way too simple, especially after I spent 4 hours yesterday creating an elaborate solution to the problem. Thanks.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •