Find  total number of vowels in a string in JavaScript:

                                                     This article explain how to find Vowels in a String and how to find total number of vowels in a string in JavaScript. I have written simple script for checking vowels in a string in JavaScript. I have used regular expression.





<html>
<head>

    <script>
function findVowels() {

var str=document.getElementById('name').value;  

   var vowelC = 0;
var total_findVowels="";
     for (var i = 0; i < str.length; i++) {

     if (str.charAt(i).match(/[a-zA-Z]/) != null) {

        // findVowels

        if (str.charAt(i).match(/[aeiouAEIOU]/))
  {

 total_findVowels=total_findVowels+str.charAt(i);            
 vowelC++;

        }

     }
   }
    document.getElementById('findVowels').value=total_findVowels;
 document.getElementById('findVowels_count').value=vowelC;
   alert("Total Number of findVowels: " + vowelC);
 

}
    </script>

</head>
<body>
<div style="background-color: skyblue; padding:20px">
    <table border="0" cellpadding=3" cellspacing="3">
        <tr>
            <td>
                Enter Input :
            </td>
            <td>
                <input type='text' value='' id='name' name='name'>
            </td>
        </tr>
        <tr>
            <td>
                Vowels Count :
            </td>
            <td>
                <input type='text' readonly="true" value='' id='findVowels_count' name='findVowels_count'>
            </td>
        </tr>
        <tr>
            <td>
                Vowels :
            </td>
            <td>
                <input type='text' readonly="true" value='' id='findVowels' name='findVowels'>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type='button' value='Check' onclick="javascript:findVowels();">
            </td>
        </tr>
    </table>
    </div>
</body>
</html>
               
Read more ...

c# - how to delete all files and folders in a directory?:
This examples shows how to delete all files (*.*) from a folder in C#.
First, you need to get the list of file names from the specified directory (using static method Directory.Get­Files. Then delete all files from the list.
Delete all files
C# code
using System.IO;
string[] filePaths = Directory.GetFiles(@"d:\Images\");
foreach (string filePath in filePaths)
  File.Delete(filePath);

Delete all files (one-row example)
To delete all files using one code line, you can use Array.ForEach with combination of anonymous method.
C# code


Array.ForEach(Directory.GetFiles(@"d:\Images\"),
              delegate(string path) { File.Delete(path); });
Share this post, if it is useful to you. Thanks!.
Read more ...

C# Get All Files from a Folder:
                                                This post shows how to get list of file names from a directory (including subdirectories). You can filter the list by specific extension.
To get file names from the specified directory, use static method Directory.Get­Files. Lets have these files and subfolders in "d:\YourDir" folder:

Get files from directory
Method Directory.GetFiles returns string array with files names (full paths).

C# Code
using System.IO;
string[] filePaths = Directory.GetFiles(@"d:\Images\");
// returns:
// "d:\Images\dotnetcluster.png"
// "d:\Images\home.jpg"


Get files from directory (with specified extension)
You can specify search pattern. You can use wildcard specifiers in the search pattern, e.g. „*.png“ to select files with the extension or „a*“ to select files beginning with letter, a“.

C# Code
string[] filePaths = Directory.GetFiles(@"d:\Images\", "*.png");
// returns:
// "c:\Images\dotnetcluster.png"

Get files from directory (including all subdirectories)
If you want to search also in subfolders use parameter Search Option. A­ll Directories.

C# Code
string[] filePaths = Directory.GetFiles(@"d:\Images\", "*.png",
                                         SearchOption.AllDirectories);
// returns:
// "d:\Images\dotnetcluster.png"
// "d:\Images\Posts\header.png"

Share this post if it is useful to you. Thanks!.
Read more ...

sending mail with attachment in asp.net,c#:
                                                                         In this tutorial you will learn how to send attachment with email in asp.net using c#. To send an email with attachments, the ASP.NET process (or the ASP.NET impersonated account) will need permission to read the file, and attach it to the MailMessage class. You can attach a  file using FileUpload Control and put the file in memory stream. In this example I'm using smtp.gmail.com as my SMTP server.  You can put your gmail login credentials and send mail with attachment.

In .aspx file

 <table style="padding-left: 10px; background-color: #4B8DF8; color: #fff; font-weight: bold;">
        <tr>
            <td colspan="2">
                <span class="primary"><b>Mail With Attachment:</b></span>
            </td>
        </tr>
        <tr>
            <td style="width: 30%">
                From :
            </td>
            <td>
                <asp:TextBox ID="txtFrom" SkinID="textbox_larger" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                To :
            </td>
            <td>
                <asp:TextBox ID="txtTo" SkinID="textbox_larger" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Subject :
            </td>
            <td>
                <asp:TextBox ID="txtSubject" SkinID="textbox_larger" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Message :
            </td>
            <td>
                <asp:TextBox ID="txtMessage" TextMode="MultiLine" SkinID="textbox_multiline_smaller"
                    runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Attach :
            </td>
            <td>
                <asp:FileUpload ID="FileUpload1" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td align="left">
                <asp:Button ID="btnSendMail" runat="server" SkinID="button_primary" OnClick="btnSendMailWithAttachment_Click"
                    Text="Send Mail"></asp:Button>
            </td>
        </tr>
    </table>

Sample screen:
                                     
In .aspx.cs file 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Linq;
using System.Net.Mail;

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

    }
    protected void btnSendMailWithAttachment_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        mail.From = new MailAddress(txtFrom.Text);
        mail.Subject = txtSubject.Text;
        mail.Body = txtMessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("Your gmail id", "your gmail password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
       
}

Please share this post if it's useful to you. Thanks!. 
Read more ...

IEnumerable doesn't have Count:


To resolve this server side error you just add the following namespaces,

 using System.Linq;
 
at the top of your source and make sure you've got a reference to the System.Core assembly.

Read more ...

Upper and Lowercase Conversion - JavaScript:
                                                                Converting a text string to uppercase is very easy using the JavaScript toUpperCase() method and in the same way the toLowerCase() method is used to converting a text string to lowercase. The following code and example shows how this works:
Example:


                             
               
Code:

<html>
<head>
<title>Convert String</title>
<script type="text/javascript" language="javascript">
function changeCase(){
    var txt = document.getElementById("txtChangeText").value;
    var str = new String(txt);
    var changeTo = str.toUpperCase();
    document.getElementById("spnChangedCase").innerHTML = changeTo;
    // var changeTo = str.toLowerCase();//Remove the comment line to convert lowercase
    //document.getElementById("spnChangedCase").innerHTML = changeTo;
}
</script>
</head>
<body>
<div style="background-color: #A5C6FE; padding: 20px">
Type to change UPPERCASE:<input id="txtChangeText" type="text" size="20" onkeypress="changeCase();" />
<span style="color: Red; font-weight: bold" id="spnChangedCase"></span>
</div>
</body>
</html>
Try the demo:

Type to change UPPERCASE:

Read more ...

c# - Enabling And Disabling Buttons In GridView:
In this article  a GridView that has a number of buttons that you need to enable or disable all at once and don't want to have to force a post back on your users in order to loop through them all. By using only a simple js function.

When a GridView renders on the page, it is simply an HTML table and you can traverse it just like you would any other HTML table using JavaScript.

The following code to do a basic version of this in order to enable or disable all buttons in a GridView. First the code gets an instance of the GridView using the ClientID of the GridView, then create a collection of all input controls in the GridView. Next it loops through each input control and checks the type (this is necessary because input controls include not only submit buttons but also things like textboxes). Finally we either enable or disable the submit button.

Code:

<script type="text/javascript" language="javascript">
function disableButtons() 
{
    var gridViewID = "<%=gvReporter.ClientID %>";
    var gridView = document.getElementById(gridViewID);
    var gridViewControls = gridView.getElementsByTagName("input");

    for (i = 0; i < gridViewControls.length; i++) 
    {
        // if this input type is button, disable
        if (gridViewControls[i].type == "submit") 
        {
            gridViewControls[i].disabled = true;
        }
    }
}

function enableButtons() {
    var gridViewID = "<%=gvReporter.ClientID %>";
    var gridView = document.getElementById(gridViewID);
    var gridViewControls = gridView.getElementsByTagName("input");

    for (i = 0; i < gridViewControls.length; i++) {
        // if this input type is button, disable
        if (gridViewControls[i].type == "submit") 
        {
            gridViewControls[i].disabled = false;
        }
    }
}
</script>
Read more ...

Reading, Opening Excel File Using C#:
                                                           By using this code you can read Excel sheet data into dataset. First you have to create a project then create file upload control and a submit button and on button click write the following code.

Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;

public partial class _ParseExcel : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{ 
}
protected void btnParseExcel_Click(object sender, EventArgs e)
{
string path = System.IO.Path.GetFullPath(uploadFile.PostedFile.FileName);
string connString = "provider=Microsoft.Jet.OLEDB.4.0;" + @"data source="+path +";" + "Extended Properties=Excel 8.0;"; 
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Table");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch
{
}
finally
{
oledbConn.Close();
} 
}
}
Read more ...

How to disable copy, paste,cut options with a right click using javascript
                                                                     Javascript based techniques can be easily disabling javascript support methods on browsers. The following script also work with IE

Code:

<html>
<head>
</head>
<body oncopy="return false;" onpaste="return false;" oncut="return false;">
    <form id="form1" runat="server">
        <div>
           Try to copy this and paste in your editor
        </div>
    </form>
</body>
</html>



Read more ...

Splitting a string in C#

Posted by Prince | 6:56:00 PM | | 0 comments »

Split a string using c#: 
                                           The String.Split() method used to split one or more string from a line in C Sharp. To split a string we need a separator to set a string length for split. In the following example I'm using the '#'  symbol to separate the strings.

Code:

//Input string = "split#a#string#" 

String[] split; 
split = String.Split('#'); 
str1 = split[0]; //split 
str2 = split[1]; //a 
str3 = split[2]; //string

Read more ...

Extract file name from path - C# / C Sharp:
                                                              The following simple C# code is used to Extract file name from a given path. Here I'm using the Substring() method to get the filename.

Code:
string strFileName = FileInput.PostedFile.FileName.ToLower;
if (strFileName.IndexOf("\\") > -1) {
 strFileName = strFileName.Substring(strFileName.IndexOf("\\"));
}
Read more ...

Get the index of the SelectedRow in a DataGridView:
                                                                                    You can get the index of the Selected Row in a Data Grid View by using the following c# code.

private void gvCustomer_SelectionChanged(object sender, EventArgs e) 
{ 
   if (gvCustomer.SelectedRows.Count == 1) 
    { 
       txtXML.Text = gvCustomer.Rows[gvCustomer.SelectedRows[0].Index].Cells["CustomerCode"].Value.ToString(); 
    } 
}
Read more ...

Validate email address in JavaScript:
                                             This is a script for validate  form box to ensure that the user entered a valid email address. If not, the form submition is canceled, and the surfer prompted to re-enter a valid address.

 This script validate the following assumptions:
  • The mailID should contains a least one character procedding the "@"
  • The mailID should contains a "@" following the procedding character(s)
  • The mailID should contains at least one character following the "@", followed by a dot (.), followed by either a two character or three character string .
Javascript code for validate email address:
<html>
<head>
    <title>Email Validation</title>
    <script type="text/javascript">
var error;
function isValidEmail(){
var str=document.mailValidation.txtEmail.value
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str)){
alert(str +" is  a valid email address");
error=false;
}
else{
alert("Please enter a valid email address!");
error=false;
}

return (error)
}
    </script>

</head>
<body>
    <form name="mailValidation">
    Enter Your Email Address:<br />
    <input type="text" size="15" name="txtEmail">
    <input type="submit" value="Submit" onclick="return isValidEmail();">
    </form>
</body>
</html>

Demo:

Enter Your Email Address:




Read more ...

Send Email using ASP.Net and C#

Posted by Prince | 7:54:00 PM | | 0 comments »

Send Email from your GMAIL account using ASP.Net and C#:
                                                    This article is provide a demo for send Emails  from your GMAIL account using ASP.Net and C#:
First create an aspx file named "SendGmail.aspx" with required input controls and action buttons. Please refer the below screen shot.


Give the id for from textbox as "txtFrom" and "txtTo", "txtSubject", "txtMessage"  respectively.
Then add the following code into the "Send Email" button's OnClick method in thecode behind. Before appropriate name space (if you need).

Code:
protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        
//Create Mail Message Object with content that you want to send with mail.
        
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(txtFromMail.Text, txtToMail.Text, txtSubject.Text, txtMeaasge.Text);
        
mailMessage.IsBodyHtml = false;      
        
//Proper Authentication Details need to be passed when sending email from gmail
        
System.Net.NetworkCredential mailAuthentication = new
        
System.Net.NetworkCredential("YourGmailID""YourGmailPassword");
        
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
        //For different server like yahoo this details changes and you can
        //get it from respective server.
        
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com"587);
        
//Enable SSL
        
mailClient.EnableSsl = true;
        
mailClient.UseDefaultCredentials = false;
        
mailClient.Credentials mailAuthentication;
        
mailClient.Send(mailMessage);
    
}
You can download full code for send email using csharp from here

Please leave some comment, if this post useful to you.
Read more ...

The type or namespace name 'MySql' could not be found:
                                  If you remove or delete the MySql.Data reference from your project library, you will get this type of errors. To resolve this you just follow the below steps.
 Solution:
Step 1: Download the Connector/Net from http://dev.mysql.com/downloads/connector/net/1.0.html

Step 2: Run the downloaded .exe file in to your system.

Step 3: Open your project in Visual Studio --> open references --> delete MySql.Data (old) reference.

Step 4: Right click on references and Add new assembly references for MySql.Data

Step 5: Build your library and you will get Build Succeed.
Read more ...


Show how many characters remaining in a html text box using javascript:
                                                                                     The following  javascript will help you to show how many characters are remaining for a textbox or textarea, The label placed next to the text box shown the number of character remaining.

<script type="text/javascript">
function txtCounters(id,max_length,myelement)
{
counter 
= document.getElementById(id);
field = document.getElementById(myelement).value;
field_length field.length;
 if 
(field_length <max_length)  {
//Calculate remaining characters
 
remaining_characters max_length-field_length;
//Update the counter on the page
  
counter.innerHTML remaining_characters;  }
 } 
</script>

<label for="txtName">Enter Your Text : </label>
<input type="text" id="txtName" size="50" maxlength="50" onkeyup="javascript:txtCounters('txtCounter',50,'txtName')"> <div id="txtCounter"><b>50</b></div>characters remaining.
Demo:

50
characters remaining.
Read more ...

Create Folder Using C#:

Posted by Prince | 7:55:00 PM | | 0 comments »

Create Folder Using C#:
          By using the following code you can give the user the ability to enter a directory name, check to see if it already exists and if not then create the folder and upload the files there.
                          First create a text box name as "txtFolderName" and a submit button name as "Create Folder" . It's just look like...


                Next, the bellow c# code used to validate if folder name exists and create a folder with name of "Image"
protected void btnCreateFolder_Click(object sender, EventArgs e)
    {
 
          if (!System.IO.Directory.Exists(MapPath(MyTree.SelectedValue + "\\" + txtFolderName.Text)))
          {           
            System.IO.Directory.CreateDirectory(MapPath(txtFolderName.Text));
            lblError.Text = "Created Successfully";
            txtFolderName.Text = "";     
          }             else
            {
                
lblError.Text = "Folder Already Exist";
            }
 

    }

Now you can see your new folder for your specified path and then leave some comment to encourage us.
Read more ...


 Save image in image type datatype:
                                            This is the  sample code for save image in image type datatype in mssql table using csharp.

Code for create database
CREATE TABLE Images(
ImageID 
INT IDENTITY(1,1PRIMARY KEY,
ImageData IMAGE)
In C# code behind: 
protected void btnSaveImage_Click(object sender, EventArgs e)
    {
        
if (FileUpload1.HasFile)
        {
            
byte[] ImageData ReadImage(FileUpload1.PostedFile.FileName);
            
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
            string 
query "INSERT INTO Images VALUES(@ImageData)";
            
SqlCommand com = new SqlCommand(query, con);
            
com.Parameters.AddWithValue("@ImageData", (object)ImageData);
            
con.Open();
            
com.ExecuteNonQuery();
            
con.Close();
        
}
    }

    
byte[] ReadImage(string ImagePath)
    {
        
byte[] ImageData = null;
        
FileInfo fi = new FileInfo(ImagePath);
        long 
NumberOfBytes fi.Length;
        
FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
        
BinaryReader br = new BinaryReader(fs);
        
ImageData br.ReadBytes((int)NumberOfBytes);
        return 
ImageData;
    
}
Write your comments after successfully run this code.
Read more ...

Random Password Generation Using C#

Posted by Prince | 4:30:00 PM | | 0 comments »



Generating Random Password Using C#:
                                                              The following method would be useful for generating random password using C#. You just give length of the password as input and get the random password.

Code:
   public static string GenerateRandomPassword(int length)
    {
        
char[] chars "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
        string 
password = string.Empty;
        
Random random = new Random();

        for 
(int 0i < lengthi++)
        {
            
int random.Next(1,chars.Length);
            
//Don't Allow Repetation of Characters
            
if (!password.Contains(chars.GetValue(x).ToString()))
                password +
chars.GetValue(x);
            else
                
i--;
        
}
        
return password;
    
}
Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.
Read more ...


Dynamically change body background color using  javascript:
                                                                                           This is the sample code for Dynamically change the body/div/text background color using javascript. By using this code you can change the text color while the background changed dynamically.

Code:
<html>
<head>
    
<title>Dynamically change background color</title>
    
<script language="javascript" type="text/javascript">
var count=0;
function 
changeColor()
{
    setTimeout(
"showColorChange()",500);
}
function showColorChange()
{
    
var bg =new Array("red","darkblue","sky","yellow","blue","pink","green");
    var 
txt =new Array("black","white","green","blue","pink","red","yellow");
    if
(count<=6)
    {        
document.getElementById("divChangeColor").style.backgroundColor=bg[count++];
        document
.getElementById("txtChangeColor").style.color=txt[count++];
        
setTimeout("showColorChange()",500);
    
}
    
else
    
{
        count
=0;
        
changeColor();
    
}
}
    
</script>

</head>
<body onload="changeColor()">
    
<div id="divChangeColor" style="width: 300px; height: 300px; background-color: Gray">
        
<span id="txtChangeColor"><b>Look at me & my background</b></span>
    
</div>
</body>
</html>

Demo:







Look at me & my background
Read more ...

Get Rid of  White Flash when iframe Loads:
                                                               To avoid white background while iframe loads, you can hides iframe until its fully loaded. You can use the following code snippets to hide iframe when its loading.
<iframe style="visibility:hidden;" onload="this.style.visibility = 'visible';" src="../iframe.html" > </iframe>
Read more ...

Related Posts Plugin for WordPress, Blogger...