Tuesday 2 October 2012

How to replace text in file in .Net?

Definition: How to replace text in file?

Method:
1) Add namespace
    using System.IO;

Code:
 protected void btnReplace_Click(object sender, EventArgs e)
    {
        string sfileName = string.Empty;
        sfileName = "F:\\Work\\HTML\\Profile.txt";

        File.WriteAllText(
            sfileName,
            File.ReadAllText(sfileName)
                .Replace("Name", "Abhishek")
                .Replace("Address","Block No.123,LBS Road,Mumbai,Maharastra")
                .Replace("Mobile", "93117481253")
       );

    }


How to unzip file in .Net?

Definition: How to unzip file in .Net?

Method: 


1) Add the Ionic.Zip dll through Add reference

2) Add the NameSpaces (using Ionic.Zip;)

In my previous post I show you how to make zip file. Now I will show you how to unzip that zip folder.

Code:
 protected void btnUnZip_Click(object sender, EventArgs e)
    {
        String TargetDirectory = "f:\\Zip\\myzip.zip";

        using (ZipFile zip1 = ZipFile.Read(TargetDirectory))
        {
            zip1.ExtractAll("f:\\UnZip\\myzip",
            Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
        }
        File.Delete(TargetDirectory);  //Delete myzip.zip file. It is optional. If you want to delete
                                                         //then delete else don't delete.
    }


How to do zip in .Net? How to make zip file in .Net?

Definition: Make zip file.

Method:
1) Add the Ionic.Zip dll through Add reference

2) Add the NameSpaces (using Ionic.Zip;). 

Code: 

A) Following method will zip whole folder.

protected void btnZip_Click(object sender, EventArgs e)
    {
        string zipfilename = @"f:\\zip\\myzip.zip";  //zipped file name
        string filename = @"F:\\myfiles";         //folder to be zip

        using (ZipFile zip = new ZipFile())
        {
            zip.AddDirectory(filename);
            zip.Save(zipfilename);
        }
    }

Output:
myzip.zip folder at F: drive.

B) Following method will add selected file and folders from different path and add it to archive folder.
 
 protected void btnZip_Click(object sender, EventArgs e)
    {
        string zipfilename = @"f:\\unzip\\myzip.zip";   //zipped file name

        string filename = @"F:\\myfiles";                //folder to be zip

        using (ZipFile zip = new ZipFile())
        {
            //// add this map file into the "images" directory in the zip archive
            zip.AddFile("F:\\Food\\files\\0.png","images");

            //// add the report into a different directory in the archive
            zip.AddFile("F:\\Recipe", "Files");

            zip.AddDirectory("f:\\ticket", "Ticket");


            zip.Save(zipfilename);
        }
    }



Output:
myzip.zip folder at F: drive.
This zip folder will contain 3 folders i.e. images, Files and Ticket.

You run one by one each code and you can see difference between 2 methods.














Tuesday 29 May 2012

How to prepare appam in kerala style? Appam recipe

Kerala Appam recipe

Ingredients for Appam recipe

2  cup(s) raw rice soaked for 4-5 hours
4  cups coconut shavings
1  cup(s) cooked rice
a pinch of yeast granules dissolved in some coconut water or little hot water
salt and sugar to taste

How to make Appam?

Drain the soaked rice and grind it along with the coconut shavings and cooked rice to a fine thick paste. Do not add too much water. Coconut water may be preferably used instead of water for grinding. Add the yeast and mix lightly. Mix in the salt and sugar to taste. Allow to ferment at room temperature for at least 6 hours.
Heat a small non-stick wok. Pour approximately half a cup of batter and quickly but gently swirl the pan around such that only a thin layer of the batter covers the sides and a thick layer collects at the bottom. Cover with a lid and cook each appam on medium heat for about 3 minute(s) or till the edges have become golden crisp and the centre is soft and spongy. Another sign of doneness would be when the edges start coming off the wok.


Serve it with vegetable stew or chicken stew or egg curry.

Friends I am sure that you will love this recipe. I love it. I prefer you to eat little bit hot.


Kerala appam
Appam


 

 

How to fetch TextArea value in .ashx file?

Definition: Fetch Textarea control value in .ashx file.

Example:
.Ashx file code:-

public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "text/html";
        try
        {
                  var comment = context.Request.Params["ctl00$ContentPlaceHolder1$txtComment"];                      context.Response.Write(comment);
         }
        catch { }
    }


Note:
contentplaceholder : because i have used Master Page.

Wednesday 16 May 2012

How to send email in .Net?or how to send an email from a Gmail address using SMTP server?

Definition: SMTP Server

SMTP protocol is used for sending email . SMTP stands for Simple Mail Transfer Protocol. System.Net.Mail namespace is used for sending email . We can instantiate SmtpClient class and assign the Host and Port . The default port using SMTP is 25 , but it may vary different Mail Servers .
The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 and also using NetworkCredential for password based authentication.

Following example shows how to send email in .Net? or How to send email by using your gmail email id?


Example:


using System.Net.Mail;
 
private void SendMail_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("your_gmail_id@gmail.com");
                mail.To.Add("To_emailid@xyz.com");
                mail.Subject = "Test Mail";
                mail.Body = "This is for testing SMTP mail from gmail.";

                SmtpServer.Port = 587;
  SmtpServer.Credentials=new System.Net.NetworkCredential("your_gmail_id@gmail.com", "your_gmail_id_password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("Mail Send Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }



 

Thursday 26 April 2012

How to convert string to number in javascript?

Definition: Convert String to Number.

The Number() function converts the object argument to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.
In short,
Number() method will convert string to number.

Example A:
Javascript function
 
function add(a,b)
{
    var ans;
    var i = a;
    var j = b;
    ans = Number(a) + Number(b);
 
    alert("Your answer: " + ans);
}

 <div>
        <input type="text" id="txta" />
        <input type="text" id="txtb" />
        <input type="button" id="btnAdd" value="Addition" onclick="add(document.getElementByI('txta').value,document.getElementById('txtb').value);" />
          </div>
Output:



Example B:
<script type="text/javascript" language="javascript">

var test1= new Boolean(true);
var test2= new Boolean(false);
var test3= new Date();
var test4= new String("999");
var test5= new String("999 888");

document.write(Number(test1)+ "<br />");

document.write(Number(test2)+ "<br />");
document.write(Number(test3)+ "<br />");
document.write(Number(test4)+ "<br />");
document.write(Number(test5)+ "<br />");

</script> 

Output:
1
0
1335442904505
999
NaN

Saturday 21 April 2012

How to call external javascript file in asp.net?

Definition:
Call external javascript file.

First create javascript file. Add JScript.js file in your solution.
No need to add <script> tag in this file.

In <head> tag add following line of code.
<script type="text/javascript" src="../JScript.js"></script>

src= source path of your JScript.js file.

Example:
Following example shows how to call or add external javascript file.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>External File</title>
    <script type="text/javascript" src="../JScript.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" id="txta" />
        <input type="text" id="txtb" />
        <input type="button" id="btnAdd" value="Addition" onclick="add(document.getElementById('txta').value),document.getElementById('txtb').value);" />
      </div>  
    </form>
</body>
</html>


JScript.js file  (don't add <script> tag in .js file)
function add(a,b)
{
    var ans;
    var i = a;
    var j = b;
    ans = Number(a) + Number(b);
 
    alert("Your answer: " + ans);
}

Output:
Addition of two text box will be shown.




 

Wednesday 18 April 2012

How to show alert box in javascript?

Definition:
The alert() method displays an alert box with a specified message and an OK button.

Syntax:
alert(your message)

you can give any appropriate message.

Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
      <title>Alert Box Example</title>
        <script type="text/javascript" language="javascript">
             function show()
            {
                alert("Hello World!");
            }
        </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        <input type="button" id="alertshow" name="alertshow"         onclick="show();" value="Alert Box" />
    </div>
    </form>
</body>
</html>

Output:


Friday 30 March 2012

How to print document in javascript? or How to show print dialog box in javascript?

Definition: 
window.print() Method

Using window.print() to print a document

The JavaScript syntax used to simulate the print button currently only works in all modern browsers, so it can be a valid substitute inside a browser window where the toolbar is disabled.

Syntax used to print a document:
window.print()

Example:

<input type="button" value="Print this page" onClick="window.print()">

OR

Another way to accomplish the exact same task as above is to use a "JavaScript url". A JavaScript url is a special kind of url that executes a command, instead of loading the specified url.

<a href="javascript:window.print()"><img src="../images/print.gif"></a>
 
Output:
 
You can see print dialogue box. 


How to create jump menu or dorpdown or select option in javascript?

Definition: Jump menu/dropdown menu/select  menu

Sometimes we need to show various option to user. By using <select> tag we can achieve this.
in .Net by using DropDownList control. Here, I have use <select>.

Example:-
As user select any option a new window will open with following selected link.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Javascript_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">
    <title>Create Jump Menu and Open new window</title>
    <script language="javascript" type="text/javascript" >

    function jumpto(url)
    {
        if (document.form1.jumpmenu.value != "null")
        {
             open_new_window(url);  //here we are passing the value of selected option
        }
    }
    function open_new_window(URL)
    {
       NewWindow = window.open(URL,"_blank","toolbar=no,menubar=0,status=0,copyhistory=0,scrollbars=yes,resizable=1,location=0,Width=1500,Height=760") ;
       NewWindow.location = URL;
    }

</script>
</head>
<body>
<form name="form1">
<div align="center">
<select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)">
  <option>Jump to...</option>
  <option value=http://arcreview.blogspot.in/>Arc's Review</option>
  <option value=http://www.google.com>Google</option>
  <option value=http://www.yahoo.com/javascript/>Yahoo</option>
  <option value=http://www.facebook.com/html/>Facebook</option>
 </select>
</div>
</form>
</body>
</html>
 

Wednesday 21 March 2012

For loop in Javascript

Definition: For Loop
 Syntax:
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed

}

startvalue = from which value your loop will start. here it is starting from 0.
endvalue = upto how much time loop to execute.

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.

It is same as "For Loop" in our C language.
 
Example:
<!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>For Loop</title>
    <script type="text/javascript">
        var i=0;
        for (i=0;i<=5;i++)
        {
            document.write("Hello World " + i);
            document.write("<br />");
        }
</script>
</head>
<body>

</body>
</html>

Output:

Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5

Friday 16 March 2012

How to show large image on mousehover in javascript?

Definition:
OnMouseHover show large image.

Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">

    <title>On mousehover show large image</title>
    <script type="text/javascript" language="ecmascript">
        function ShowBiggerImage(obj)
        {
            document.getElementById("LargeImageDiv").innerHTML = "<img src='" + obj.src + "'+'width=350 height=500' >";
        }

        function ShowDefaultImage(obj)
        {
            document.getElementById("LargeImageDiv").innerHTML = "";
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
       
        <div id="LargeImageDiv" style="position: absolute; z-index:2"> 
        </div>
              <table align="center" frame="box" style="border: thin solid #660033; table-layout: fixed">
            <tr>
                <td>
                    <div align="center">
                        <asp:Image ID="Image1" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/cutebird.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);"/>
                    </div>
                </td>
                <td></td>
                <td>
                    <div align="center">
                        <asp:Image ID="Image2" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/snowtwt.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);"  />
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div align="center">
                        <asp:Image ID="Image3" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/springtwt.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);" />
                    </div>
                </td>
                <td></td>
                <td>
                    <div align="center">
                        <asp:Image ID="Image4" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/summertwt.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);" />
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div  align="center">
                        <asp:Image ID="Image5" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/twt.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);"/>
                    </div>
                </td>
                <td></td>
                <td>
                    <div align="center" >
                        <asp:Image ID="Image6" runat="server" Width="80px" Height="100px"
                         ImageUrl="~/Images/flytwt.png"
                         onmouseover="ShowBiggerImage(this);"
                         onmouseout="ShowDefaultImage(this);" />
                    </div>
                </td>
            </tr>
        </table>       
    </form>
</body>
</html>




Output:
It will look like this.


Wednesday 14 March 2012

Convert unix date to datetime.

Definition: Convert Unixdate to DateTime stamp.

protected void Button1_Click(object sender, EventArgs e)
    {
        // UNIX timestamp
        double timestamp = 1309177737;

        // Step1 : Make System.DateTime equivalent to the UNIX Epoch.

        System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

        // Step 2: Add the number of seconds in UNIX timestamp to be converted.

        dateTime = dateTime.AddSeconds(timestamp);

        // The dateTime now contains the right date/time so to format the string,

        // use the standard formatting methods of the DateTime object.

        string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString();

        // Print the date and time
        Response.Write(printDate);
    }

Output :
6/27/2011 12:28 PM

Wednesday 7 March 2012

How to add click event to Anchor or tag?

Definition: 
In script part you can add click event to Achor or <a></a> tag. With the help of Jquery you can do this. First download the following jquery (jquery-1.4.3.min.js) if you don't have.Second add jquery.

To Add use following code: 
<script src="Jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
(please take care of path where you have save jquery)
Example:
<!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>Clcik event</title>
<script src="Jquery/jquery-1.4.3.min.js" type="text/javascript"></script>

    <script type="text/javascript">
       $(document).ready(function(){
             $("a").click(function(event){
             alert("Thanks for visiting!");
          });
        });
    </script>
  </head>
  <body>
    <a href="http://arcreview.blogspot.in/">Arc's Review</a>
  </body>
</html>
Output:
You will see alert box and you press ok button , you will redirect to my blog.

Monday 5 March 2012

How to insert tab in JavaScript?

Definition: "\t" will insert tab in the text.

Example:
 
Script Part:
 
   function show()
        {
         
           var text = "how to insert tab \t 123456789";
            document.getElementById("txtsp").value = text;
          
        }

Control Part:
       <textarea id="txtsp" name="txtsp" class="style1" ></textarea>
        <input type="submit" name="show" id="show"  value="Special Character" onclick="show();"/>

Output:
how to insert tab      123456789

How to insert Single Quote in Javascript?

Definition: To insert ('') single quote in JavaScript, use ( \ ) backslash.
The backslash ( \ ) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.

Example:
Script Part:

 <script type="text/javascript" language="javascript">
        function show()
        {
                     var text ="how to use \'single quote\'";
                    document.getElementById("txtSpecial").value = text;
         }
  </script>

HTML Control:

        <input value="" id="txtSpecial" name="txtSpecial" type="text"/><br />
        <input type="submit" name="show" id="show"  value="Special Character" onclick="show();"/>



Output:
how to use 'single quote'

Friday 2 March 2012

setTimeout() Method Javascript

Definition:
setTimeout() - executes a code some time in the future

Syntax:
var tTime = setTimeout("javascript statement",milliseconds);

The first parameter of setTimeout() can be a string of executable code, or a call to a function.
The second parameter indicates how many milliseconds from now you want to execute the first parameter.

1000 milliseconds = one second

Example:

When the button is clicked in the example below, an alert box will be displayed after 2 seconds.

 <html>
<head>
<script type="text/javascript">
function timeMessage()
{
var tTime = setTimeout("HelloWorld()",2000);
}
function HelloWorld()
{
         alert("Hello World");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 2 seconds" onclick="timeMessage()" />
</form>
</body>
</html>

Thursday 19 January 2012

Access and Modify values of an Array?

Definition: The Array object is used to store multiple values in a single variable.

Example:

First  Create Array (To learn more about how to create array in more detail , Please click the following link) http://arcreview.blogspot.com/2012/01/how-to-create-array-in-javascript.html

var myFruits=new Array(); 
myFruits[0]="Mango";     
myFruits[1]="Orange";
myFruits[2]="Pineapple";

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:

document.write(myFruits[0]);

o/p will be:
 Mango

Modify Array 

To modify a value in an existing array, just add a new value to the array with a specified index number.

myFruits[0]="Grapes";

The following code line:
document.write(myFruits[0]);

o/p will be:
Grapes


How to create Array in JavaScript?

Definition : The Array object is used to store multiple values in a single variable.

Create an Array
An array can be defined in three ways. 

The following code creates an Array object called myFruits:

1.
var myFruits=new Array(); // regular array (add an optional integer
myFruits[0]="Mango";       // argument to control array's size)
myFruits[1]="Orange";
myFruits[2]="Pineapple";


2.
var myFruits=new Array("Mango","Orange","Pineapple"); // condensed array


 3.
var myFruits=["Mango","Orange","Pineapple"]; // literal array


Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Example:
HTML Body tag:


<body>
    <form id="form1" runat="server">
    <div>
        <input id="btnCreateArray" type="submit" value="Create Array" name="
btnCreateArray"   onclick="CreateArray();"/>
     </div>
    </form>
</body>



JavaScript Code:
<script type="text/javascript" language="javascript">
       var myarray = new Array();
       

        function CreateArray()
        {
           
            myarray[0]= "apple";
            myarray[1]="orange";
            myarray[2] ="grapes";
           
         document.write(myarray[0] + "  " + myarray[1] + "  " + myarray[2]);
        }
        CreateArray();
                   
    </script>