How to read mail from gmail in asp.net

7:23:00 am 0 Comments

In this post,I will show you how to read mail from gmail in asp.net
aspdotnetcodebook
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        UserName :
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
        Password:
        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox><br />
        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /><br />
        <asp:GridView ID="grdMail" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.Xml.Linq;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        XNamespace ns = "http://purl.org/atom/ns#";
        string userName = txtUserName.Text;
        string password = txtPassword.Text;
        string gmailFeedUrl = @"https://mail.google.com/mail/feed/atom ";
        WebClient client = new WebClient();
        string credential = string.Format("{0}:{1}", userName, password);
        string auth = "Basic" + Convert.ToBase64String(Encoding.ASCII.GetBytes(credential));
        client.Headers.Add("Authorization", auth);
        var inboxXml = client.DownloadString(gmailFeedUrl);
        var xml = XDocument.Parse(inboxXml);
        var query = from entry in xml.Descendants(ns + "entry")
                    select new
                    {
                        Title = entry.Element(ns + "title").Value,
                        Author = entry.Element(ns + "author").Element(ns + "name").Value,
                    };
        grdMail.DataSource = query;
        grdMail.DataBind();
    }
}

0 comments:

How to display a serial number from 1 to n in a grid view






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Paging.aspx.cs" Inherits="Paging" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
             PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging">
             <Columns>
                 <asp:BoundField DataField="LastName" HeaderText="Name" />
                 <asp:BoundField DataField="Lectures" HeaderText="Lectures" />
                 <asp:TemplateField HeaderText="S.No">
                 
                     <ItemTemplate>
                         <asp:Label ID="Label1" runat="server" Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'></asp:Label>
                     </ItemTemplate>
                 </asp:TemplateField>
             </Columns>
         </asp:GridView>
     </div>
 </form>
</body>
</html>

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;

public partial class Paging : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {
          GridView1.DataSource = GetDataTable();
          GridView1.DataBind();

      }
  }
  protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
      GridView1.PageIndex = e.NewPageIndex;
 
      GridView1.DataSource = GetDataTable();
      GridView1.DataBind();
  }
  private DataTable GetDataTable()
  {
      //create table
      DataTable dt = new DataTable("Members");
      dt.Columns.Add("ID", Type.GetType("System.Int32"));
      dt.Columns.Add("LastName", Type.GetType("System.String"));
      dt.Columns.Add("Lectures", Type.GetType("System.Int32"));

      //create fields
      DataColumn[] pk = new DataColumn[1];
      pk[0] = dt.Columns["ID"];
      dt.PrimaryKey = pk;
      dt.Columns["ID"].AutoIncrement = true;
      dt.Columns["ID"].AutoIncrementSeed = 1;
      dt.Columns["ID"].ReadOnly = true;

      //fill rows
      DataRow dr;
      for (int x = 1; x <= 10; x++)
      {
          //make every other one different
          if (Math.IEEERemainder(x, 2) == 0)
          {
              dr = dt.NewRow();
              dr["LastName"] = "Riss";
              dr["Lectures"] = 14;
              dt.Rows.Add(dr);
          }
          else
          {
              dr = dt.NewRow();
              dr["LastName"] = "Anders";
              dr["Lectures"] = 3;
              dt.Rows.Add(dr);

          }
      }

      return dt;
  }
}
*
create a template field, in that item template, put a label, specify it's text as
Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'

2 comments:

Select a row in an asp:GridView without using a Select Command

7:16:00 am 0 Comments





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SelectRow.aspx.cs" Inherits="SelectRow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
               Width="200px" AllowPaging="True" OnRowDataBound="PeopleGridView_RowDataBound">
               <Columns>
                   <asp:BoundField DataField="StringField" HeaderText="Name" SortExpression="StringField">
                   </asp:BoundField>
               </Columns>
           </asp:GridView>
       </div>
   </form>
</body>
</html>

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;

public partial class SelectRow : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetDataSet();
            GridView1.DataBind();
        }

    }
    public DataTable GetDataSet()
    {

        DataTable dt = new DataTable("Company");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
        dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringField", typeof(string)));
        for (int i = 0; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i;
            dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
            dt.Rows.Add(dr);
            DataColumn[] Parent_PKColumns = new DataColumn[1];
            Parent_PKColumns[0] = dt.Columns["ID"];
            dt.PrimaryKey = Parent_PKColumns;
            Session["DataSource"] = dt;
        }

        return dt;
    }
    protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
        }

    }
}

0 comments:

Programmatically adding LINKs to HTML HEADER in Code Behind

7:15:00 am 0 Comments

In this example I am adding a link to the html header pointing to an rss feed.
HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "application/rss+xml");
link.Attributes.Add("rel", "alternate");
link.Attributes.Add("href", Page.ResolveClientUrl("~/rss/LatestArticles/"));
this.Header.Controls.Add(link);

0 comments:

How To Convert HTML to Text, Easily

7:12:00 am 0 Comments


Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy.
It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:

<%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs"
 Inherits="StripTag" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <asp:TextBox ID="TextBox1" runat="server" Height="172px" Width="363px" TextMode="MultiLine"></asp:TextBox></div>
     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
 </form>
</body>
</html>


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;

public partial class StripTag : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {


   }
   public string StripTags(string HTML)
   {
       // Removes tags from passed HTML 
       return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "");
   }


   protected void Button1_Click(object sender, EventArgs e)
   {
       Label1.Text = StripTags(TextBox1.Text);

   }
}

0 comments:

Filling typed dataset programmatically

7:11:00 am , 0 Comments

Filling a typed dataset works just like filling an untyped dataset. You create a data adapter, assign the SelectCommand, and call Fill(). The only real trick is to get the table and field names right. A DataAdapeter will generate table names for each distinct result set generated by the SelectCommand. The names will be "Table", "Table1", "Table2", etc. If you call the overloaded Fill() method which takes a table name parameter, the generated names will follow the same pattern, except your table name will be used instead of "Table". Once the data adapter has generated the table names, it will look for matching table names in your data set. The data is then mapped to the matching column names in the matching tables. As long as the SelectCommand returns the proper column names, the data will populate as you would expect. Some things to beware of: * You will *not* get errors if the table or column names are wrong. If the Data Adapter can't find a given table, it would normally add a new table to your dataset. For typed data sets, things are slightly different. You won't get an exception in this case, but you also wont' get your data. This includes both misnamed tables *and* misnamed columns -- the data is simply discarded if it can't be fit into your schema. * If your SelectCommand returns multiple result sets, you will almost certainly need to map the resulting table names to those in your dataset. The table names need to be mapped in the order they are returned by the SelectCommand, and the code looks something like this (assume the dataset has three tables: MyTable, MyOtherTable, MyThirdTable):
SqlCommand cmd = new SqlCommand("multi_recordset_proc", new SqlConnection("your con. string"));

          cmd.CommandType = CommandType.StoredProcedure;

          SqlDataAdapter da = new SqlDataAdapter(cmd);
          da.TableMappings("MyTable1", "MyOtherTable");
          da.TableMappings("MyTable2", "MyThirdTable");
          da.Fill(dataset, "MyTable");
* If you have relationships in your dataset, they will be enforced during the Fill. I beleive this is done on a per-table basis, that is, the contraints for a given table are disabled, data is populated, and the constraints are enabled. If you populate a table before populating parent tables, you will generate an error. You can get around this problem by being careful of the order you populate tables. Alternatively, you can do:
ds.EnforceConstraints = false;
           da.Fill(ds, "Table");
           ds.EnforceConstraints = true;

0 comments:

how to convert web page to pdf

7:09:00 am 0 Comments



In this post i will show how to convert web page to pdf using iTextSharp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Pdf.aspx.cs" Inherits="Pdf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceholderPdf" runat="server"></asp:PlaceHolder>
    <div>
        <table border="1">
            <tr>
                <td colspan="2">
                    aspdotnetcodebook
                </td>
            </tr>
            <tr>
                <td>
                    cell1
                </td>
                <td>
                    cell2
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblLabel" runat="server" Text="Label Test"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
    protected override void Render(HtmlTextWriter writer)
    {
        MemoryStream mem = new MemoryStream();
        StreamWriter twr = new StreamWriter(mem);
        HtmlTextWriter myWriter = new HtmlTextWriter(twr);
        base.Render(myWriter);
        myWriter.Flush();
        myWriter.Dispose();
        StreamReader strmRdr = new StreamReader(mem);
        strmRdr.BaseStream.Position = 0;
        string pageContent = strmRdr.ReadToEnd();
        strmRdr.Dispose();
        mem.Dispose();
        writer.Write(pageContent);
        CreatePDFDocument(pageContent);


    }
    public  void CreatePDFDocument(string strHtml)
    {

        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
        StringReader se = new StringReader(strHtml);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        document.Close();
        ShowPdf(strFileName);
     
   
     
    }
    public void ShowPdf(string strFileName)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
        Response.ContentType = "application/pdf";
        Response.WriteFile(strFileName);
        Response.Flush();
        Response.Clear();
    }
}

0 comments:

Asynchronous GridView in 5 simple steps



A web page with a data bound GridView control can take a long time to load. The page is not rendered until all the controls are, and the GridView cannot render before data has been retrieved from the database. So, let’s load the GridView asynchronous and make the page load faster and the perceived speed greater.
This little trick is actually very simple and it involves the built-in client callback feature of ASP.NET. Even though I’m not a big fan of that particular feature, it can be quite handy from time to time. The best part of this is that you don’t have to change much to your existing code.

Web page

On the webpage that hosts the GridView control, you have to make 2 small changes.
Step 1. Encapsulate the GridView The GridView control has to be encapsulated by an HTML control with an id attribute, so that it can be referenced by JavaScript. That is because the GridView does not render when no data is bound to it.

"grid"> Loading... "Server" ID="gvAsync" />
Step 2. Add a JavaScript Then a JavaScript is needed to load the rendered and data bound GridView to the HTML control we added in step 1. Place the JavaScript below the GridView’s surrounding div tag.

Code-behind

In the code-behind file there are three small steps to perform.
Step 3. Implement ICallbackEventHandler We need to implement the interface to turn on the client callback feature.
public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler
Step 4. Bind the call back reference The literal control placed in the JavaScript function in step 2 has to contain the client callback reference. Add the following to the Page_Load.
if (!Page.IsCallback) ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
Step 5. Bind the grid and return the rendered HTML To finish the asynchronous loading we have to implement the two methods that are defined by the ICallbackEventHandler interface we implemented in step 3. One of the methods binds a DataTable to the GridView and renders the control. The second returns the rendered HTML to the JavaScript method we defined in step 2.
private string _Callback; public string GetCallbackResult() { return _Callback; } public void RaiseCallbackEvent(string eventArgument) { DataTable table = RetrieveDataTableFromDatabase(); gvAsync.DataSource = table; gvAsync.DataBind(); using (System.IO.StringWriter sw = new System.IO.StringWriter()) { gvAsync.RenderControl(new HtmlTextWriter(sw)); _Callback = sw.ToString(); } }
You can use your present data binding method to bind the GridView. The important part is that the GridView is data bound before the RaiseCallbackEvent method renders the control.
The same technique can be used for all the data control such as the Repeater, FormView and DataList.




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="asyncgridview.aspx.cs" Inherits="asyncgridview" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Async GridView</title>
</head>
<body>
<form id="form1" runat="server">

<div id="grid">
  <span>Loading...</span>
  <asp:GridView runat="Server" ID="gvAsync" />
</div>

<script type="text/javascript"> 
  function EndGetData(arg)
  {
    document.getElementById("grid").innerHTML = arg;
  }

  setTimeout("<asp:literal runat="server" id="ltCallback" />", 100);
</script>

</form>
</body>
</html>
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler
{
  protected void Page_Load(object sender, EventArgs e)
  {
      System.Threading.Thread.Sleep(5000);
    if (!Page.IsCallback)
      ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
  }

  private DataTable RetrieveDataTableFromDatabase()
  {
    DataTable table = new DataTable();
    table.Columns.Add("Product", typeof(string));
    table.Columns.Add("Price", typeof(float));

    table.Rows.Add("Hat", 16);
    table.Rows.Add("Jacket", 234);
    table.Rows.Add("Socks", 35);

    return table;
  }

  #region ICallbackEventHandler Members

  private string _Callback;

  public string GetCallbackResult()
  {
    return _Callback;
  }

  public void RaiseCallbackEvent(string eventArgument)
  {
    DataTable table = RetrieveDataTableFromDatabase();
    gvAsync.DataSource = table;
    gvAsync.DataBind();

    using (System.IO.StringWriter sw = new System.IO.StringWriter())
    {
      gvAsync.RenderControl(new HtmlTextWriter(sw));
      _Callback = sw.ToString();
    }
  }

  #endregion
}

0 comments:

How To Create A Filebrowser in ASP

7:08:00 am 0 Comments





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileBrowser.aspx.cs" Inherits="FileBrowser" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <h1 class="boxes">
              Files on the Server:
              <asp:Literal ID="litLocation" runat="server" />
          </h1>
          <asp:Panel ID="panFiles" runat="server" CssClass="boxes">
              <asp:PlaceHolder ID="myPlaceHolder" runat="server" />
          </asp:Panel>
          <asp:Panel ID="Panel1" runat="server" CssClass="boxes">
              <asp:TextBox ID="txtFolder" runat="server"></asp:TextBox>
              <asp:Button ID="btnNewFolder" runat="server" Text="Create New Folder" OnClick="btnNewFolder_Click" />
          </asp:Panel>
          <asp:Panel ID="panUpload" runat="server" CssClass="boxes">
              Choose a file to upload to the server<br />
              <asp:FileUpload ID="fupTest" runat="server" Width="400px" />
              <br />
              <asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
              <p>
                  <asp:Label ID="labMessage" runat="server"></asp:Label>
              </p>
          </asp:Panel>
      </div>
  </form>
</body>
</html>

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 System.IO;

public partial class FileBrowser : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       string currentRoot = RetrievePathOfFolderToDisplay();
       litLocation.Text = currentRoot;
       GenerateListing(currentRoot);
   }
   /// <summary>
   /// Displays the content of the specified folder.
   /// </summary>
   private void GenerateListing(string rootpath)
   {
       // First clear out the place holder
       myPlaceHolder.Controls.Clear();
       // Calculate the path to retrieve folders + files
       string path = Server.MapPath("") + "/" + rootpath;
       // Make the "go up a level" link if needed
       MakeUpOneLevelLink(rootpath);
       // Get a list of all folders
       DirectoryInfo dirInfo = new DirectoryInfo(path);
       DirectoryInfo[] folders = dirInfo.GetDirectories();
       // Loop through each folder and display it
       foreach (DirectoryInfo folder in folders)
       {
           DisplayFolder(folder, rootpath);
       }
       // Get a list of all the files in current path
       FileInfo[] files = dirInfo.GetFiles();
       // Loop through each file
       foreach (FileInfo file in files)
       {
           DisplayFile(file, rootpath);
       }
   }
   /// <summary>
   /// Retrieves the path of the folder to be displayed
   /// </summary>
   /// 
   private string RetrievePathOfFolderToDisplay()
   {
       string localpath = Request.QueryString["local"];
       // If no query string, use uploads folder as the root
       if (localpath == null)
           return "uploads";
       else
           // Remove the URL encoding necessary for
           // the querystring
           return Server.UrlDecode(localpath);
   }
   /// <summary>
   /// Displays the appropriate controls for the passed folder
   /// </summary>
   private void DisplayFolder(DirectoryInfo folder, string rootpath)
   {
       // Get the folder name without the path
       string shortfolder = Path.GetFileName(folder.FullName);
       // Add a folder icon
       Image img = new Image();
       img.ImageUrl = "images/mime_folder.png";
       myPlaceHolder.Controls.Add(img);
       // Add a nonbreakable space
       LiteralControl space1 = new LiteralControl("&nbsp;");
       myPlaceHolder.Controls.Add(space1);
       // Add a link to the folder so user can display it
       HyperLink lnk = new HyperLink();
       lnk.Text = shortfolder;
       // The link for the folder must pass the folder name.
       // Because the folder name may contain characters that are
       // not allowed in a querystring, we must URL encode it
       lnk.NavigateUrl = "FileBrowser.aspx?local=" +
       Server.UrlEncode(rootpath + "/" + shortfolder);
       myPlaceHolder.Controls.Add(lnk);
       // Add a line break
       LiteralControl br1 = new LiteralControl("<br/>");
       myPlaceHolder.Controls.Add(br1);
   }
   /// <summary>
   /// Displays the appropriate controls for the passed file
   /// </summary>
   private void DisplayFile(FileInfo file, string rootpath)
   {// Get the filename without the path
       string shortname = Path.GetFileName(file.FullName);
       // Add a file icon
       Image img = new Image();
       img.ImageUrl = GetIconForExtension(file);
       myPlaceHolder.Controls.Add(img);
       // Add a nonbreakable space
       LiteralControl space2 = new LiteralControl("&nbsp;");
       myPlaceHolder.Controls.Add(space2);
       // Add a link to the file so user can download/view it
       HyperLink lnk = new HyperLink();
       lnk.Text = shortname;
       lnk.NavigateUrl = Server.UrlDecode(rootpath) + "/" +
       shortname;
       myPlaceHolder.Controls.Add(lnk);
       // Add the file size in kb
       long kb = file.Length / 1000;
       LiteralControl size = new LiteralControl(" [" + kb +
       " KB]");
       myPlaceHolder.Controls.Add(size);
       // Add a line break
       LiteralControl br2 = new LiteralControl("<br/>");
       myPlaceHolder.Controls.Add(br2);
   }
   /// <summary>
   /// Returns the filename of the appropriate icon image file
   /// based on the extension of the passed file
   /// </summary>
   private string GetIconForExtension(FileInfo file)
   {
       string image = "images/";
       string ext = Path.GetExtension(file.FullName).ToLower();
       if (ext == ".txt")
           image += "mime_text.png";
       else if (ext == ".doc")
           image += "mime_doc.png";
       else if (ext == ".pdf")
           image += "mime_pdf.png";
       else if (ext == ".gif" || ext == ".jpg" || ext == ".wmf")
           image += "mime_image.gif";
       else if (ext == ".html" || ext == ".htm")

           image += "mime_html.gif";
       else
           image += "mime_unknown.png";
       return image;
   }
   /// <summary>
   /// Makes the "go up a level" link (if needed for the
   /// current folder) and adds it to the place holder
   /// </summary>
   private void MakeUpOneLevelLink(string currentFolder)
   {
       // Get the previous folder (the next one "up" in
       // the hierarchy)
       string previousFolder = GetPreviousFolder(currentFolder);
       // If there is a previous path, add a link to
       // place holder
       if (previousFolder != "")
       {
           Image imgBack = new Image();
           imgBack.ImageUrl = "images/mime_folder.gif";
           myPlaceHolder.Controls.Add(imgBack);
           HyperLink lnkBack = new HyperLink();
           lnkBack.Text = "..";
           lnkBack.NavigateUrl = "FileBrowser.aspx?local=" +
           Server.UrlEncode(previousFolder);
           myPlaceHolder.Controls.Add(lnkBack);
           LiteralControl br = new LiteralControl("<br/>");
           myPlaceHolder.Controls.Add(br);
       }
   }
   /// <summary>
   /// Gets the previous folder (the next one "up" in the file
   /// system hierarchy) from the passed path.
   /// If there was no previous folder, return an
   /// empty string
   /// </summary>
   private string GetPreviousFolder(string path)
   {
       int posOfLastSlash = path.LastIndexOf("/");
       if (posOfLastSlash < 0)
           return "";
       string stripped = path.Remove(posOfLastSlash);
       return stripped;
   }
   /// <summary>
   /// Event handler for the upload button for the FileUploader
   /// </summary>
   protected void btnUpload_Click(object sender, EventArgs e)
   {
       // The location for the uploaded file is current path
       string path = RetrievePathOfFolderToDisplay();
       if (fupTest.HasFile)
       {
           string fullname = Server.MapPath(path + "/" +
           fupTest.FileName);
           if (System.IO.File.Exists(fullname))
           {
               labMessage.Text =
               "File already exists - uploaded cancelled";
           }
           else
           {
               fupTest.SaveAs(fullname);
               labMessage.Text = "File successfully uploaded";
               // Recreate the file listing to show the
               // uploaded file
               GenerateListing(path);
           }
       }
       else
       {
           labMessage.Text = "File was not specified";
       }
   }
   /// <summary>
   /// Event handler for the create new folder button
   /// </summary>
   protected void btnNewFolder_Click(object sender, EventArgs e)
   {
       // Get the location for the new folder
       string folderLocation = RetrievePathOfFolderToDisplay();
       string fullPath = Server.MapPath(folderLocation) + "/" +
       txtFolder.Text;
       // Create the folder on the server
       Directory.CreateDirectory(fullPath);
       // Recreate the file listing to show the new folder
       GenerateListing(folderLocation);
   }

}

0 comments:

How to add an RSS feed in website

7:06:00 am 0 Comments







Many websites have RSS feeds, especially websites with blogs. An RSS feed identifies content on your website, including the publication date. Web browsers and blog readers use the RSS feed to notify users when content is updated.
The acronym RSS stands for "really simple syndication", and the "really simple" part is no exaggeration. Thanks to the simplicity of RSS it's very easy to add an RSS feed to your website. You can read about the RSS specification here.
Here's what my RSS feed looks like. Pretty simple, eh?
Step 1: Create an .aspx page (e.g. rss.aspx) that returns information about your content in RSS format. This .aspx page will return data in XML format, not HTML. I recommend using output caching on this page since it's likely to be retrieved frequently. I cache my rss feed for one minute:

<%@ OutputCache Duration="60" VaryByParam="none" %>

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="rss.aspx.cs" Inherits="rss" %>
In the code-behind for the .aspx page, just build your RSS data and output it with Response.Write.

For example, here's my code-behind. The code first calls a dummy Data Method to get all the data about my blog. The data is stored in a dataset. Then the code iterates through each row in the dataset and builds the section of the RSS XML. Finally, the items are inserted into the XML and the XML is output using Response.Write():
Step 2: Now that you have a .aspx page that returns your RSS data, you need to notify web browsers and blog readers that the feed exists. Just add a tag to the section of your .aspx pages. For example, here's my tag:


<head runat="server">

<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />



<title>Untitled Page</title>

</head>

check out this complete code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Rss.aspx.cs" Inherits="Rss" %>

<%@ OutputCache Duration="60" VaryByParam="none" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />



<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>



</div>

</form>

</body>

</html>

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;



public partial class Rss : System.Web.UI.Page

{

 protected void Page_Load(object sender, EventArgs e)

 {

 

     rss_link.Visible = true;



     if (!IsPostBack)

     {

         DataTable entriesDataSet = new DataTable();

         entriesDataSet = Data();



         const string itemFormat =

 @"

 <item>

   <title>{0}</title>

   <link>{1}</link>

   <description>{2}</description>

   <pubDate>{3}</pubDate>

 </item>";



         string items = string.Empty;



         foreach (DataRow row in entriesDataSet.Rows)

         {

             string url = string.Format("http://localhost/MyPractice/Rss.aspx?b={0}", row["ID"]);

             DateTime pubDate = (DateTime)row["TimeStamp"];



             string item = string.Format(itemFormat, row["Title"], url, row["Title"], pubDate.ToString("s"));



             items = item + items;

         }



         const string rssFormatString =

 @"<rss version=""2.0"">

<!-- generated {0} -->

<channel>

 <title>xyz</title>

 <link>http://aspdotnetcodebook.blogspot.com</link>

 <description>by xyz</description>

 {1}

</channel>

</rss>";



         string result = string.Format(rssFormatString, DateTime.Now, items);



         Response.Clear();

         Response.BufferOutput = true;

         Response.ContentType = "text/xml";

         Response.StatusCode = 200;



         Response.Write(result);

         Response.End();

     }

 }



 public DataTable Data()

 {



     DataTable dt = new DataTable();

     dt.Columns.Add("Id", typeof(int));

     dt.Columns.Add("Title", typeof(string));

     dt.Columns.Add("link", typeof(string));

     dt.Columns.Add("description", typeof(string));

     dt.Columns.Add("TimeStamp", typeof(DateTime));



     dt.Rows.Add(new object[] { "1", "test", "http://abc.com ", "test", "12/12/2008" });

     dt.Rows.Add(new object[] { "2", "test", "http://abc.com ", "test", "12/12/2008" });

     dt.Rows.Add(new object[] { "3", "test", "http://abc.com ", "test", "12/12/2008" });



     return dt;

 }

}

0 comments:

Working With PopUp In ASP.net

7:04:00 am 0 Comments





Whenever we build any web applications it can have requirements to work with popup windows. For example: To pick a date for a date field in an aspx page, we can place a calendar control on a popup so that user can select a date from the calendar instead of typing himself, a simple date picker control. This article will help you understand some of tasks that we more often do with popup windows.

Refreshing a parent page from a popup ASP.Net page

There are situations where we will be required to populate the information’s entered on the popups to the parent page and refresh the parent page so that it can be accessed in the server side. The below example will help us in achieving it.

The below example will populate the entered name in the child.aspx(popup) to the parent(Parent.aspx) and submit the page to the server.
Parent.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Parent.aspx.cs" Inherits="Parent" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>

<script language="javascript">

function OpenWindow(strChildPageUrl)

{

   var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

}

</script>

</head>
<body>
<form runat="Server">
<div>
   <asp:textbox id="txtName" runat="server"></asp:textbox>
   <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Value" />
   <input type="button" id="Button1" value="Enter Name" onclick="OpenWindow('Child.aspx')" />
</div>
</form>
</body>
</html>

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;

public partial class Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    }

}
protected void Button2_Click(object sender, EventArgs e)
{
    if (txtName.Text != "")

        Response.Write(txtName.Text);

}
}

child.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Child.aspx.cs" Inherits="Child" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script language="javascript">

 function SubmitToParent()

 {

 window.opener.document.forms[0].txtName.value = document.getElementById('txtChildName').value;

 window.opener.document.forms[0].submit();

 self.close();

 }

</script>

</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtChildName" runat="server"></asp:TextBox>
        <input type="button" id="Button1" value="Submit to Parent" onclick="SubmitToParent()" />
    </div>
</form>
</body>
</html>
Window.Open Clears Parent page and writes [Object]

Sometimes we will have requirements to open an asp.net page as a popup when we click a hyperlink. Consider the below code,



<a href="javascript:window.open('http:/google.com')"> google</a>



The above code will clear the existing content on the page and will output only [Object]. This behaviour is because the actual return value of Window.Open function is the window object itself.

To prevent the above behaviour and have the parent page without clearing its existing content we need to change the above code similar to below,



<a href="javascript:void(window.open('http:/google.com'))"> google</a>

or

<a href="#" onclick="javascript:window.open('http:/google.com'); return false;"> google</a>
Opening ASP.Net Popup window in specific location of the screen


Opening ASP.Net Popup window in specific location of the screen



Sometimes we would like to open our popup window on specific location on our screen. This can be done by MoveTo() method of the window object.



function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

      testwindow.moveTo(100,0);

}

0 comments:

Photoalbum using ListView and Lightbox jquery plugin

7:04:00 am 0 Comments

In this post i am going to show you how to create a simple photo album in asp.net using ListView and Jquery Lightbox plugin
aspdotnetcodebook


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script src="Scripts/jquery.lightbox-0.5.js" type="text/javascript"></script>

    <link href="css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />
    <title></title>
    <style type="text/css">
        .productlist li
        {
            dispaly: inline;
            float: left;
            margin-left: 15px;
            margin-bottom: 15px;
        }
        *
        {
            border: 0;
            margin: 0;
            padding: 0;
        }
        body
        {
            background: #fff;
            color: #777;
            padding: 50px;
        }
        #page
        {
            position: relative;
        }
        #images
        {
            float: left;
            width: 600px;
        }
        #details
        {
            color: #000;
        }
        h1
        {
            background: inherit;
            border-bottom: 1px dashed #ccc;
            color: #933;
            font: 32px Georgia, serif;
            font-weight: bold;
            margin: 0 0 20px;
            padding: 0 0 15px;
            text-align: center;
        }
        .gallery
        {
            width: 700px;
            cursor: default;
            list-style: none;
        }
        .gallery img
        {
            background: #fff;
            border-color: #aaa #ccc #ddd #bbb;
            border-style: solid;
            border-width: 1px;
            color: inherit;
            padding: 2px;
            vertical-align: top;
            width: 100px;
            height: 75px;
        }
        .gallery li
        {
            background: #eee;
            border-color: #ddd #bbb #aaa #ccc;
            border-style: solid;
            border-width: 1px;
            color: inherit;
            display: inline;
            float: left;
            margin: 3px;
            padding: 5px;
            position: relative;
        }
    </style>

    <script type="text/javascript">
        $(function() {
            $('#images  a').lightBox({ fixedNavigation: true });

        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <h1>
        Image Gallery</h1>
    <div id="page">
        <div id="images">
            <asp:ListView ID="lvPhotoViewer" runat="server" ItemPlaceholderID="itemContainer">
                <LayoutTemplate>
                    <ul class="gallery">
                        <asp:PlaceHolder ID="itemContainer" runat="server" />
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                    <li><a href='<%# "~"+Eval("ImageUrl") %>' runat="server" id="imgHref">
                        <asp:Image runat="server" ID="imPhoto" Width="150px" Height="150px" ImageUrl='<%# "~"+Eval("ImageUrl") %>' />
                    </a>
                        <br />
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
                    </li>
                </ItemTemplate>
            </asp:ListView>
        </div>
    </div>
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lvPhotoViewer.DataSource = new Photo().GetAll();
        lvPhotoViewer.DataBind();
    }
}
public class Image
{
    public string Name { get; set; }
    public string ImageUrl { get; set; }
    public List<Image> GetAll()
    {
        List<Image> images = new List<Image>()
        {
            new Image(){Name="Creek",ImageUrl="/images/Creek.jpg"},
            new Image(){Name="Dock",ImageUrl="/images/Dock.jpg"},
            new Image(){Name="Forest",ImageUrl="/images/Forest.jpg"},
            new Image(){Name="Garden",ImageUrl="/images/Garden.jpg"},
            new Image(){Name="Creek",ImageUrl="/images/Creek.jpg"},
        };
        return images;

    }


}
 
 
 
 
 

0 comments: