How to download a file from Server folder

Posted by Venkat | Labels:

Now we are going to see how to download a file or image from the Server folder ie: showing file/open dialog box. For this we have to use Response object to show or get the file.

Sample Code:

        private void WriteFileToResponse()
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.MapPath("~/Download/" + FileName));
            //                    Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";

            //Write the file to the Response Output stream without buffering. 
            //This is new to ASP.NET 2.0. Prior to that use WriteFile. 
            Response.TransmitFile(Server.MapPath("~/Download/" + FileName));
            Response.Flush();
            Response.End();
        }

HTML Validation

Posted by Venkat | Labels: ,

As we used the Embed tag for embed the Flash files , on home or master page as this tag not support for HTML Validation (W3C) . but still we used this tag for showing flash file , if you want to do HTML validation for your site - this makes an error , so you have to avoid this.


Instead use Object tag for placing Flash files

Example:

 <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" data="the-swf-file.swf" type="application/x-shockwave-flash" width="600" height="420"> <param name="movie" value="the-swf-file.swf" /> <param name="quality" value="high" /> </object>

Wrap the text on Gridview.

Posted by Venkat | Labels:

Hi Good day to All

After a long time , i am back  - i have no time to post the Resources here . now , i will try to post atleast one Resource per day.

I wish you all a Very Happy Diwali

Now i am going to see how to Wrap the text show in the Gridview , I had searched many links & sites finally i got one javascript.
place the javascript at the Top of the page ie: loaded when the page Loads.

<script type="text/javascript"> 
       window.onload = function()
        { 
        if (window.attachEvent == undefined) 
        {
         var tag = document.getElementsByTagName("td"); 
         for (var i = 0; i < tag.length; i++)
          {
           if (tag.item(i).className == "wordwrap") 
           {
            var text = tag.item(i).innerHTML; 
            tag.item(i).innerHTML = text.replace(/(.*?)/g, "<wbr/>"); 
            } 
           } 
          }
         }
    </script>
And one thing you are going to consider , here you have to apply the class="wordwrap" on your td tag at where you want text wrap or which column wants the text wrap then you have to specify the width in px not in % or any.
This is my Sample Gridview code

<asp:GridView ID="userList_GridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                                          BorderColor="WhiteSmoke" BorderWidth="0px" CellPadding="5" 
                                            EmptyDataText="User not found...!" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black"
                                            PageSize="30" ToolTip="User List....!" Width="100%" GridLines="None" BackColor="WhiteSmoke" >
                                            <Columns>
                                                <asp:TemplateField>
                                                    <HeaderTemplate>
                                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                            <tr style=" color: Black;" class ="fbtxt">
                                                                <td align="left" style="width: 18%">
                                                                 Username
                                                                </td>
                                                                <td align="left" style="width: 14%">
                                                                    Email
                                                                </td>
                                                                
                                                                
                                                               <td align="center" style="width: 15%">
                                                                   Resource Permission
                                                                </td>
                                                                <td align="center" style="width: 11%">
                                                                    Permission
                                                                </td>
                                                                  <td align="center" style="width: 7%">
                                                                     Edit
                                                                    </td>
                                                                <td align="center" style="width: 8%">
                                                                    Delete
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </HeaderTemplate>
                                                    <HeaderStyle BackColor="LightSteelBlue"  Font-Bold="True" Font-Size="10pt" ForeColor="Black" />
                                                    <ItemTemplate>
                                                    <div style ="width :100%;table-layout:fixed;border:0px;">
                                                    <div class ="fntxt">
                                                    <div align="left" style="width: 165px; word-wrap:break; float:left ;" class="wordwrap">
                                                      <%# Eval("username")%>
                                                    </div> 
                                                    <div align="left" style="width: 150px;float:left;" class="wordwrap" >
                                                     <%#Eval("email")%>
                                                    </div> 
                                                    
                                                   <div align="left" style="width: 20%;float:left;" >
                                               <a href ='<%# "resourceaccess.aspx?userResource=" +  Eval("username")   %>' class ="WhiteLink"> Resource Access</a>
                                                    </div>
                                                      <div align="left" style="width: 13%;float:left;" >
                                                      <a href= '<%# "userlist.aspx?userPermission=" +  Eval("username")  %>' class ="WhiteLink"> <%# Eval("approve") %></a>
                                                 
                                                    </div>
                                                    <div align="center" style="width: 12%;float:left;"  >
                                                    <asp:HyperLink ID="Edit_HyperLink"  runat="server" NavigateUrl='<%# "~/Admin/userlist.aspx?editUser=" +  Eval("username")  %>'
                                                                      CssClass ="WhiteLink"  OnClick="return confirm('Are you sure want to Edit this record ?');" Text="Edit"
                                                                        ToolTip="Edit user list....!"></asp:HyperLink>
                                                    </div> 
                                                    <div align="center" style="width: 7%;float:left;"  >
                                                    <asp:HyperLink ID="Delete_Button"  runat="server" NavigateUrl='<%# "~/Admin/userlist.aspx?delUname=" +  Eval("username")  %>'
                                                                      CssClass ="WhiteLink"  OnClick="return confirm('Are you sure want to Delete this record ?');" Text="Delete"
                                                                        ToolTip="Delete user list....!"></asp:HyperLink>
                                                    </div> 
                                                    
                                                    </div>
                                                    </div>
                                                        
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                            <PagerStyle BackColor="WhiteSmoke" Font-Bold="False" Font-Names="verdana" Font-Size="8pt"
                                                ForeColor="Red" HorizontalAlign="Center" />
                                        </asp:GridView>

Refresh the Parent Page after Closing PopUp Page (window)

Posted by Venkat | Labels: ,

Good Day to all

And also I wish you a Very Happy FriendShip Day..

Now we have to discuss the How to Refresh the parent window by Closing the popup window

Passing the function on your button ie: place Close button on you popup If you click the Close Button , it will close the popup and refresh the parent page.


<script>
function refreshParent() {
window.opener.location.href = window.opener.location.href;

if (window.opener.progressWindow)

{
window.opener.progressWindow.close()
}
window.close();

}
</script>

Email with Attachment

Posted by Venkat | Labels:

Now we will see , how to send an attachment to the email.

for the you have to create an instance for Attachment class and pass the filename and specify the media type information for an email message attachements and set the ContentDisposition which specify the file type whether its txt , doc, gif,jpg etc..,

Import NameSpace

using System.Net.Mail;
using System.Net.MIME;
using System.Net;

Code

try
{

MailMessage mail = new MailMessage();

mail.To.Add("venkat@gmail.com");

mail.From = new MailAddress("admin@Support.com");

mail.Subject = "Testing Email Attachment";

string file = Server.MapPath("~/files/findemai_ontextfile.txt");

Attachment attachFile = new Attachment(file, MediaTypeNames.Application.Octet);

ContentDisposition disposition = attachFile.ContentDisposition;

mail.Attachments.Add(attachFile);

SmtpClient smtp = new SmtpClient();

smtp.Host = "smtp.gmail.com";

smtp.EnableSsl = true;

smtp.Credentials = new NetworkCredential("xxxxxxx@gmail.com", "*********");
s;

smtp.Send(mail);

}

catch (Exception ex)
{

Response.Write(ex.Message);

}

This link helps you :
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

Checkboxlist sample code

Posted by Venkat | Labels: ,

Now we are going to discuss about the Checkbox list Control so Checkboxlist allows user to select Multiple values , we will see how to retrieve the selected values from the Checkboxlist.

Here is the HTML Code


<asp:CheckBoxList ID="cblPlanets" runat="server" Width="109px">
<asp:ListItem Value="1">Mercury</asp:ListItem>
<asp:ListItem Value="2">Venus</asp:ListItem>
<asp:ListItem Value="3">Earth</asp:ListItem>
<asp:ListItem Value="4">Mars</asp:ListItem>
<asp:ListItem Value="5">Jupiter</asp:ListItem>
<asp:ListItem Value="6">Saturn</asp:ListItem>
<asp:ListItem Value="7">Uranus</asp:ListItem>
<asp:ListItem Value="8">Neptune</asp:ListItem>
</asp:CheckBoxList>
in Code behind , then place one label control to get the selectedvalue of checkboxlist

C# SOURCE

protected void btnSubmit_Click(object sender, EventArgs e)
{
lblText.Text = "You selected: ";

foreach (ListItem li in cblPlanets.Items)
{
if (li.Selected == true)
{
lblText.Text = lblText.Text += "~" + li.Text;
}
}
}

"The state information is invalid for this page and might be corrupted" With ASP.NET AJAX

Posted by Venkat | Labels:

If you got this error while you working with Asp.Net AJAX.

This seems to be caused by Firefox's methods for saving session information in its cache. There is many way to solve this problem it’s depending on how extensive you want to disable the cache. In my case, I just wanted to do it on one page, so at the top of Page_Load I added:

Response.Cache.SetNoStore();


Set the page Declaration with

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Page.aspx.cs" Inherits="Main" Title=My Home" EnableViewStateMac ="false" EnableSessionState="True" EnableEventValidation ="false" ValidateRequest ="false" ViewStateEncryptionMode ="Never" %>
You can also add with web.config file

<pages validaterequest="false" enableeventvalidation="false" viewstateencryptionmode="Never">
</pages>

DeCompress the file using asp.net

Posted by Venkat | Labels: , ,

In previous post we seen how to compress the file this will helpful when the file is large you can
compress the file.

Now we will see how to Decompress the file

Button_Click event.


DecompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"));

Here i just swap the filename so it may confuse so use some different path(Folder) or filename

Decompress Method

public static void DecompressFile(string sourceFileName, string destinationFileName)
{

FileStream outStream;

FileStream inStream;

//Check if the source file exist.

if (File.Exists(sourceFileName))
{

//Read teh input file

inStream = File.OpenRead(sourceFileName);

//Check if the destination file exist else create once

outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);

//Now create a byte array to hold the contents of the file

//Now increase the filecontent size more since the compressed file

//size will always be less then the actuak file.

byte[] fileContents = new byte[(inStream.Length * 100)];

//Read the file and decompress

GZipStream zipStream = new GZipStream(inStream, CompressionMode.Decompress, false);

//Read the contents to this byte array

int totalBytesRead = zipStream.Read(fileContents, 0, fileContents.Length);

outStream.Write(fileContents, 0, totalBytesRead);

//Now close all the streams.

zipStream.Close();

inStream.Close();

outStream.Close();

}

}

Compress the file using asp.net

Posted by Venkat | Labels: , ,

Good day to all today we are going to discuss about how to compress the file using asp.net application , ie: for compression there are some third party tools like CSharpZip (not sue about the name of the tools..) ,gzip, etc..

Asp.net has inbuilt with Compression ie: derive from the Class

using System.IO.Compression;

There are two compression derived from this namespace.
1) Gzipstream
2) Deflate stream

Deflate seems to be must faster than the Gzipstream but Deflate doesn't uncompress other formats , but Gzipstream decompress the other files like winzip, winrar .

Now we are going to see Gzipstream it has a class which contains filename and compression mode , Compression mode has two values Compress and Decompress.

Button_ClickEvent

CompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"));

Here you have to give two parameter first one is Sourcefilename to be compressed , second is path where you have to place the compressed file. it will check if the file exists the compressed file has been placed there, else it will create on the fly.

Method definition

public static void CompressFile(string sourceFileName, string destinationFileName)
{

FileStream outStream;

FileStream inStream;

//Check if the source file exist.

if (File.Exists(sourceFileName))
{

//Read teh input file

//Check if the destination file exist else create once

outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);

GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress);

//Now create a byte array to hold the contents of the file

byte[] fileContents = new byte[inStream.Length];

//Read the contents to this byte array

inStream.Read(fileContents, 0, fileContents.Length);

zipStream.Write(fileContents, 0, fileContents.Length);

//Now close all the streams.

zipStream.Close();

inStream.Close();

outStream.Close();

}

}

Specified string is not in the form required for an e-mail address

Posted by Venkat | Labels:

This error cause while you are working with .net1.1.1 ie" Sytstem.Web.Mail; if we send the email to multiple person we use like this

string toemail = "xxxxx@yahoo.com;yyyyyy@gmail.com;zzzzzz@hotmail.com;";

so this works there because we used semicolon to separate the emailID

But in .net 2.0 System.Net.Mail

if we use the same way (ie: using semicolon to differentiate the emailID) it will cause to give this error.

"Specified string is not in the form required for an e-mail address"

so the modified string

string toemail = "xxxxx@yahoo.com,yyyyyy@gmail.com,zzzzzz@hotmail.com";

PayOffers.in