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";

Get All Files from Directories and Sub-Directories - Vb.NET

Posted by Venkat | Labels: , ,

Here i have to discuss about how to get all the files of Directories and SubDirectories.

Generally we know how to get the files from From directory

Vb.NET


Imports System.IO

Dim position as integer = 1

Public Sub GetFiles(ByVal path As String)

If File.Exists(path) Then

' This path is a file

ProcessFile(path)

ElseIf Directory.Exists(path) Then

' This path is a directory

ProcessDirectory(path)

End If

End Sub





' Process all files in the directory passed in, recurse on any directories

' that are found, and process the files they contain.

Public Sub ProcessDirectory(ByVal targetDirectory As String)

' Process the list of files found in the directory.

Dim fileEntries As String() = Directory.GetFiles(targetDirectory)

For Each fileName As String In fileEntries

ProcessFile(fileName)

Next



' Recurse into subdirectories of this directory.

Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)

For Each subdirectory As String In subdirectoryEntries

ProcessDirectory(subdirectory)

Next

End Sub



' Insert logic for processing found files here.

Public Sub ProcessFile(ByVal path As String)

Dim fi As New FileInfo(path)

Response.Write("File Number " + position.ToString() + ". Path: " + path + "
")

position += 1

End Sub

Give the path like this

GetFiles("C:\Test\")

And there is a simple way to get all files like this

Dim di as new IO.DirectoryInfo("C:\uploadfiles")
Dim finfo as IO.FileInfo() = di.GetFiles("*.*",IO.SearchOption.AllDirectories)


Get All files of Directories and SubDirectories - C#

Posted by Venkat | Labels: , ,

Here i have to discuss about how to get all the files of Directories and SubDirectories.

Generally we know how to get the files from From directory

ex: Directory.GetFiles("path");

C# Code:


using System.IO;

private int position = 1;

public void GetFiles(string path)

{

if (File.Exists(path))

{

// if file Exists

ProcessFile(path);

}

else if (Directory.Exists(path))

{

// if Directory exists

ProcessDirectory(path);

}

}

public void ProcessDirectory(string targetDirectory)

{

string[] fileEntries = Directory.GetFiles(targetDirectory);

foreach (string fileName in fileEntries)

ProcessFile(fileName);

string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);

foreach (string subdirectory in subdirectoryEntries)

ProcessDirectory(subdirectory);

}

public void ProcessFile(string path)

{

FileInfo fi = new FileInfo(path);

Response.Write("File Number " + position.ToString() + ". Path: " + path + "
"
);

position++;

}


Give File Path like this


GetFiles("C:\\Test\\");

Validation which accept( empty , numeric or Float values)

Posted by Venkat | Labels: ,

Now we have to discuss about the validationexpression ie:

the textbox should accept empty values , numeric ( float ) .

Implementation Code :

^\d*\.?\d*$

HTML


<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid format" ControlToValidate="TextBox3" ValidationExpression="^\d*\.?\d*$" ValidationGroup="d"></asp:RegularExpressionValidator>
<asp:Button ID="Button5" runat="server" Text="Button" ValidationGroup="d" />
Matches

( ) -> empty value
4535
520.20
2.54

Non-Matches

21.0dfdf
47854
Rpks

Disable Submit button after submit information

Posted by Venkat | Labels: ,

Here we have to discuss the ie: how to disable the submit button after you submit the details for example: user are sending some value to database or storing user information so after storing the information i have to disable the submit button to avoid duplicate insertion ie: insert two or more times.


protected void Page_Load(object sender, EventArgs e)
{
string clickHandler = string.Format(
"document.body.style.cursor = 'wait'; this.value='Please wait...'; this.disabled = true; {0};",
this.ClientScript.GetPostBackEventReference(Button1, string.Empty));
Button1.Attributes.Add("onclick", clickHandler);
}

protected void Button1_Click(object sender, EventArgs e)
{
// Emulate a lengthy process of 10 seconds...
TimeSpan waitTime = new TimeSpan(0, 0, 0, 10);
System.Threading.Thread.Sleep(waitTime);

Response.Write("Button1_Click fired
");
}

Validate Decimal numbers

Posted by Venkat | Labels: ,

Now we are going to discuss about the validate the decimal numbers it should be in the format of


<asp:TextBox ID="Phone_TextBox" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator"
ValidationExpression="^\d+\.\d{2}$" ValidationGroup="phone" ControlToValidate="Phone_TextBox">it should be 125.00 this format</asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="phone" /></div>


Matches

142.00
254.25 etc

Non-Matches

214
25.0
254.5
254.355

code:

PreviousPage Type

Posted by Venkat | Labels: ,

Hi , we already seen the CrossPage Posting so now we are going to see the concept Previouspage ( to send data from one page to another page )

in the first page ie: Webform1.aspx


<asp:TextBox ID="TextBox1" Text="xxxx" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" Text="L”schen" PostBackUrl="~/webform2.aspx" />

On Webform2.aspx you have to write it on page Directive, you have to specify the page so from that page you can get the textbox value to this page. In the Virtualpath you should specify the Previous page name from where you get the control value.

<%@ PreviousPageType VirtualPath="~/Webform1.aspx" %>

on Codebehind ie: Page_load event write this

if (Page.PreviousPage != null)
{
TextBox oTextBox = (TextBox)Page.PreviousPage.FindControl("TextBox1");
if (oTextBox != null)
{
Response.Write(oTextBox.Text);
}
}

Sys is Undefined

Posted by Venkat | Labels: ,

When i add ajaxtoolkit.dll file to bin folder of my new project that has been created in .net 2005 or .net 2.0 so when i place the ajax controls on my page and written some code on running the project it shows no error but code is not working on status bar i have see Error on this page

When i click the error icon it shows Sys is undefined

so the solution is you have to modify the web.config file like this.

1) Below <Configuraion> tag add this


<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>


2) Below <system.web> add the settings

<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>


3) Then find compilation debug="false" change like this


<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>

4) Then below the compilation settings

<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>


5) Then after </system.web> add the settings

<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>
</system.web.extensions>

6) Then add the system.webserver settings

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>


These are the setting you have to modify on your web.config if your are selecting the AJAX - Enabled Websites when you are creating the project so at that time there is no need these setting, these settings are added automatically.

All the best

PayOffers.in