Pages

Free Hosting

Monday, October 17, 2011

ASP.NET code for downloading files.


First create a DataGrid in your asp designer page. Add a Hyper link field to which files to be associated with  & all other setting as bellow.

<asp:DataGrid ID="fileload" runat="server" AutoGenerateColumns="False">

        <Columns>

            <asp:HyperLinkColumn DataNavigateUrlField="Name"

                DataNavigateUrlFormatString="FetchFile.aspx?FileName={0}" DataTextField="Name"

                HeaderText="File Name:" SortExpression="Name"></asp:HyperLinkColumn>

        </Columns>

   

    </asp:DataGrid>

Look above, in order fetch files from the directory another asp page fetch.aspx is refered in the DataNavigateUrlFormatString of the hyperlink column field. So create another asp page as ‘FetchFile.aspx’  & add the following code in the page load event.

string dlDir = "downloadfiles/";

        string strFilename = Request.QueryString["Filename"];

        string path=Server.MapPath(dlDir+strFilename);

        System.IO.FileInfo toDownload = new FileInfo(path);



        if (toDownload.Exists)

        {

            Response.Clear();

            Response.AddHeader("Content-Disposition", "attachment;filename=" + toDownload.Name);

            Response.AddHeader("Content-Length", toDownload.Length.ToString());

            Response.ContentType = "application/octet-stream";

            Response.WriteFile(toDownload.FullName);

            Response.End();

        }

Then come into the main asp coding page where DataGrid was created earlier & write the following code into the page loade event.



string folder = Server.MapPath("downloadfiles/");

        //Get the files by using directoryInfo class of system.IO assembly

        DirectoryInfo di = new DirectoryInfo(folder);

        FileInfo[] fri = di.GetFiles();

        int countfile = fri.Count();

        //Create a table & bind the file names into cells.

        System.Data.DataTable table = new System.Data.DataTable();

        DataColumn column;

        DataRow row;

        column = new DataColumn();

        column.ColumnName = "Name";

        column.DataType = System.Type.GetType("System.String");



        table.Columns.Add(column);

       

        for (int i = 0; i <countfile; i++)

        {

            row = table.NewRow();

            row["Name"] = fri[i].Name.ToString();

            table.Rows.Add(row);

        }

        //bind the table data to the data grid in designer page

        fileload.DataSource = table;
        fileload.DataBind();
build the solution & run your main asp page. Your Data Grid will be filled with the downloadable file lists. Click any file among of them & watch your downloading.

Passing Array from server to client


This is a frequent requirement for an ASP.NET developer to pass a server side array to client side and access them through JavaScript. There are several ways to do that. But here I am describing one of the simplest steps to pass server side array to client side. In this blog post, you will get to know two things, the first one is how to pass the array from server side to client side and the second one is how to bind that array to an empty “html dropdown” list.

Well, the easiest way to pass the server side array to a client side is by using “RegisterArrayDeclaration”.RegisterArrayDeclaration method registers a JavaScript array with the System.Web.UI.Page object. As the array object is registered with the “Page" object, we can access it from JavaScript easily.RegisterArrayDeclaration takes array name and value of the array element as arguments.

In the below example, I have registered one array with the name of “Skills”.

 

  protected void Page_Load(object sender, EventArgs e)
    {
       // Register List of Languages
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C#'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'VB.NET'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C++'");
    }

Now, what does the above declaration do? This is nothing but a declaration of a JavaScript array like:



Var Skills = new Array('C#', 'VB.NET','C','C++');

This “Skills” array is now only a JavaScript array which is easily accessible by client side code. Now let’s take a look at how to access them and how to bind them in a dropdown list. 
In my form, I have an HTML
 select element and one HTML Button. I want my server side (which is now a client side) array to bind in the dropdown list.


  <select id="ddlNames" name="D1">
    </select><input id="BtnNameLoad" type="button"
         value="Load Name" onclick="return BtnNameLoad_onclick()" />


Below is the code snippet for binding the array to HTML control:



function BtnNameLoad_onclick() {

            //Get The Control ID for the dropdown
            var listID = document.getElementById("ddlNames");
            //Check if the object is not null
            if (listID != null) {
                for (var i = 0; i < Skills.length; i++) {
                   // Create and Element Object of type "option"
                    var opt = document.createElement("option");
                    //Add the option element to the select item
                    listID.options.add(opt);
                    //Reading Element From Array
                    opt.text = Skills[i];
                }
            }
        }

Displaying Festival Names on Calendar control in ASP.Net

Tags : Festival Names,Calendar Control,Importance of the day,Asp.Net,C#.Net,SQL Server.

Hi Friends,In this article i would like to explain how to display Festival Names on Calender control in ASP.Net.


* For this i took 1 Calendar control on to the page.

* I created a table with name(Holidays) in SQL Server 2005 & fields are HolidayName,HolidayDate.

* Please find the below table once :



* Then find the code for Calender_DayRender event :

Source Code :

Default.aspx.cs :
1.  using System; 
2.  using System.Configuration; 
3.  using System.Data; 
4.  using System.Linq; 
5.  using System.Web; 
6.  using System.Web.Security; 
7.  using System.Web.UI; 
8.  using System.Web.UI.HtmlControls; 
9.  using System.Web.UI.WebControls; 
10. using System.Web.UI.WebControls.WebParts; 
11. using System.Xml.Linq; 
12. using System.Data.SqlClient; 
13. public partial class _Default : System.Web.UI.Page 
14. { 
15. SqlConnection con; 
16. protected void Page_Load(object sender, EventArgs e) 
17. { 
18.  con = new SqlConnection(ConfigurationManager.ConnectionStrings["DotnetGuruConnectionString"].ConnectionString); 
19. } 
20. protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) 
21. { 
22.  CalendarDay day = (CalendarDay)e.Day; 
23.  SqlCommand cmd = new SqlCommand("select HolidayName,HolidayDate from Holidays", con); 
24.  con.Open(); 
25.  SqlDataReader dr = cmd.ExecuteReader(); 
26.   
27.  while (dr.Read()) 
28.  { 
29.      if (day.Date.ToString() == dr["HolidayDate"].ToString()) 
30.      { 
31.          TableCell cell = (TableCell)e.Cell; 
32.          string s1 = dr["HolidayName"].ToString(); 
33.          if (s1 != null) 
34.          { 
35.              cell.BackColor = System.Drawing.Color.LightGray; 
36.              cell.Controls.Add(new LiteralControl(" 
37. " + s1)); 
38.          } 
39.   
40.      } 
41.   
42.  } 
43.  con.Close(); 
44. } 
45. } 

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
 con = new SqlConnection(ConfigurationManager.ConnectionStrings["DotnetGuruConnectionString"].ConnectionString);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
 CalendarDay day = (CalendarDay)e.Day;
 SqlCommand cmd = new SqlCommand("select HolidayName,HolidayDate from Holidays", con);
 con.Open();
 SqlDataReader dr = cmd.ExecuteReader();

 while (dr.Read())
 {
     if (day.Date.ToString() == dr["HolidayDate"].ToString())
     {
         TableCell cell = (TableCell)e.Cell;
         string s1 = dr["HolidayName"].ToString();
         if (s1 != null)
         {
             cell.BackColor = System.Drawing.Color.LightGray;
             cell.Controls.Add(new LiteralControl("
" + s1));
         }

     }

 }
 con.Close();
}
}
Design View :

Default.aspx :

 
1.  <FORM id=form1 runat="server"> 
2.  <DIV> 
3.    
4.      <ASP:CALENDAR id=Calendar1 size="8pt" width="300px" runat="server" showgridlines="True" height="200px" forecolor="#663399" names="Verdana" daynameformat="Shortest" borderwidth="1px" bordercolor="#FFCC66" backcolor="#FFFFCC" ondayrender="Calendar1_DayRender"> 
5.          <SELECTEDDAYSTYLE backcolor="#CCCCFF" bold="True"> 
6.          <SELECTORSTYLE backcolor="#FFCC66"> 
7.          <TODAYDAYSTYLE forecolor="White" backcolor="#FFCC66"> 
8.          <OTHERMONTHDAYSTYLE forecolor="#CC9966"> 
9.          <NEXTPREVSTYLE size="9pt" forecolor="#FFFFCC"> 
10.         <DAYHEADERSTYLE height="1px" backcolor="#FFCC66" bold="True"> 
11.         <TITLESTYLE size="9pt" forecolor="#FFFFCC" backcolor="#990000" bold="True"> 
12.     </TITLESTYLE> 
13.   
14. </DAYHEADERSTYLE></NEXTPREVSTYLE></OTHERMONTHDAYSTYLE></TODAYDAYSTYLE></SELECTORSTYLE></SELECTEDDAYSTYLE></ASP:CALENDAR></DIV> 
15. </FORM> 
<SPAN style="COLOR: rgb(51,51,255); FONT-SIZE: 130%; FONT-WEIGHT: bold"></SPAN>