2011 | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

How to Find Vowels in a String in JavaScript

Wednesday

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>
               

C# Get All Files from a Folder

Tuesday

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\codingcluster.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\codingcluster.png"

Get files from directory (including all sub directories)
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\dcodingcluster.png"
// "d:\Images\Posts\header.png"

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

how to delete files in folder and subfolders in C#

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!.

Set UITextField Maximum Length in iphone

Wednesday

iPhone SDK: Set Max Character length TextField:
                                                                       The UITextField class has no max length property, it's simple to get this functionality by setting the text field's delegate

Step 1: Implement the UITextFieldDelegate protocol and tag into your text field(s).

Step 2: Add the following line in to top of your .m file

#define MAX_LENGTH 10


Step 3: Implement the following method textField:shouldChangeCharactersInRange:replacementString

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length >= MAX_LENGTH && range.length == 0)
    {
        return NO; // return NO to not change text
    }
    else
    {
     return YES;
    }
}

Iphone- Make a UITextField move up when keyboard is present

Tuesday


UITextField: move view when keyboard appears
                                                                           For showing the text fields without being hidden by the keyboard, the standard way is to move up/down the view having text fields whenever the keyboard is shown.
               
          
The following simple steps is used to move up/down the UITextField in your iPhone.

Step 1: Set the UITextFieldDelegates, and tag the textFields (in your .h file)

Step 2: Place "CGFloat animatedDistance;" in to inside the interface (in your .h file)

Step 3:  Define the following values in top of your .m file (after @implimentation)    

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

Step 4: And finally add the following code into your .m file         
 
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];

CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
CGFloat heightFraction = numerator / denominator;

if (heightFraction < 0.0)
{
heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
heightFraction = 1.0;
}

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
{
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}
CGRect viewFrame = self.view.frame;
viewFrame.origin.y = animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];

[UIView commitAnimations];
}

(void)textFieldDidEndEditing:(UITextField *)textField
{
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];

[UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {

if (theTextField) {
[theTextField resignFirstResponder];
// Invoke the method that does whatever
}
return NO;
}
Please share this post. If it's useful to you.

Send Email Attachments from a Form using Asp.Net and C#

Monday

how to send mail with attachment in asp.net using 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!. 

'System.Array' does not contain a definition for 'Count'

'System.Array' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)


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.



Convert Text to Uppercase Using JavaScript

Thursday

Converting all text in textbox into UPPERCASE / lowercase:
                                                                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:

c# - Enabling And Disabling Buttons In GridView

Monday

                                                              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>

How to change font size of a row in tableview

Thursday

Change font size of a row in tableview:
                                       Copy and paste the following code into your  tableView's cellForRowAtIndexPath  method to change the font size of  a row in  a table view and set the number of line to display in a row.

 Code:
//Setup the cell...
cell.textLabel.font = [UIFont systemFontOfSize:12]; //Change this value to adjust size
cell.textLabel.numberOfLines = 3; //Change this value to show more or less lines.
cell.textLabel.text = @"Your Text";

Reading data from an Excel file using C#

Wednesday

How to read data of an 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();
} 
}
}

Please share this post, if it's useful for you. Thanks! 

iPhone UIView with Border

Adding border to UITextView - in  iPhone SDK:
                                         This is a sample for add border arround with a UIView in  an iphone application (Ref screen shot ). Here I'm using an image view to set  round background in iphone Apps. You just copy and paste the following in to inside your page's ViewDidLoad method (You can change dimensions ).
Don't forget to import  the QuartzCore framework  (#import QuartzCore/QuartzCore.h)
Coding
- (void)viewDidLoad {
        [super viewDidLoad];
 [self.view setBackgroundColor:[UIColor whiteColor]];
 //Create a Imageview
 UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 2, 600, 600)];

 //Enable maskstobound so that corner radius would work.
 [imageView.layer setMasksToBounds:YES];
 //Set the corner radius
 [imageView.layer setCornerRadius:10.0];
 //Set the border color
 [imageView.layer setBorderColor:[[UIColor whiteColor] CGColor]];
 //Set the image border
 [imageView.layer setBorderWidth:1.0]; 
 UIView * loadingView = [[UIView alloc] initWithFrame:CGRectMake(5, 2, 300, 250)];
 [loadingView setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]];
 
 //Enable maskstobound so that corner radius would work.
 [loadingView.layer setMasksToBounds:YES];
 //Set the corner radius
 [loadingView.layer setCornerRadius:10.0];
 //Set the border color
 [loadingView.layer setBorderColor:[[UIColor blackColor] CGColor]];
 //Set the image border
 [loadingView.layer setBorderWidth:1.0];
  
 //Add the loadingView as a subview to imageView
 [imageView addSubview:loadingView];
 [loadingView release];
 
 //Add the imageview as a subview to main view
 [self.view addSubview:imageView];
 [imageView release];
    [super viewDidLoad];
}

Sample screen:


                                                       

Get File Size in B/KB/MB/GB/TB using php

Tuesday

Get File Size using php
                              The following PHP code snippet used to Get File Size in B/KB/MB/GB/TB.

Code:

<?php
/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function findFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}
?>

Disable Cut/Copy/Paste into HTML form using Javascript

How to disable  cut , copy,  paste on Client browser's 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>



Get value stored in Cookie in php

Saturday

Get value from  Cookie in PHP:

                                                  By using  the following code you can retrieve the value stored in cookie. Here I'm using the global variable $_COOKIE to get the value stored in cookies.

Code:
<?php 
setcookie( "cookiename", "cookievalue", time()+60000);
$yourCookie = $_COOKIE["cookiename"];
if ( isset( $yourCookie ) )
   echo "<p>Your cookie value is - $yourCookie</p>";
else
   echo "<p>Nothing in your cookie.</p>";
?>

how to get filename using c#

get filename from filepath - 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("\\"));
}

split string using C# Example

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

Data Gridview Get index of selected row using C Sharp

Friday

How to 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(); 
    } 
}

Javascript Email Validation

Thursday

Simple email validation 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 user prompted to re-enter a valid email 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:  




How to validate email address in iPhone

Monday

iPhone SDK validate email address:
                                        This is prefect method to validate email address valid or not. In this method I'm using "NSPredicate" and "Name Regex" to validate email-ID

Code for email validation on textField in iPhone sdk:
NSString *email = textFieldemail.text;
NSString *emailRegEx =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

NSPredicate *regExPredicate =
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:email];


if(!myStringMatchesRegEx)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"invalid email-ID, please provide a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];
                        
                     This is another one of  a simplest method to validate an email id on a text box in iphone development.

if (! (([txtMailId.text rangeOfString:@"@"].location != NSNotFound) && ([txtMailId.text rangeOfString:@"."].location != NSNotFound) && [txtMailId.text rangeOfString:@"@"].location < [txtMailId.text rangeOfString:@"."].location ) )
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"invalid email-ID, please enter a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];

How to send an Email using c#

Saturday

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, txtMessage.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.

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets