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

Reading data from an Excel file using C#


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.


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

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)
- (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


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


 * @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


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

Get value stored in Cookie in php


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.

setcookie( "cookiename", "cookievalue", time()+60000);
$yourCookie = $_COOKIE["cookiename"];
if ( isset( $yourCookie ) )
   echo "<p>Your cookie value is - $yourCookie</p>";
   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.

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.


//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


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


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:
    <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");
alert("Please enter a valid email address!");

return (error)

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

    Enter Your Email Address:  

How to validate email address in iPhone


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 =

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

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];
[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];
[self prepareHmlDataAndSendEmail];

How to send an Email using c#


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

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
//Smtp Mail server of Gmail is "" 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(""587);
//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials mailAuthentication;
You can download full code for send email using csharp from here

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

The type or namespace name 'MySql' could not be found (are you missing a using directive or an assembly reference?)


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.
Step 1: Download the Connector/Net from

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.

iPhone: Copy a file from resources to documents

iPhone SDK: How to copy a file from resources to documents Directory?:
                                                        You can copy a file or database from resources to documents directory by using the following code.

NSFileManager *fileMgr= [[NSFileManager alloc] init];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"reporter.sqlite3" ofType:nil];
    NSError *error;
    if(![fileMgr copyItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/Documents/reporter.sqlite3", NSHomeDirectory()] error:&error]) {
         //Exception Hndling
         NSLog(@"Error : %@", [error description]);

    [fileMgr release];

Get remaining characters count in a textbox using javascript


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)
= document.getElementById(id);
field = document.getElementById(myelement).value;
field_length field.length;
(field_length <max_length)  {
//Calculate remaining characters
remaining_characters max_length-field_length;
//Update the counter on the page
counter.innerHTML remaining_characters;  }

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

chars remaining.

iphone SDK: Create Relationships in sqlite3 database


Create relationships between tables in sqlite3:
                                SQLite supports the definition of foreign key constraints, the following sqlite3 query will be used to create a table "media" with foreign key reference with "incident" table
constraint FK_media__incident foreign key(incident_id) references incident(incident_id))
  This an example for create table with more than one references. Each references separate with commas,
CREATE TABLE "incident_type_list" ("incident_id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE "incident_type_id" INTEGER NOT NULL "created_date" DATETIME NOT NULL "last_modified_date" DATETIME NOT NULL,
constraint FK_incident_type_list_incident foreign key(incident_id) references ir_incident(incident_id),
constraint FK_incident_type_list_incident_type foreign key(incident_type_id) references incident_type(type_id))
  Leave some comments if this post useful for you. Thanks!.

Create Folder Using C#


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

Calculating difference between two dates in PHP

Calculating difference between two dates using PHP:
The following code used to calculating the difference between two dates in PHP without using DateTime class.

                     The strtotime() function parses date wrote as as string to UNIX timestamp. After substracting two timestamps, $diff is equal to number of seconds between these two days, we wanted to have difference in days, so we need to make additional arithmetic operations and return result. The most important here is use of the same timezone.

function dateDifference($dt1, $dt2, $timeZone = 'GMT')
    $tZone = new DateTimeZone($timeZone)
    $dt1 = new DateTime($dt1, $tZone)
    $dt2 = new DateTime($dt2, $tZone)

    $ts1 = $dt1->format('Y-m-d')
    $ts2 = $dt2->format('Y-m-d')

    $diff = abs(strtotime($ts1)-strtotime($ts2))

    $diff/= 3600*24

    return $diff

echo date
Difference('2011-11-11', '2011-12-12');

File Upload Using PHP


PHP File Upload:
                             The following HTML form used for uploading files. The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded.

The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> <br />
input type="submit" name="submit" value="Submit" />

The "fileUpload.php" file contains the code for uploading a file:

                                           By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload

                        This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 100000))
  if ($_FILES["file"]["error"] > 0)
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      echo $_FILES["file"]["name"] . " already exists. ";
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored to: " . "upload/" . $_FILES["file"]["name"];
  echo "Invalid file format";
The above code checks if the file already exists, if it does not, it copies the file to the specified folder.

iPhone SDK display current date

 iphone SDK CurrentDate Application

                                                In this application used  to display current date on label by using Window based application. First create a window based application called CurrentDate. Creating a variable (mlabel), declared as IBOutlet andalso property is declared. 

The  CurrentDateAppDelegate.h  file look like this
@interfaceCurrentDateAppDelegate : NSObject <UIApplicationDelegate>

The  CurrentDateAppDelegate.m file look like this

@synthesizewindow, mlabel;

   NSDateFormatter*dateFormatter =
   [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
   [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
   NSDate*date =[NSDatedate];
   NSString*formattedDateString = [dateFormatterstringFromDate:date];
   NSLog(@"formattedDateStringfor locale %@: %@", [[dateFormatterlocale]localeIdentifier],formattedDateString);
   mlabel.text=[NSString stringWithFormat:@"%@",formattedDateString];

You can replace the above code with your original  files and run to see date.




Blogger Widgets