Powered By Blogger

Friday, November 6, 2009

access specifiers in C# and VB.Net

Public, Private, Protected, Friend, Internal, Default


1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.

2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.

3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.

4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.

5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.

6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

difference between ADO and ADO.NET

  • ADO works with connected data. This means that when you access data, such as viewing and updating data, it is real-time, with a connection being used all the time.
  • The ADO.NET object is a lightweight object. The ADO Recordset was a huge object in ADO.
  • ADO.NET breaks the functionality of the ADO object to multiple classes, thereby allowing a focused approach to developing code.
  • The ADO.NET DataReader is equivalent to the "firehose" cursor.
  • The DataSet is a disconnected cache with tracking and control binding functionality.
  • The DataAdapter provides the ability to completely customize how the central data store is updated with the changes to a DataSet.
  • ADO allows you to create client-side cursors only, whereas ADO.NET gives you the choice of either using client-side or server-side cursors.
  • ADO allows you to persist records in XML format, ADO.NET allows you to manipulate your data using XML as the primary means.


difference between Classic ASP and ASP.NET

Major difference:

* Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles,
otherwise does'nt.

*Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET technology (which is the next generation of ADO).

Others:

*
In classic ASP, there was no server controls. You have to write all html tags manually. ASP.NET offers a very rich set of controls called Server Controls and Html Controls.

*Validation Controls.

*Debugging benefits-In classic ASP, debugging is a tough task because of limited support due to the interpreted model. In contrast, not only ASP.NET improves the performance over the interpreted model but also provides debugging tools for component developers and pages compiled into classes.

*Multi Language Support-Only VBScript and Javascript were available for scripting in ASP where as, in ASP.NET there are no such restrictions. The .NET compliant language can be used with ASP.NET including several like C# and VB.NET, where both of them are server-sided languages.

Abstract Class vs Interface with example

Abstract Class

-An abstract class is a special kind of class that cannot be instantiated.
-An abstract class is only to be sub-classed (inherited from).
-It enforces certain hierarchies for all the subclasses.
- A class may inherit only one abstract class, but may implement multiple number of Interfaces.


Interface

-An interface is not a class
-Interface have only Signature.
-
It does not have Contructor,destructor,Fileds
-


Difference:

*A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.

*Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.

*Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.

*Interface is used to "implements"; whereas abstract class is used to "extends".

* Interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.

*************************************************************************************

Multiple inheritance:
---------------------

Abstract class- A class may inherit only one abstract class.

Interface - A class may inherit several interfaces.

Access Modfiers
--------------------

An abstract class can contain access modifiers for the subs, functions, properties

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public

Speed
-------


Abstract class- Fast

Interface -Requires more time to find the actual method in the corresponding classes.

************************************************************************************


Example:

Abstract Class

public abstract class Employee
{
//we can have fields and properties


//in the Abstract class

protected String id;
protected String lname;
protected String fname;

//properties


public abstract String ID
{
get;
set;
}

public abstract String FirstName
{
get;
set;
}

public abstract String LastName
{
get;
set;
}
//completed methods


public String Update()
{
return "Employee " + id + " " +
lname + " " + fname +
" updated";
}
//completed methods


public String Add()
{
return "Employee " + id + " " +
lname + " " + fname +
" added";
}
//completed methods


public String Delete()
{
return "Employee " + id + " " +
lname + " " + fname +
" deleted";
}
//completed methods


public String Search()
{
return "Employee " + id + " " +
lname + " " + fname +
" found";
}

//abstract method that is different


//from Fulltime and Contractor

//therefore i keep it uncompleted and

//let each implementation

//complete it the way they calculate the wage.


public abstract String CalculateWage();

}

------------------

Interface

public interface IEmployee
{

// protected String id;
// protected String lname;
// protected String fname;


//just signature of the properties

//and methods.

//setting a rule or contract to be

//followed by implementations.


String ID
{
get;
set;
}

String FirstName
{
get;
set;
}

String LastName
{
get;
set;
}

// cannot have implementation


// cannot have modifiers public

// etc all are assumed public

// cannot have virtual


String Update();

String Add();

String Delete();

String Search();

String CalculateWage();
}


----------------

we cannot call abstract class directly, so create a child class to inherit the abstract class:

Here,

Emp_Fulltime- Child Class.

Employee- Abstract Class.



public class Emp_Fulltime : Employee
{

public Emp_Fulltime()
{
}


public override String ID
{
get

{
return id;
}
set
{
id = value;
}
}

public override String FirstName
{
get

{
return fname;
}
set
{
fname = value;
}
}

public override String LastName
{
get

{
return lname;
}
set
{
lname = value;
}
}

//common methods that are

//implemented in the abstract class

public new String Add()
{
return base.Add();
}
//common methods that are implemented


//in the abstract class

public new String Delete()
{
return base.Delete();
}
//common methods that are implemented


//in the abstract class

public new String Search()
{
return base.Search();
}
//common methods that are implemented


//in the abstract class

public new String Update()
{
return base.Update();
}

//abstract method that is different


//from Fulltime and Contractor

//therefore I override it here.

public override String CalculateWage()
{
return "Full time employee " +
base.fname + " is calculated " +
"using the Abstract class...";
}
}

------------------------

class - Emp_fulltime2

Interface - IEmployee



public class Emp_fulltime2 : IEmployee
{
//All the properties and


//fields are defined here!

protected String id;
protected String lname;
protected String fname;

public Emp_fulltime2()
{
//


// TODO: Add constructor logic here

//

}

public String ID
{
get

{
return id;
}
set
{
id = value;
}
}

public String FirstName
{
get
{
return fname;
}
set

{
fname = value;
}
}

public String LastName
{
get
{
return lname;
}
set
{
lname = value;
}
}

//all the manipulations including Add,Delete,


//Search, Update, Calculate are done

//within the object as there are not

//implementation in the Interface entity.

public String Add()
{
return "Fulltime Employee " +
fname + " added.";
}

public String Delete()
{
return "Fulltime Employee " +
fname + " deleted.";
}

public String Search()
{
return "Fulltime Employee " +
fname + " searched.";
}

public String Update()
{
return "Fulltime Employee " +
fname + " updated.";
}

//if you change to Calculatewage().


//Just small 'w' it will raise

//error as in interface

//it is CalculateWage() with capital 'W'.

public String CalculateWage()
{
return "Full time employee " +
fname + " caluculated using " +
"Interface.";
}
}

------------------------------



public void Call_Interface()

private void InterfaceExample_Click(object sender,
System.EventArgs e)
{
try

{

IEmployee emp;

Emp_fulltime2 emp1 = new Emp_fulltime2();

emp = emp1;
emp.ID = "2234";
emp.FirstName= "Rahman" ;
emp.LastName = "Mahmoodi" ;
//call add method od the object


MessageBox.Show(emp.Add().ToString());

//call the CalculateWage method

MessageBox.Show(emp.CalculateWage().ToString());


}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

}

--------------------

public void call_AbstractClass()

{
Employee emp;

emp = new Emp_Fulltime();


emp.ID = "2244";
emp.FirstName= "Maria" ;
emp.LastName = "Robinlius" ;
MessageBox.Show(emp.Add().ToString());

//call the CalculateWage method


MessageBox.Show(emp.CalculateWage().ToString());

}


Source:

Codeproject: http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

DotnetSpider: http://www.dotnetspider.com/resources/20897-What-Difference-Between-Interface-abstract.aspx

javascript for validation

function FilterNumberInput()
{

if(57<48) returnvalue="false;" keycode="="46)" returnvalue =" true;"><97)><65) returnvalue =" false;" keycode="="46||event.keyCode="="32||event.keyCode="="95)" returnvalue =" true;" keycode ="="" returnvalue =" false;" emailpat="/^(.+)@(.+)$/" specialchars="">@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null)
{
alert("Your Email Address must be valid!")
return false
}
var user=matchArray[1]
var domain=matchArray[2]
if (user.match(userPat)==null)
{
alert("Your Email Address must be valid!")
return false;
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null)
{
for (var i=1;i<=4;i++) { if (IPArray[i]>255)
{
alert("Your Email Address must be valid!")
return false
}
}
return true
}
var domainArray=domain.match(domainPat)
if (domainArray==null)
{
alert("Your Email Address must be valid!")

return false
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2>3)
{
alert("The Email Address must end in a three-letter domain, or two letter country.")
return false
}
if (len<2) regexp =" /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+="&%@!\-\/]))?/" retvalue =" inputString;" ch =" retValue.substring(0," ch ="="" retvalue =" retValue.substring(1," ch =" retValue.substring(0," ch =" retValue.substring(retValue.length-1," ch ="="" retvalue =" retValue.substring(0," ch =" retValue.substring(retValue.length-1," retvalue =" retValue.substring(0," ndecimal =" 0;" xtxt="textValue.value;" xtxt =" document.getElementById(" txtlen=" xTxt.length;" i =" 0;" x =" xTxt.substr(i," x ="="" ndecimal =" nDecimal"> 1)
{
alert("You have entered more than one decimal point!\nPlease only enter one!");
textValue.value="";
textValue.focus();
return false;
}
}
}

function IgnoreDecimal(textValue)

{
var nDecimal = 0;
var i;
var x;
var xTxt=textValue.value;
//var xTxt = document.getElementById("ctl00_ContentPlaceHolder1_txtBasicDuty").value;
var txtLen= xTxt.length;
for(i = 0; i < x =" xTxt.substr(i," x ="="" ndecimal =" nDecimal"> 0)
{
alert("You have entered decimal point!\nPlease ignore decimal point!");
textValue.value="";
textValue.focus();
return false;
}
}
}

CreditCard validation
---------------------------

public bool IsCreditCardValid(string cardNumber)
{
const string allowed = "0123456789";
int i;

StringBuilder cleanNumber = new StringBuilder();
for (i = 0; i < cardNumber.Length; i++) { if (allowed.IndexOf(cardNumber.Substring(i, 1)) >= 0)
cleanNumber.Append(cardNumber.Substring(i, 1));
}
if (cleanNumber.Length <> 16)
return false;

for (i = cleanNumber.Length + 1; i <= 16; i++) cleanNumber.Insert(0, "0"); int multiplier, digit, sum, total = 0; string number = cleanNumber.ToString(); for (i = 1; i <= 16; i++) { multiplier = 1 + (i % 2); digit = int.Parse(number.Substring(i - 1, 1)); sum = digit * multiplier; if (sum > 9)
sum -= 9;
total += sum;
}
return (total % 10 == 0);
}

--------------
public static bool IsDate(string strdt)
{
try
{
if (strdt.Trim() != "")
{
DateTime dt = Convert.ToDateTime(strdt);
}
return true;
}
catch
{
return false;
}
}


public static bool IsNumeric(string numberString)
{
try
{
if (numberString.Trim() != "")
{
double num = Convert.ToDouble(numberString);
}
return true;
}
catch
{
return false;
}
}

Tuesday, November 3, 2009

varchar and nvarchar in SQL Server

VARCHAR
  • VARCHAR is an abbreviation for variable-length character string.
  • VARCHAR is stored as regular 8-bit data.
  • Varchar (MAX) can hold max of 2,147,483,648 characters
NVARCHAR
  • The "N" in NVARCHAR means uNicode.
  • NVARCHAR strings are stored in the database as UTF-16 — 16 bits or two bytes per character
  • NVARCHARs use two bytes for each character, that means a given NVARCHAR can only hold 4,000 characters (not bytes) maximum.
  • NVARCHAR (MAX) can hold 1,073,741,823 characters
  • The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters.

  • The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables.

Wednesday, October 28, 2009

retrieve file from database c#

public void retrieveFile()
{

string fileId = "10";



connection.Open();
SqlCommand command = new SqlCommand("SELECT flname,flcontent FROM upload WHERE fid = @FileId", connection);

command.Parameters.AddWithValue("@FileId", fileId);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
byte[] content = reader["flcontent"] as byte[];
string filename = reader["flname"].ToString();
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Content-Length", content.Length.ToString());
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
//writeByteArrayToFile(content, filename);
}



}

Monday, October 26, 2009

upload and retrieve images,doc,docx,txt to and from database C#

create table imgupl(id int identity(1,1),filename varchar(500),uploadedfile image)

----------------------------------------

upload
--------

string fileName = System.IO.Path.GetFileName(this.FileUpload1.FileName);

byte[] fileContent = this.FileUpload1.FileBytes;

con.open();
using (SqlCommand command = new SqlCommand("insert into imgupl values(@Filename,@FileContent)", con))
{
SqlParameter fileNameParameter = new SqlParameter("@Filename", System.Data.SqlDbType.NVarChar, 255);
fileNameParameter.Value = fileName ;
SqlParameter fileContentParameter = new SqlParameter("@FileContent", System.Data.SqlDbType.Image);
fileContentParameter.Value = fileContent ;
command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
command.ExecuteNonQuery();
MyTemp = "Record Saved Successfully.";
}


----------------------------------------

download:
-------------
string fileId = "1";

using (SqlCommand command = new SqlCommand("SELECT filename ,uploadedfile FROM imgupl WHERE id = @FileId", connection))
{
command.Parameters.AddWithValue("@FileId", fileId.Replace("-", "||"));
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
byte[] content = reader["uploadedfile "] as byte[];
string filename = reader["filename "].ToString();
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Content-Length", content.Length.ToString());
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}
}





----------------------------------------

Export DataSet To Excel VB.Net

Public Sub ExportDataSetToExcel(ByVal dt As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
' create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
' instantiate a datagrid
Dim dg As New GridView()
dg.AllowPaging = False
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub

covert number into words(like denomination)

Public Function Fn_NumToWord(ByVal NumVal As Integer) As String
Dim NoArr() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0}
Dim StrLength, i As Integer
Dim TNo As String
TNo = Trim(Str(NumVal))
StrLength = Len(TNo)

For i = 0 To StrLength - 1
NoArr(i) = Microsoft.VisualBasic.Right(TNo, 1)
TNo = Microsoft.VisualBasic.Left(TNo, StrLength - (i + 1))
Next i

Fn_NumToWord = ConvStr(NoArr)
End Function

Private Function ConvStr(ByVal NoA As Integer()) As String
Dim CrVal, LakVal, ThVal, Hval, LaVal As Integer
Dim CoStr As String

CrVal = (NoA(8) * 10) + NoA(7)
LakVal = (NoA(6) * 10) + NoA(5)
ThVal = (NoA(4) * 10) + NoA(3)
Hval = NoA(2)
LaVal = (NoA(1) * 10) + NoA(0)

CoStr = IndStr(CrVal, 0) & IndStr(LakVal, 1) & IndStr(ThVal, 2) & IndStr(Hval, 3)

Dim LaStr As String = IndStr(LaVal, 4)

If CoStr <> "" And LaStr <> "" Then
ConvStr = CoStr & " and " & LaStr
Else
ConvStr = CoStr & LaStr
End If

End Function

Private Function IndStr(ByVal NoVal As Integer, ByVal OrdNo As Integer) As String
Dim S, K As String
Dim LastStr() As String = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Tweleve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen ", "Twenty"}
Dim OrdArr() As String = {"Crore ", "Lakh ", "Thousand ", "Hundred ", ""}
Dim Valstr() As String = {"", "", "Twenty ", "Thirty ", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}

If NoVal < 20 Then
S = LastStr(NoVal)
Else
S = Valstr(Int(NoVal / 10)) & LastStr(NoVal Mod 10)
End If

If S <> "" Then IndStr = S & OrdArr(OrdNo)

End Function

date coversion(American to Indian Format and vice versa)

Change the culture
for Indian date date format(dd/MM/yyyy)

<%@ Page Language="C#" MasterPageFile="~/MasterUser.master" Culture="en-CA" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="default" Title="" %>



C#
---------

public string IndianDateConverter(string Dat)
{
string[] StrArr;
string str;
StrArr = Dat.Split('/');
str = Convert.ToString(StrArr[0]);
StrArr[0] = Convert.ToString(StrArr[1]);
StrArr[1] = str;
Dat = "";
Dat = StrArr[0] + "/";
Dat += StrArr[1] + "/";
Dat += StrArr[2];
return Dat;
}




VB.Net
-----------

Public Function fn_convertdate(ByVal dates As String) As String
Try
Dim strr(), str As String

str = dates
strr = dates.Split("/")
str = strr(0)
strr(0) = strr(1)
strr(1) = str

dates = ""
dates = strr(0) & "/"
dates += strr(1) & "/"
dates += strr(2)

Return dates
Catch ex As Exception

End Try

End Function

validate programmatically VB.Net

Public Function Fn_Check_Characters(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Characters = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46)) Then
Fn_Check_Characters = False
Exit For
End If
Next
End Function

Public Function Fn_Check_DataGrid_String(ByVal NewStr As String) As Boolean
Dim Str, j As String
Dim i As Integer
Fn_Check_DataGrid_String = True
For i = 1 To Len(NewStr)
j = Mid(NewStr, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46)) Then
Fn_Check_DataGrid_String = False
Exit For
End If
Next
End Function

Public Function Fn_Check_Extra_Characters(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Extra_Characters = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46) Or (Asc(j) = 44) Or (Asc(j) = 47) Or (Asc(j) = 40) Or (Asc(j) = 41) Or (Asc(j) = 59)) Then
Fn_Check_Extra_Characters = False
Exit For
End If
Next
End Function

Public Function Fn_Check_Pure_Numbers(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Pure_Numbers = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_Pure_Numbers = False
Exit For
End If
Next
End Function

Public Function Fn_Check_Pure_Numbers1(ByVal T As String) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T
Fn_Check_Pure_Numbers1 = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_Pure_Numbers1 = False
Exit For
End If
Next
End Function

Public Function Fn_Check_DataGrid_Numbers(ByVal NewStr As String) As Boolean
Dim j As String
Dim i As Integer
Fn_Check_DataGrid_Numbers = True
For i = 1 To Len(NewStr)
j = Mid(NewStr, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_DataGrid_Numbers = False
Exit For
End If
Next
End Function

Public Function Fn_Check_Numbers(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i, Cnt As Integer
Cnt = 0
Str = Trim(T.Text)
Fn_Check_Numbers = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If j = "." Then
Cnt = Cnt + 1
If Cnt = 2 Then
Fn_Check_Numbers = False
Exit For
End If
End If
If Not ((Asc(j) >= 48 And Asc(j) <= 57) Or Asc(j) = 46 Or Asc(j) = 45) Then
Fn_Check_Numbers = False
Exit For
End If
Next
End Function

Public Function Fn_Check_Alpha_Numeric(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Alpha_Numeric = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) >= 48 And Asc(j) <= 57) Or (Asc(j) = 46)) Then
Fn_Check_Alpha_Numeric = False
Exit For
End If
Next
End Function

Public Function Fn_Date_Validations(ByVal EDay As DropDownList, ByVal Emonth As DropDownList, ByVal EYear As DropDownList) As Boolean
Dim Str As String
Fn_Date_Validations = True
If Emonth.SelectedItem.Text = "Feb" Then
If (Val(EYear.SelectedItem.Text) Mod 4) = 0 Then
If Val(EDay.SelectedItem.Text) > 29 Then
Fn_Date_Validations = False
Exit Function
End If
Else
If Val(EDay.SelectedItem.Text) > 28 Then
Fn_Date_Validations = False
Exit Function
End If
End If
Else
Str = Emonth.SelectedItem.Text
If Not (Str = "Jan" Or Str = "Mar" Or Str = "May" Or Str = "Jul" Or Str = "Aug" Or Str = "Oct" Or Str = "Dec") Then
If Val(EDay.SelectedItem.Text) > 30 Then
Fn_Date_Validations = False
Exit Function
End If
End If
End If
End Function

Public Sub Pr_Month_Numeric_Validations(ByVal EDay As DropDownList, ByVal Emonth As DropDownList, ByVal EYear As DropDownList)
Dim Str As String
If EYear.SelectedItem.Text = "Year" Or Emonth.SelectedItem.Text = "Month" Then
Exit Sub
End If
If Emonth.SelectedItem.Text = "2" Then
If (EYear.SelectedItem.Text Mod 4) = 0 Then
Call Pr_Fill_Combo_Days(EDay, 29)
Else
Call Pr_Fill_Combo_Days(EDay, 28)
End If
Else
Str = Emonth.SelectedItem.Text
If Str = "1" Or Str = "3" Or Str = "5" Or Str = "7" Or Str = "8" Or Str = "10" Or Str = "12" Then
Call Pr_Fill_Combo_Days(EDay, 31)
Else
Call Pr_Fill_Combo_Days(EDay, 30)
End If
End If
End Sub


Public Function removesplcharacter(ByVal ValArray() As Char) As String
Dim usability As String = ""

For i As Integer = 0 To ValArray.Length - 1
If Not ValArray(i) = " " And Not ValArray(i) = "-" And Not ValArray(i) = "." Then
usability = usability + ValArray(i)
End If
Next

Return usability

End Function

create table programmatically with 'n' number of column c#


public int CreateTable(string tabname1,string tabname2,string[] MyAtt)
{
try
{
MyAtt = tabname1;
MyProd = tabname2;
SB.Append("CREATE TABLE " + MyProd + " (");
SBB.Append("CREATE TABLE " + MyProd + "_QUERYLOG (");
for (int i = 0; i < MyAtt.Length; i++)
{

if (i == MyAtt.Length-1)
{
SB.Append(MyAtt[i] + " BIT,");
SBB.Append(MyAtt[i] + " BIT)");
}
else
{
SB.Append(MyAtt[i] + " BIT,");
SBB.Append(MyAtt[i] + " BIT,");
}

}
SB.Append("DESCRIPTION VARCHAR(500),NOTEPAD IMAGE,MAXIVISI INT,FILNAM VARCHAR(500))");
int I = DAL.CreateTab(SBB.ToString());
int y = DAL.CreateTab(SB.ToString());
return y;
}
catch
{
return 0;
}
}

fill ListBox ,CheckBoxList programetically

public CheckBoxList ChkBxLst(CheckBoxList ck, DataTable MyDT)
{
ck.Items.Clear();
for (int i = 0; i < MyDT.Rows.Count; i++)
{
ck.Items.Add(MyDT.Rows[i][0].ToString());
}
return ck;
}

public ListBox MyListBox (ListBox LB, DataTable MyDT)
{
LB.Items.Clear();
for (int i = 0; i < MyDT.Rows.Count-2; i++)
{
LB.Items.Add(MyDT.Rows[i][0].ToString());
}
return LB;
}

split, substring and remove null values in string array in c#

public string[] MySplit(string SplitStr,string SplitbyStr)
{
Sltstr = SplitStr.Split((SplitbyStr).ToCharArray());
return Sltstr;
}

public string MySubString(string Mystr, int cnt)
{
MyInt = Mystr.Length;
if (cnt > MyInt)
{
MyTemp = Mystr.Substring(0, MyInt);
}
else
{
MyTemp = Mystr.Substring(0, cnt);
}
return MyTemp;
}

public string[] RemoveEmptyFromArray(string[] OriginalArray)
{

SB.Remove(0, SB.Length);
//IEnumerator IEnu = MySplit(OriginalArray[0],":") .GetEnumerator();
//while (IEnu.MoveNext())
//{
// if (IEnu.Current.ToString() != "")
// {
// sTmp.Append(IEnu.Current.ToString()+ "||");
// }
//}
for (int i = 0; i < OriginalArray.Length; i++)
{
string s = Convert.ToString(OriginalArray[i]);
//if (i == 0 && s != "")
// if (s == "")
if (i == 0 && s != null)
{
SB.Append(Convert.ToString(s));
}
else if (Convert.ToString(SB) == "" && s != null)
{
SB.Append(Convert.ToString(s));
}
else if (s != null)
{
SB.Append("|" + Convert.ToString(s));
}


//if (Convert.ToString(OriginalArray[i]) != "")
//{
// if (i == OriginalArray.Length - 1)
// {
// SB.Append(Convert.ToString(OriginalArray[i]));
// }
// else
// {
// SB.Append(Convert.ToString(OriginalArray[i]) + "|");
// }
//}

}
return MySplit(SB.ToString(), "|");



}

Restrict file selected in FileUpload control in Asp.Net



private bool IsValidFile(string filePath)
{
bool isValid = false;

string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".doc", ".docx", ".txt", ".rtf", ".RTF", ".DOC", ".DOCX", ".TXT", ".BMP", ".JPG", ".PNG", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;

}

}
return isValid;

}

reset controls in asp.net

C#:
------

public void ResetFormControlValues(this) 'or'
public void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;

}
}
}


------------------------------------------------------

VB.Net
----------

Public Sub ResetFormControlValues(ByVal parent As Control)

'Dim c As New Control
For Each c As Control In parent.Controls
If c.Controls.Count > 0 Then
ResetFormControlValues(c)
Else
Select Case (c.GetType().ToString())
Case "System.Web.UI.WebControls.TextBox"
CType(c, TextBox).Text = ""
Case "System.Web.UI.WebControls.CheckBox"
CType(c, CheckBox).Checked = False
Case "System.Web.UI.WebControls.RadioButton"
CType(c, RadioButton).Checked = False
Case "System.Web.UI.WebControls.DropDownList"
CType(c, DropDownList).SelectedIndex = 0
End Select
End If
Next

End Sub

fill treeview programmatically in asp.net

public void TreeViewPopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
tn.Text = dr["name"].ToString();
//tn.Value = dr["idd"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
//tn.PopulateOnDemand = ((int)dr["childnodecount"] > 0);
}
}

public void TreeViewPopulateSubLevel(String parentid, TreeNode parentNode)
{
DB.DbConnect(con);
cmd = new SqlCommand("select IDD,NAM,(select count(*) FROM model WHERE parentid=sc.idd) childnodecount FROM model sc where parentid='" + parentid + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
TreeViewPopulateNodes(dt, parentNode.ChildNodes);
}

public void TreeViewPopulateRootLevel(string Fld, TreeView TreeView1)
{
cmd = new SqlCommand("select IDD,NAM,(select count(*) FROM model WHERE parentid=sc.IDD) childnodecount FROM model sc where parentid IS NULL and nam='" + Fld + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
TreeViewPopulateNodes(dt, TreeView1.Nodes);
}