Archive for the ‘C#.Net’ Category

How To Create An XML Document In C#

Sunday, March 29th, 2009

It is very easy, as there I wondered, here is the code:

?View Code CSHARP
using System.Xml.Linq
protected void CreateDocumentXML ()
{
XDocument TheCodersXML = new XDocument(
new XDeclaration("1.0","utf-8","yes")
new XComment("List of Students")
new XElement("Students"
new XElement("Student"
new XAttribute("Id","No:123")
new XElement("Name","Diana Wallwalker")
new XElement("Age","23")),
 
new XElement("Student"
new XAttribute("Id","No:456")
new XElement("Name","Danny Thomas")
new XElement("Age","27")),
 
new XElement("Student"
new XAttribute("Id","No:789")
new XElement("Name","Roger Benny")
new XElement("Age","20")),
 
new XElement("Student"
new XAttribute("Id","No:012")
new XElement("Name","Venu Thomas"),
new XElement("Age","26"))
)
);
}

In the end it saved in the address you want:

?View Code CSHARP
TheCodersXML.Save(@"c:\TheCodersXML.xml");

 

 Output:

<?xml version="1.0″ encoding="utf-8″ standalone="yes"?>
<!-- List of Students -->
<students>
	<student Id="No:123">
		<name>Diana Wallwalker</name>
		<age>23</age>
	</student>
	<student Id="No:456">
		<name>Danny Thomas</name>
		<age>27</age>
	</student>
	<student Id="No:789">
		<name>Roger Benny</name>
		<age>20</age>
	</student>
	<student Id="No:012">
		<name>Venu Thomas</name>
		<age>26</age>
	</student>
</students>

Validate: Username, Email Id, Phone No, Zip Code & URL In 5 Languages(JS, C#.Net, VB.Net, JAVA & PHP)

Monday, March 23rd, 2009

Validate of Username, Email Id, Phone No, Zip/Postal Code & URL In Javascript, C#.Net, VB.Net, JAVA & PHP !

1. Validate username: Validate alpha numeric values
2. Validate email addresses : example@domain.com
3. Validate Phone numbers: Validate US phone number eg: 123-456-7890
4. Validate Zip/Postal Codes: Validate US Zip/Postal Code eg: 12345-6789
5. Validate Domain Name eg: http://live.com

Validate username: Validate alpha numeric values

?View Code JAVASCRIPT
function is_valid_username(str_username)
{
 var filter = /^([a-zA-Z\s0-9]*)$/;
 if (!filter.test(str_username))
 {
 alert(’Wrong username format.’);
 }
 else
 {
 alert('Username format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_username(string str_username)
 {
 Regex matchRegex = new Regex(@"^[a-zA-Z0-9_]{3,16}$");
 MatchCollection matches  = matchRegex.Matches(str_username);
 if(matches.Count==0)
 {
 Response.Write("Wrong username format."); // In Webserver
 //MessageBox.Show("Wrong username format."); //In Windows Form
 }
 else
 {
 Response.Write("Username format is ok."); // In Webserver
 //MessageBox.Show("Username format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_username(ByVal str_username As String)
    Dim matchRegex As New Regex("^[a-zA-Z0-9_]{3,16}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_username)
    If matches.Count = 0 Then
        Response.Write("Wrong username format.") ' In Webserver
        'MessageBox.Show("Wrong username format."); 'In Windows Form
    Else
        Response.Write("Username format is ok.")    ' In Webserver
        'MessageBox.Show("Username format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
 
public class is_valid_username
{
 public static void main(String str_username)
 {
 Pattern p=Pattern.compile("^[A-Za-z0-9]+$");
 Matcher m=p.matcher(str_username);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Username format is ok.");
 }
 else
 {
 System.out.println("Wrong username format.");
 }
 }
}
Function is_valid_username($str_username)
{
 if (preg_match('/^[a-z\d_]{5,20}$/i',$str_username))
 {
     echo "Username format is ok.";
 }
 else
 {
     echo "Wrong username format.";
 }
}

Validate email addresses : example@domain.com

?View Code JAVASCRIPT
function is_valid_email(str_email_id)
{
 var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 if (!filter.test(str_email_id))
 {
 alert(’Wrong email address format.’);
 }
 else
 {
 alert('Email address format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 private void is_valid_email(string email_id)
 {
 Regex matchRegex = new Regex(@"[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}");
 MatchCollection matches  = matchRegex.Matches(email_id);
 if(matches.Count==0)
 {
 Response.Write("Wrong email address format."); // In Webserver
 //MessageBox.Show("Wrong email address format."); //In Windows Form
 }
 else
 {
 Response.Write("Email address format is ok."); // In Webserver
 //MessageBox.Show("Email address format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_email(ByVal email_id As String)
    Dim matchRegex As New Regex("[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}")
    Dim matches As MatchCollection = matchRegex.Matches(email_id)
    If matches.Count = 0 Then
        Response.Write("Wrong email address format.") ' In Webserver
        'MessageBox.Show("Wrong email address format."); 'In Windows Form
    Else
        Response.Write("Email address format is ok.")    ' In Webserver
        'MessageBox.Show("Email address format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_email
{
 public static void main(String str_email_id)
 {
 Pattern p=Pattern.compile("[a-zA-Z]*[0-9]*@[a-zA-Z]*.[a-zA-Z]*");
 Matcher m=p.matcher(str_email_id);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Email address format is ok.");
 }
 else
 {
 System.out.println("Wrong email address format.");
 }
 }
}
Function is_valid_email($email_id)
{
 if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email_id))
 {
     echo "Email address format is ok.";
 }
 else
 {
     echo "Wrong email address format.";
 }
}

Validate Phone numbers: Validate US phone number eg: 123-456-7890

?View Code JAVASCRIPT
function is_valid_phone_no(str_phone_no)
{
 var filter =  /^((\+?1-)?\d\d\d-)?\d\d\d-\d\d\d\d$/;
 if (!filter.test(str_phone_no))
 {
 alert(’Wrong phone number format.’);
 }
 else
 {
 alert('Phone number format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_phone_no(string str_phone_no)
 {
 Regex matchRegex = new Regex(@"\d{3}-\d{3}-\d{4}$");
 MatchCollection matches  = matchRegex.Matches(str_phone_no);
 if(matches.Count==0)
 {
 Response.Write("Wrong phone number format."); // In Webserver
 //MessageBox.Show("Wrong phone number format."); //In Windows Form
 }
 else
 {
 Response.Write("Phone number format is ok."); // In Webserver
 //MessageBox.Show("Phone number format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
Private Sub is_valid_phone_no(ByVal str_phone_no As String)
    Dim matchRegex As New Regex("\d{3}-\d{3}-\d{4}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_phone_no)
    If matches.Count = 0 Then
        Response.Write("Wrong phone number format.") ' In Webserver
        'MessageBox.Show("Wrong phone number format."); 'In Windows Form
    Else
        Response.Write("Phone number format is ok.")    ' In Webserver
        'MessageBox.Show("Phone number format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_phone_no
{
 public static void main(String str_phone_no)
 {
 Pattern p=Pattern.compile("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$");
 Matcher m=p.matcher(str_phone_no);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("Phone number format is ok.");
 }
 else
 {
 System.out.println("Wrong phone number format.");
 }
 }
}
Function is_valid_phone_no($str_phone_no)
{
 if (preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x',$str_phone_no))
 {
     echo "Phone number format is ok.";
 }
 else
 {
     echo "Wrong phone number format.";
 }
}

Validate Zip/Postal Codes: Validate US Zip/Postal Code eg: 12345-6789

?View Code JAVASCRIPT
function is_valid_zip_code(str_zip_code)
{
 var filter =  /^\d\d\d\d\d-\d\d\d\d$/;
 if (!filter.test(str_zip_code))
 {
 alert(’Wrong Zip/Postal Code format.’);
 }
 else
 {
 alert('Zip/Postal Code format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 
 private void is_valid_zip_code(string str_zip_code)
 {
 Regex matchRegex = new Regex(@"\d{5}-\d{4}$");
 MatchCollection matches  = matchRegex.Matches(str_zip_code);
 if(matches.Count==0)
 {
 Response.Write("Wrong Zip/Postal Code format."); // In Webserver
 //MessageBox.Show("Wrong Zip/Postal Code format."); //In Windows Form
 }
 else
 {
 Response.Write("Zip/Postal Code format is ok."); // In Webserver
 //MessageBox.Show("Zip/Postal Code format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
Private Sub is_valid_zip_code(ByVal str_zip_code As String)
    Dim matchRegex As New Regex("\d{5}-\d{4}$")
    Dim matches As MatchCollection = matchRegex.Matches(str_zip_code)
    If matches.Count = 0 Then
        Response.Write("Wrong Zip/Postal Code format.") ' In Webserver
        'MessageBox.Show("Wrong Zip/Postal Code format."); 'In Windows Form
    Else
        Response.Write("Zip/Postal Code format is ok.")    ' In Webserver
        'MessageBox.Show("Zip/Postal Code format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_zip_code
{
 public static void main(String str_zip_code)
 {
 Pattern p=Pattern.compile("^(\\d{5})[- ]?(\\d{4})$");
 Matcher m=p.matcher(str_zip_code);
 boolean matchFound = m.matches();
if(matchFound)
 {
 System.out.println("Zip/Postal Code format is ok.");
 }
 else
 {
 System.out.println("Wrong Zip/Postal Code format.");
 }
 }
}
Function is_valid_zip_code($str_zip_code)
{
 if (preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$str_zip_code))
{
     echo "Zip/Postal Code format is ok.";
 }
 else
 {
     echo "Wrong Zip/Postal Code format.";
 }
}

Validate Domain Name eg: http://live.com

?View Code JAVASCRIPT
function is_valid_url(str_url)
{
 var filter =   /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s&lt;&gt;\#%"\,\{\}\\|\\\^\[\]`]+)?$/
 if (!filter.test(str_url))
 {
 alert(’Wrong URL format.’);
 }
 else
 {
 alert('URL format is ok.')
 }
 return false;
}
?View Code CSHARP
 using System.Text.RegularExpressions;
 private void is_valid_url(string str_url)
 {
Regex matchRegex = new Regex(@"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?");
 MatchCollection matches  = matchRegex.Matches(str_url);
 if(matches.Count==0)
 {
 Response.Write("Wrong URL format."); // In Webserver
 //MessageBox.Show("Wrong URL format."); //In Windows Form
 }
 else
 {
 Response.Write("URL format is ok."); // In Webserver
 //MessageBox.Show("URL format is ok."); //In Windows Form
 }
 }
Imports System.Text.RegularExpressions
 
Private Sub is_valid_url(ByVal str_url As String)
    Dim matchRegex As New Regex("(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?")
    Dim matches As MatchCollection = matchRegex.Matches(str_url)
    If matches.Count = 0 Then
        Response.Write("Wrong URL format.") ' In Webserver
        'MessageBox.Show("Wrong URL format."); 'In Windows Form
    Else
        Response.Write("URL format is ok.")    ' In Webserver
        'MessageBox.Show("URL format is ok."); 'In Windows Form
    End If
End Sub
import java.util.regex.*;
public class is_valid_url
{
 public static void main(String str_url)
 {
 Pattern p=Pattern.compile("(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?");
 Matcher m=p.matcher(str_url);
 boolean matchFound = m.matches();
 if(matchFound)
 {
 System.out.println("URL format is ok.");
 }
 else
 {
 System.out.println("Wrong URL format.");
 }
 }
}
Function is_valid_url($str_url)
{
 if (preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$str_url))
 {
     echo "URL format is ok.";
 }
 else
 {
     echo "Wrong URL format.";
 }
}

C# From VB.NET

Saturday, March 7th, 2009

What is dfferent between C#.NET & VB.NET

Basic differences

  • C # will be marked in the case identifiers and method names and class names, VB does not distinguish.
  • VB is switched to late binding and early binding (Option Strict On / Off).
  • VB is whether to switch to force a variable’s type (Option Explicit On / Off).

Literals

Not easily accomplished

?View Code CSHARP
 
string s = "Welcome";
char ch = 'abc';
int i = 123;
long l = 123L;
double d = 123.0;
float f = 123.0F;
bool bl = true;
object o = null;
Dim s As String = "Welcome"
Dim ch As Char = "abc" c
Dim i As Integer = 123
Dim l As Long = 123L
Dim d As Double = 123.0
Dim f As Single = 123.0 F
Dim bl As Boolean = True
Dim o As Object = Nothing

Date Literals

Dim d1 = # 05 / 01 / 2008 #
Dim d2 = # 05 / 01 / 2008 12: 00: 00 AM #

I have another spare.

Array

Creation and access of the array

?View Code CSHARP
int [] array = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
/ / Skip
int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
/ / Type inference
var array = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
 
Console.WriteLine (array [0]);
Console.WriteLine (array [1]);
Console.WriteLine (array [2]);
Dim array () As Integer = new Integer () {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
'Omitted
Dim array () As Integer () = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
'Type inference
Dim array () = New Integer () {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
 
Console. WriteLine (array (0));
Console. WriteLine (array (1));
Console. WriteLine (array (2));

Operator

The difference is in this together as
Equal Sign:
C# : ==
VB.NET =
Inequality:
C# : !=
VB.NET: <>

Statement

Conditional or repetitive statement

?View Code CSHARP
int int_val = Get_Value ();
/ / Conditional branch
if (int_val == 0) {
/ / True
} Else {
/ / False
}
 
/ / For statement
for (int i = 0; i <10; i + +) {
/ / Processing
}
 
int [] int_Array = Get_Array ();
/ / Statement (Collection)
foreach (int i in int_Array) {
/ / Processing
}
Dim int_val As Integer = Get_Value ()
'Branches
If int_val = 0 Then
'True
Else
'False
End If
 
'Statement
For i As Integer = 0 to 10
'Treatment
End For
 
Dim int_Array As Integer (,) = Get_Array ()
'Statement (Collection)
For Each i As Integer in int_Array
'Treatment
Next

Namespace

Namespace

?View Code CSHARP
namespace TheCodersSpace {
/ / Define
}
 
/ / Import
using TheCodersSpace;
/ / Alias
using TC = TheCodersSpace;
Namespace TheCodersSpace
'Definition
End Namespace
 
'Import
Imports TheCodersSpace
'Alias
Imports TC = TheCodersSpace

Import XML namespace

Imports <xmlns:TheCoders="http://code.venuthomas.net">

Class

Class (VB, the class also included in the module)

?View Code CSHARP
class TheCoders {
}
 
/ / Static class
static class StaticTheCoders {
}
 
/ / Abstract base class
abstract class AbstractTheCoders {
}
 
/ / Inheritance
class ExtendTheCoders: TheCoders {
}
 
/ / No inheritance
sealed class SealedTheCoders {
}
Class TheCoders
End Class
 
'Static class (Module)
Module StaticTheCoders
End Module
 
'Base class
MustInherit Class AbstractTheCoders
End Class
 
'Inherited
Class ExtendTheCoders
Inherits TheCoders
End Class
 
'Not Inherited
NotInheritable Class SealedTheCoders
End Class

Interface

Interface

?View Code CSHARP
interface ITheCoders {
}
 
/ / Implementation
class TheCoders: ITheCoders {
}
Interface ITheCoders
End Interface
 
'Implementation
Class TheCoders
Implements ITheCoders
End Class

Structure

Structure

?View Code CSHARP
struct TheCoders {
public string Name;
}
Structure TheCoders
Public Name As String
End Structure

Methods

Method (professional function)

?View Code CSHARP
public void TheCodersDoSomething () {
}
 
/ / In argument
public void TheCodersPrintMessage (string message) {
}
/ / Two arguments, the overload
public void TheCodersPrintMessage (string message, int count) {
}
 
/ / Return value with
public string TheCodersGetMessage () {
}
 
/ / Overrides
public virtual void TheCodersOverridableMethod () {
}
 
/ / Overrides
public override void TheCodersOverridableMethod () {
}
 
/ / Redefinition
public new public void TheCodersReDeclareMethod () {
}
Public Sub TheCodersDoSomething ()
End Sub
 
'In argument
Public Sub TheCodersPrintMessage (ByVal message As String)
End Sub
'Two Arguments, Overloading
Public Sub TheCodersPrintMessage (ByVal message As String, ByVal count As Integer)
End Sub
 
'In Returns
Public Function TheCodersGetMessage () As String
End Function
 
'Can override
Public Overridable Sub TheCodersOverridableMethod ()
End Sub
 
'Override
Public Overrides Sub TheCodersOverridableMethod ()
End Sub
 
'Redefining
Public Shadows Sub TheCodersReDeclareMethod () {
}

Properties

Properties

?View Code CSHARP
private string name;
/ / Properties
public string Name {
get {return name;}
set {name = value;}
}
 
/ / Read-only property
public string TheCodersReadOnlyName {
get {return name;}
}
Private _name As String
'Properties
Public Property Name () As String
Get
Return _name
End Get
Set (ByVal value As String)
_name = value
End Set
End Property
 
'Read-only property
Public ReadOnly Property TheCodersReadOnlyName () As String
Get
Return _name
End Get
End Property

Generic

Generic

?View Code CSHARP
List<string> strList = new List<string>();
strList.Add ( "Venu");
strList.Add ( "Thomas");
 
/ / Class definition
class GenericTheCoders <t>  {
public T heCodersGetValue () {
}
}
Dim strList As List (Of String) = New List (Of String)
strList. Add ( "Venu")
strList. Add ( "Thomas")
 
/ / Class definition Class GenericTheCoders (Of T)
Public Function heCodersGetValue () As T
End Function
End Class

Nullable Types

Nullable there.

?View Code CSHARP
int i = null;
Dim i As Integer = Nothing

Type inference

Type inference, it is. NET 3.5 (C # 3.0, VB9) function from

?View Code CSHARP
var strVal = "Welcome";
var intVal = 1;
Dim strVal = "Welcome"
Dim intVal = 1

Lambda expression

Lambda expression

?View Code CSHARP
Func <int, int, int> func = (a, b) => a * b;
func (2, 3);
Dim func As Func (Of Integer, Integer, Integer) = Function (a, b) a * b
func (2, 3)

Also write this

Dim func = Function (a As Integer, b As Integer) a * b

VB.NET smarter than the type inference

Directives preprocessor

VB I was able to

?View Code CSHARP
# define TheCoders
 
# if TheCoders
/ / TheCoders
# else
/ / Not TheCoders
# endif
# Const TheCoders = True
 
# If TheCoders
'TheCoders
# Else
'Not TheCoders
# End If

Download Multiple Files Into One ZIP File

Monday, February 16th, 2009

How to Download Multiple Files Into One ZIP File

downloadDownload ICSharpCode.SharpZipLib.dll

Add this code as Class

using ICSharpCode.SharpZipLib.Zip;

Copy this code to your *.cs file