Common Regular Expression Patterns for C#

Email id validation

Regular expression:

  1. /^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ (Email Id)
  2. /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w- ]+\.)+[\w-]{2,4})?$/ (free/domain specific email id)

URL validation

Regular expression:

  1. /(http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?/ (with or without http)
  2. /((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\’|\# |!|\(|?|,| |>|<|;|\)])/( valid everywhere)

Password strength validation

Regular expression:

  1. / ^[a-z0-9\.@#\$%&]+$/ (only contains letter [a-z] digits[0-9], special characters(@#$%&))
  2. / ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/ (Minimum 8 characters at least 1 Alphabet and 1 Number)
  3. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/ (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
  4. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}/ (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
  5. / ^[a-zA-Z0-9\s]{7,16}$/ (Minimum length 7 and Maximum length 16 Characters allowed [a–z] [A-Z] [0-9])

Mobile number validation

Regular expression:

  1. / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)
  2. /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)
  3. ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)

String pattern validation

Regular expression:

  1. /(?s)^((?!manish).)*$/ (string contains manish)
  2. \d/ (at list one digit )
  3. /(.)*(\\d)(.)* / (contains number)
  4. /^\d$/ (contains only number )
  5. /^\d{11}$/ (contains only 11 digit number )
  6. /^[a-zA-Z]+$/ (contains only letter )
  7. /^[a-zA-Z0-9]+$/ (contains only letter and number )

Use of the regular expressions

Use the preceding regular expressions in the following ways.

In the following example, I am showing an email validation in various ways. Just replace the regular expression and use any of the others to use another validation.

Using JavaScript

  1. “text/javascript”>
  2.          function validateEmailId(email) {
  3.              var reg = regular expression above pattern
  4.              if (reg.test(email)) {
  5.                  mesg.innerHTML = “”;
  6.                  return true;
  7.              }
  8.              else {
  9.                  mesg.style.color = “red”;
  10.                  mesg.innerHTML = “Please provide a valid email address”;
  11.                  return false;
  12.              }
  13.          }
  14.     

Call the preceding method like.

Email Address:

  1. <asp:TextBox ID=“txtemail” runat=“server” onblur=“validateEmailId(this.value)”></asp:TextBox>
  2. <span id=“mesg” style=“font-size: small; position: relative;”>
  3.  </span>

Using C# server-side

Using a normal function:

ASP.NET

 

    • Email Address

 

  1. <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  2.     <asp:Label ID=“lblmsg” runat=“server” ></asp:Label>
  3.     <br/>
  4.     <asp:Button ID=“btnsubmit” runat=“server” Text=“Submit”
  5.         onclick=“btnsubmit_Click”  />
    • C#

 

  1. private bool validateEmailId(string emailId)
  2. {
  3.    return Regex.IsMatch
  4.    (
  5.       emailId,
  6.       @“^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$”,
  7.       RegexOptions.IgnoreCase
  8.    );
  9. }
    • Call the preceding function in a button click.

 

  1. protected void btnsubmit_Click(object sender, EventArgs e)
  2. {
  3.    if (validateEmailId(txtemail.Text.Trim()))
  4.    {
  5.       lblmsg.Text = string.Empty;
  6.    }
  7.    else
  8.    {
  9.       lblmsg.Text = “Please provide a valid email address”;
  10.       lblmsg.ForeColor = System.Drawing.Color.Red;
  11.    }
  12. }

Using RegularExpressionValidator

ASP.NET

    • Email Address:

 

  1. <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  2.     <asp:RegularExpressionValidator ID=“RegularExpressionValidator1” runat=“server”
  3.         ErrorMessage=“Please provide a valid email address”
  4.         ToolTip=“Please provide a valid email address”
  5.         ValidationExpression=“^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$”
  6.         ControlToValidate=“txtemail” ForeColor=“Red”>Please provide a valid email address</asp:RegularExpressionValidator>

Using CustomValidator

ASP.NET

    • Scripts

 

  1. “text/javascript”>
  2.         function validateEmailId(oSrc, args) {
  3.             if (args.Value > 0) {
  4.                 args.IsValid = (args.Value.match(/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/));
  5.             }
  6.         }
  7.     
    • Email Address:

 

  1. “text/javascript”>
  2.         function validateEmailId(oSrc, args) {
  3.             if (args.Value > 0) {
  4.                 args.IsValid = (args.Value.match(/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/));
  5.             }
  6.         }
  7.     
  8.    Email Address:
  9.     <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  10.     <asp:CustomValidator ID=“CustomValidator1” runat=“server”
  11.         ErrorMessage=“Please provide a valid email address”
  12.         ClientValidationFunction=“validateEmailId” ControlToValidate=“txtemail”
  13.         Display=“Dynamic” ForeColor=“Red”
  14.         ToolTip=“Please provide a valid email address”>Please provide a valid email address</asp:CustomValidator>
    Change the preceding regular expression in case you need to use another expression.

Use regular expression with Linq:

Regex.Match(hrefValue, @”^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$”).Success

Using MVC:

Data Annotations

Suppose we have a student class like follows:

  1. public partial class tblstudent
  2. {
  3.    public string Studentname { getset; }
  4.    public string Emailid { getset; }
  5. }

We can apply a regular expression like:

  1. [RegularExpression(@“^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$”, ErrorMessage = “Please provide a valid email address”)]
  2. public string Emailid { get; set; }

We can also extract a word or group of words from a string using a regular expression.

Suppose we want to extract a domain name and user name from an email id, then by using the following method we can do it.

Using C#:

  1. string hrefValue = txtemail .Text .Trim ();
  2. Match m = Regex.Match(hrefValue, @“^(\w+([-+.’]\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$”);
  3.             Response.Write(string .Format (“UserName : {0}”,  m.Groups[1].Value));
  4.             Response.Write(“<br/>”);
  5.             Response.Write(string.Format(“Domain : {0}”,  m.Groups[3].Value));

Using JavaScript:

  1. “text/javascript”>
  2.          function validateEmailId(email) {
  3.              var reg = /^(\w+([-+.’]\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$/;
  4.              var matches = email.match(reg);
  5.              UserId.innerHTML =‘UserName : ‘+ matches[1];
  6.              Domain.innerHTML =‘Domain : ‘+  matches[3];
  7.          }
  8.     

Convert TCVN3 to Unicode – Chuyển đổi xâu ký tự từ TCVN3 sang Unicode

Trong nhiều trường hợp cần phải chuyển đổi mã từ TCVN 3 sang Unicode. Bài này giới thiệu một thuật toán đơn giản cho phép chuyển đổi một xâu ký tự từ TCVN 3 sang Unicode.
Ý tưởng của thuật toán là xây dựng hai mảng chứa các ký tự tiếng Việt có dấu cho mã TCVN 3 và Unicode. Để không phải tìm kiếm mỗi khi gặp ký tự có dấu, cần xây dựng một mảng trung gian để chuyển đổi, điều này làm giảm đáng kể thời gian chuyển đổi.
1. Hàm Csharp

using System;
using System.Collections.Generic;
using System.Text;

class Converter {
    private static char[] tcvnchars = {
        ‘µ’, ‘¸’, ‘¶’, ‘·’, ‘¹’, 
        ‘¨’, ‘»’, ‘¾’, ‘¼’, ‘½’, ‘Æ’, 
        ‘©’, ‘Ç’, ‘Ê’, ‘È’, ‘É’, ‘Ë’, 
        ‘®’, ‘Ì’, ‘Ð’, ‘Î’, ‘Ï’, ‘Ñ’, 
        ‘ª’, ‘Ò’, ‘Õ’, ‘Ó’, ‘Ô’, ‘Ö’, 
        ‘×’, ‘Ý’, ‘Ø’, ‘Ü’, ‘Þ’, 
        ‘ß’, ‘ã’, ‘á’, ‘â’, ‘ä’, 
        ‘«’, ‘å’, ‘è’, ‘æ’, ‘ç’, ‘é’, 
        ‘¬’, ‘ê’, ‘í’, ‘ë’, ‘ì’, ‘î’, 
        ‘ï’, ‘ó’, ‘ñ’, ‘ò’, ‘ô’, 
        ‘­’, ‘õ’, ‘ø’, ‘ö’, ‘÷’, ‘ù’, 
        ‘ú’, ‘ý’, ‘û’, ‘ü’, ‘þ’, 
        ‘¡’, ‘¢’, ‘§’, ‘£’, ‘¤’, ‘¥’, ‘¦’
    };

    private static char[] unichars = {
        ‘à’, ‘á’, ‘ả’, ‘ã’, ‘ạ’, 
        ‘ă’, ‘ằ’, ‘ắ’, ‘ẳ’, ‘ẵ’, ‘ặ’, 
        ‘â’, ‘ầ’, ‘ấ’, ‘ẩ’, ‘ẫ’, ‘ậ’, 
        ‘đ’, ‘è’, ‘é’, ‘ẻ’, ‘ẽ’, ‘ẹ’, 
        ‘ê’, ‘ề’, ‘ế’, ‘ể’, ‘ễ’, ‘ệ’, 
        ‘ì’, ‘í’, ‘ỉ’, ‘ĩ’, ‘ị’, 
        ‘ò’, ‘ó’, ‘ỏ’, ‘õ’, ‘ọ’, 
        ‘ô’, ‘ồ’, ‘ố’, ‘ổ’, ‘ỗ’, ‘ộ’, 
        ‘ơ’, ‘ờ’, ‘ớ’, ‘ở’, ‘ỡ’, ‘ợ’, 
        ‘ù’, ‘ú’, ‘ủ’, ‘ũ’, ‘ụ’, 
        ‘ư’, ‘ừ’, ‘ứ’, ‘ử’, ‘ữ’, ‘ự’, 
        ‘ỳ’, ‘ý’, ‘ỷ’, ‘ỹ’, ‘ỵ’, 
        ‘Ă’, ‘Â’, ‘Đ’, ‘Ê’, ‘Ô’, ‘Ơ’, ‘Ư’
    };

    private static char[] convertTable;

    static Converter() {
        convertTable = new char[256];
        for (int i = 0; i < 256; i++)
            convertTable[i] = (char)i;
        for (int i = 0; i < tcvnchars.Length; i++)
            convertTable[tcvnchars[i]] = unichars[i];
    }

    public static string TCVN3ToUnicode(string value) {
        char[] chars = value.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            if (chars[i] < (char)256)
                chars[i] = convertTable[chars[i]];
        return new string(chars);
    }
}

2. Hàm trong SQL:
Vấn đề chuyển đổi font chữ trong SQL đã được nhắc đến nhiều, và nếu bạn là lập trình viên và đã làm nhiều dự án chắc là bạn đã từng gặp vấn đề này: Chuyển font từ TCVN3 sang Unicode.

Tôi xin giới thiệu các bạn hàm convert sau:

CREATE FUNCTION dbo.funConvertToUnicode
 (@strInput VARCHAR(4000)  )
RETURNS NVARCHAR(4000) AS  
BEGIN 
 DECLARE @strOutput NVARCHAR(4000)
 DECLARE @TCVN CHAR(671)
 DECLARE @UNICODE CHAR(671)
 SET @TCVN = 
 ',184, 181, 182, 183, 185, 168, 190, 187, 188, 189, 198,
  169, 202, 199, 200, 201, 203, 208, 204, 206, 207, 209, 
  170, 213, 210, 211, 212, 214, 221, 215, 216, 220, 222,
  227, 223, 225, 226, 228, 171, 232, 229, 230, 231, 233, 
  172, 237, 234, 235, 236, 238, 243, 239, 241, 242, 244, 
  173, 248, 245, 246, 247, 249, 253, 250, 251, 252, 254, 
  174, 184, 181, 182, 183, 185, 161, 190, 187, 188, 189, 198, 
  162, 202, 199, 200, 201, 203, 208, 204, 206, 207, 209, 163, 
  213, 210, 211, 212, 214, 221, 215, 216, 220, 222, 227, 223, 
  225, 226, 228, 164, 232, 229, 230, 231, 233, 165, 237, 234, 
  235, 236, 238, 243, 239, 241, 242, 244, 166, 248, 245, 246, 
  247, 249, 253, 250, 251, 252, 254, 167, '

 SET @UNICODE = 
 ',225, 224, 7843,227, 7841,259, 7855,7857,7859,7861,7863,
 226, 7845,7847,7849,7851,7853,233, 232, 7867,7869,7865,234, 
 7871,7873,7875,7877,7879,237, 236, 7881,297, 7883,243, 242, 
 7887,245, 7885,244, 7889,7891,7893,7895,7897,417, 7899,7901,
 7903,7905,7907,250, 249, 7911,361, 7909,432, 7913,7915,7917,
 7919,7921,253, 7923,7927,7929,7925,273, 193, 192, 7842,195, 
 7840,258, 7854,7856,7858,7860,7862,194, 7844,7846,7848,7850,
 7852,201, 200, 7866,7868,7864,202, 7870,7872,7874,7876,7878,
 205, 204, 7880,296, 7882,211, 210, 7886,213, 7884,212, 7888,
 7890,7892,7894,7896,416, 7898,7900,7902,7904,7906,218, 217, 
 7910,360, 7908,431, 7912,7914,7916,7918,7920,221, 7922,
 7926,7928,7924,272, '

 IF @strInput IS NULL RETURN ''
 IF @strInput = '' RETURN ''
 DECLARE @COUNTER INT
 DECLARE @POSITION INT
 SET @COUNTER = 1
 SET @strOutput = ''
 WHILE (@COUNTER <= LEN(@strInput))
 BEGIN
 SET @POSITION = CHARINDEX(','+CONVERT(CHAR(4),
  ASCII(SUBSTRING(@strInput, @COUNTER, 1)))+',', @TCVN, 1)
 IF @POSITION > 0
 SET @strOutput = @strOutput + 
  NCHAR(CONVERT(INT,SUBSTRING(@UNICODE, @POSITION+1, 4)))
 ELSE
 SET @strOutput = @strOutput + SUBSTRING(@strInput, @COUNTER, 1)
 SET @COUNTER = @COUNTER + 1
 END
 RETURN @strOutput 
END

Chú ý để hàm chạy đúng bạn cần để
SET @TCVN = ‘,184, 181, 182,…’

SET @UNICODE = ‘,225, 224, 7843,…’
Mỗi biến trên cùng 1 dòng code. Ở đây mình không trình bày được như vậy vì nếu để trên cùng dòng sẽ quá độ rộng của trình duyệt
Để chạy thử hàm trên bạn mở notepad, chọn font (Unikey) là TCVN3 và gõ vào chuỗi bất kỳ.
Vì dụ: SELECT [dbo].[fuConvertToUnicode] (‘Céng hßa x· héi chñ nghÜa ViÖt Nam’) –> Cộng hòa xã hội chủ nghĩa Việt Nam

AES 128bit Cross Platform (Java and C#) Encryption Compatibility

It seems quite a minor issue but doing cross platform encryption and decryption specifically AES was a bit a challenge for me. When you  get it working it just seems like no big change to the original code you where working on but you wasted fruitless hours debugging. Just sharing so that another person doesn’t have to waste time wondering why same settings produce a different cipher and going through a number of unhelpful posts where it ” works on my machine”.

I initially used ISO 10126 padding, but that seemed to produce a different cipher in C# and Java. I decided to go with no padding which leads me to the  cryptographic exception: Length of the data to decrypt is invalid. After some head banging I settled with PKCS7

Same encoding of strings has to be used in java and c#, other wise you will end up having different ciphers in java and c#.

The java code below uses a base64 util class from android SDK but you can replace it like with one from apache commons

C# encryption utility

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public RijndaelManaged GetRijndaelManaged(String secretKey)
        {
            var keyBytes = new byte[16];
            var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
            Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
            return new RijndaelManaged
            {
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                KeySize = 128,
                BlockSize = 128,
                Key = keyBytes,
                IV = keyBytes
            };
        }
        public byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
        {
            return rijndaelManaged.CreateEncryptor()
                .TransformFinalBlock(plainBytes, 0, plainBytes.Length);
        }
        public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
        {
            return rijndaelManaged.CreateDecryptor()
                .TransformFinalBlock(encryptedData, 0, encryptedData.Length);
        }
        /// <summary>
        /// Encrypts plaintext using AES 128bit key and a Chain Block Cipher and returns a base64 encoded string
        /// </summary>
        /// <param name="plainText">Plain text to encrypt</param>
        /// <param name="key">Secret key</param>
        /// <returns>Base64 encoded string</returns>
        public String Encrypt(String plainText, String key)
        {
            var plainBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(Encrypt(plainBytes, GetRijndaelManaged(key)));
        }
        /// <summary>
        /// Decrypts a base64 encoded string using the given key (AES 128bit key and a Chain Block Cipher)
        /// </summary>
        /// <param name="encryptedText">Base64 Encoded String</param>
        /// <param name="key">Secret Key</param>
        /// <returns>Decrypted String</returns>
        public String Decrypt(String encryptedText, String key)
        {
            var encryptedBytes = Convert.FromBase64String(encryptedText);
            return Encoding.UTF8.GetString(Decrypt(encryptedBytes, GetRijndaelManaged(key)));
        }

Java Encryption Utility

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
private final String characterEncoding = "UTF-8";
    private final String cipherTransformation = "AES/CBC/PKCS5Padding";
    private final String aesEncryptionAlgorithm = "AES";
    public  byte[] decrypt(byte[] cipherText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
        cipherText = cipher.doFinal(cipherText);
        return cipherText;
    }
    public byte[] encrypt(byte[] plainText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    {
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        plainText = cipher.doFinal(plainText);
        return plainText;
    }
    private byte[] getKeyBytes(String key) throws UnsupportedEncodingException{
        byte[] keyBytes= new byte[16];
        byte[] parameterKeyBytes= key.getBytes(characterEncoding);
        System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
        return keyBytes;
    }
    /// <summary>
    /// Encrypts plaintext using AES 128bit key and a Chain Block Cipher and returns a base64 encoded string
    /// </summary>
    /// <param name="plainText">Plain text to encrypt</param>
    /// <param name="key">Secret key</param>
    /// <returns>Base64 encoded string</returns>
    public String encrypt(String plainText, String key) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
        byte[] plainTextbytes = plainText.getBytes(characterEncoding);
        byte[] keyBytes = getKeyBytes(key);
        return Base64.encodeToString(encrypt(plainTextbytes,keyBytes, keyBytes), Base64.DEFAULT);
    }
    /// <summary>
    /// Decrypts a base64 encoded string using the given key (AES 128bit key and a Chain Block Cipher)
    /// </summary>
    /// <param name="encryptedText">Base64 Encoded String</param>
    /// <param name="key">Secret Key</param>
    /// <returns>Decrypted String</returns>
    public String decrypt(String encryptedText, String key) throws KeyException, GeneralSecurityException, GeneralSecurityException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException{
        byte[] cipheredBytes = Base64.decode(encryptedText, Base64.DEFAULT);
        byte[] keyBytes = getKeyBytes(key);
        return new String(decrypt(cipheredBytes, keyBytes, keyBytes), characterEncoding);
    }

Hopefully this saves someone time.

Source: https://zenu.wordpress.com/2011/09/21/aes-128bit-cross-platform-java-and-c-encryption-compatibility/

Using iTextSharp with asp.net to add header in pdf file

Introduction

I recently posted an article about using iTextSharp to generate pdf document from different source text. In this short post, I am going to explain how can we add header in the generated PDF document. I assume you know about basics of using iTextSharp. If you are not, I strongly recommend reading my last post here

Background

When generating PDF document, its often desirable that some specific header is included in the generated file. It could be to mention page number or some message or even some logo. We will see how to do that.

Article Body

We have already used iTextSharp dll in asp.net project in my last post. We had used this code to generate the PDF file by using a .txt file as a source

Document itextDoc = new Document();
PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc,Response.OutputStream);
StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
writer.Write(File.ReadAllText(@"E:\MyFolder\filename.txt"));
StringReader sr = new StringReader(sw.ToString());
//Parse into IElement
List<IElement> elements =HTMLWorker.ParseToList(sr,null);      
//Open the Document
itextDoc.Open();
//loop through all elements
foreach (IElement el in elements)
{
    //add individual element to Document
    itextDoc.Add(el);
}                
//Close the document
itextDoc.Close();
//set the Response object
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.End();

This is all fine. But this will create normal PDF file without any header. To include headers in all pages, We have to use PDFWriter PageEvents. To add PageEvent listner, a class has to be created which would implement IPdfPageEvent

For the purpose of adding header, we will write implementation for only 2 methods OnEndPage and OnOpenDocument. Enough theory! Lets see the code details

I have tried to code in much detail so it is easy to understand. As the iTextSharp is derived from iText Java library, you can read details of each class, their methods and purpose in Java documentation here

public class itextEvents : IPdfPageEvent
{
    //Create object of PdfContentByte
    PdfContentByte pdfContent;
    
    public void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
    {
        //We are going to add two strings in header. Create separate Phrase object with font setting and string to be included
        Phrase p1Header = new Phrase("BlueLemonCode generated page", FontFactory.GetFont("verdana",8));
        Phrase p2Header = new Phrase("confidential", FontFactory.GetFont("verdana",8));
        //create iTextSharp.text Image object using local image path
        iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\images\\bluelemoncode.jpg");
        //Create PdfTable object
        PdfPTable pdfTab = new PdfPTable(3);
        //We will have to create separate cells to include image logo and 2 separate strings
        PdfPCell pdfCell1 = new PdfPCell(imgPDF);
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell(p2Header);
        //set the alignment of all three cells and set border to 0
        pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
        pdfCell1.Border=0;               
        pdfCell2.Border=0;
        pdfCell3.Border=0;
        //add all three cells into PdfTable
        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        pdfTab.TotalWidth = document.PageSize.Width - 20;
        //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
        //first param is start row. -1 indicates there is no end row and all the rows to be included to write
        //Third and fourth param is x and y position to start writing
        pdfTab.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 15, writer.DirectContent);
        //set pdfContent value
        pdfContent = writer.DirectContent;
        //Move the pointer and draw line to separate header section from rest of page
        pdfContent.MoveTo(30, document.PageSize.Height - 35);
        pdfContent.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 35);
        pdfContent.Stroke();       
    }
}

as we are implementing interface IPdfPageEvent here, we will have to provide at least empty implementation of all the methods of IPdfPageEvent (which i have avoided posting here for clean code)

Finally, set the PageEvent of PdfWriter where we had created object of PdfWriter. So, the code becomes

1
2
3
Document itextDoc = new Document();
PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc,Response.OutputStream);
pdfDoc.PageEvent = new itextEvents();

I am using some random text file to generate PDF file and below is the file created by using above code. As you can see, the header contains image logo at extreme right, different text at middle and right of header. The header also has a line drawn at the bottom.

Note that the formatting of text inside generated PDF filecan be manipulated by implementing other methods of PageEvent like OnParagraph, OnSection. Also, we can include a watermark in all pages of of generated. We will leave some of these other features for next time.

List of Most Common Regular Expressions and Their Uses

Introduction

A regular expression is a pattern that could be matched against an input text. The following is the important list of regular expressions that we use widely in our application.

  1. Email id validation
  2. URL validation
  3. Password strength validation
  4. Mobile number validation
  5. String pattern validation

For using a regular expression in C# server-side we need to use the following namespace.

using System.Text.RegularExpressions;

Remember: Remove / at the start and the end of the string to convert a JavaScript Regex to C#.

Email id validation

Regular expression:

  1. /^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ (Email Id)
  2. /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)([\w- ]+\.)+[\w-]{2,4})?$/ (free/domain specific email id)

URL validation

Regular expression:

  1. /(http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?/ (with or without http)
  2. /((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\’|\# |!|\(|?|,| |>|<|;|\)])/( valid everywhere)

Password strength validation

Regular expression:

  1. / ^[a-z0-9\.@#\$%&]+$/ (only contains letter [a-z] digits[0-9], special characters(@#$%&))
  2. / ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/ (Minimum 8 characters at least 1 Alphabet and 1 Number)
  3. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/ (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
  4. / ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,10}/ (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
  5. / ^[a-zA-Z0-9\s]{7,16}$/ (Minimum length 7 and Maximum length 16 Characters allowed [a–z] [A-Z] [0-9])

Mobile number validation

Regular expression:

  1. / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)
  2. /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)
  3. ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)

String pattern validation

Regular expression:

  1. /(?s)^((?!manish).)*$/ (string contains manish)
  2. \d/ (at list one digit )
  3. /(.)*(\\d)(.)* / (contains number)
  4. /^\d$/ (contains only number )
  5. /^\d{11}$/ (contains only 11 digit number )
  6. /^[a-zA-Z]+$/ (contains only letter )
  7. /^[a-zA-Z0-9]+$/ (contains only letter and number )

Use of the regular expressions

Use the preceding regular expressions in the following ways.

In the following example, I am showing an email validation in various ways. Just replace the regular expression and use any of the others to use another validation.

Using JavaScript

  1. “text/javascript”>
  2.          function validateEmailId(email) {
  3.              var reg = regular expression above pattern
  4.              if (reg.test(email)) {
  5.                  mesg.innerHTML = “”;
  6.                  return true;
  7.              }
  8.              else {
  9.                  mesg.style.color = “red”;
  10.                  mesg.innerHTML = “Please provide a valid email address”;
  11.                  return false;
  12.              }
  13.          }
  14.     

Call the preceding method like.

Email Address:

  1. <asp:TextBox ID=“txtemail” runat=“server” onblur=“validateEmailId(this.value)”></asp:TextBox>
  2. <span id=“mesg” style=“font-size: small; position: relative;”>
  3.  </span>

Using C# server-side

Using a normal function:

ASP.NET

 

      Email Address

 

  1. <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  2.     <asp:Label ID=“lblmsg” runat=“server” ></asp:Label>
  3.     <br/>
  4.     <asp:Button ID=“btnsubmit” runat=“server” Text=“Submit”
  5.         onclick=“btnsubmit_Click”  />
      C#

 

  1. private bool validateEmailId(string emailId)
  2. {
  3.    return Regex.IsMatch
  4.    (
  5.       emailId,
  6.       @“^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$”,
  7.       RegexOptions.IgnoreCase
  8.    );
  9. }
      Call the preceding function in a button click.

 

  1. protected void btnsubmit_Click(object sender, EventArgs e)
  2. {
  3.    if (validateEmailId(txtemail.Text.Trim()))
  4.    {
  5.       lblmsg.Text = string.Empty;
  6.    }
  7.    else
  8.    {
  9.       lblmsg.Text = “Please provide a valid email address”;
  10.       lblmsg.ForeColor = System.Drawing.Color.Red;
  11.    }
  12. }

Using RegularExpressionValidator

ASP.NET

      Email Address:

 

  1. <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  2.     <asp:RegularExpressionValidator ID=“RegularExpressionValidator1” runat=“server”
  3.         ErrorMessage=“Please provide a valid email address”
  4.         ToolTip=“Please provide a valid email address”
  5.         ValidationExpression=“^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$”
  6.         ControlToValidate=“txtemail” ForeColor=“Red”>Please provide a valid email address</asp:RegularExpressionValidator>

Using CustomValidator

ASP.NET

      Scripts

 

  1. “text/javascript”>
  2.         function validateEmailId(oSrc, args) {
  3.             if (args.Value > 0) {
  4.                 args.IsValid = (args.Value.match(/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/));
  5.             }
  6.         }
  7.     
      Email Address:

 

  1. “text/javascript”>
  2.         function validateEmailId(oSrc, args) {
  3.             if (args.Value > 0) {
  4.                 args.IsValid = (args.Value.match(/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/));
  5.             }
  6.         }
  7.     
  8.    Email Address:
  9.     <asp:TextBox ID=“txtemail” runat=“server” ></asp:TextBox>
  10.     <asp:CustomValidator ID=“CustomValidator1” runat=“server”
  11.         ErrorMessage=“Please provide a valid email address”
  12.         ClientValidationFunction=“validateEmailId” ControlToValidate=“txtemail”
  13.         Display=“Dynamic” ForeColor=“Red”
  14.         ToolTip=“Please provide a valid email address”>Please provide a valid email address</asp:CustomValidator>
    Change the preceding regular expression in case you need to use another expression.

Use regular expression with Linq:

Regex.Match(hrefValue, @”^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$”).Success

Using MVC:

Data Annotations

Suppose we have a student class like follows:

  1. public partial class tblstudent
  2. {
  3.    public string Studentname { getset; }
  4.    public string Emailid { getset; }
  5. }

We can apply a regular expression like:

  1. [RegularExpression(@“^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$”, ErrorMessage = “Please provide a valid email address”)]
  2. public string Emailid { get; set; }

We can also extract a word or group of words from a string using a regular expression.

Suppose we want to extract a domain name and user name from an email id, then by using the following method we can do it.

Using C#:

  1. string hrefValue = txtemail .Text .Trim ();
  2. Match m = Regex.Match(hrefValue, @“^(\w+([-+.’]\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$”);
  3.             Response.Write(string .Format (“UserName : {0}”,  m.Groups[1].Value));
  4.             Response.Write(“<br/>”);
  5.             Response.Write(string.Format(“Domain : {0}”,  m.Groups[3].Value));

Using JavaScript:

  1. “text/javascript”>
  2.          function validateEmailId(email) {
  3.              var reg = /^(\w+([-+.’]\w+)*)@(\w+([-.]\w+)*\.\w+([-.]\w+)*)$/;
  4.              var matches = email.match(reg);
  5.              UserId.innerHTML =‘UserName : ‘+ matches[1];
  6.              Domain.innerHTML =‘Domain : ‘+  matches[3];
  7.          }
  8.     

Email Address:

  1. <asp:TextBox ID=“txtemail” runat=“server” onblur=“validateEmailId(this.value)”></asp:TextBox>
  2.                            <br/>
  3.                            <span id=“UserId” style=“font-size: small; position: relative;”></span>
  4.                            <br/>
  5.                            <span id=“Domain” style=“font-size: small; position: relative;”></span>

We need to make a group inside an expression using ( ) characters and extract that group value using the preceding process. For checking a regular expression click here.

Summary

In this illustration you came to understand the various types of regular expressions and their uses.

Tra cứu thông tin SQL

————————————–
–KIEM TRA XEM BANG COMPRESS HAY KHONG
————————————–

SELECT table_name, partition_name, compression, compress_for
FROM user_tab_partitions
WHERE table_name IN (‘CORE_MESSAGE_DATA’) ORDER BY PARTITION_NAME DESC;

—————————————
—————————————

————————————–
–KIEM TRA DUNG LUONG BANG
————————————–
select  segment_name, ((sum(bytes)/1024)/1024/1024) GB, segment_type
from  user_segments
–where segment_name like’%OPEN_CLOSE%’
group by segment_name, bytes, segment_type
ORDER BY bytes desc;

————————————-
————————————-

————————————-
–KIEM TRA SO SESSION ACTIVE
————————————-
select sysdate from dual;

select inst_id,sesion.sid,
sesion.serial#,
sesion.username,sesion.machine,program, logon_time,
sql_text, sesion.status
from gv$session sesion left join v$sqlarea sqlarea
on sesion.sql_hash_value = sqlarea.hash_value
and sesion.sql_address    = sqlarea.address
where sesion.username is not null –and sesion.status=’ACTIVE’
and username=’VTRACKING’ and  status=’ACTIVE’
and logon_time < sysdate
order by machine, username, sql_text;

/
ALTER SYSTEM KILL SESSION ‘1122,64741’;
—————————————–
–KIEM TRA BANG PHAN MANH
—————————————–
select owner,table_name,
round((blocks*8),2)||’kb’ “Fragmented size”,
round((num_rows*avg_row_len/1024),2)||’kb’ “Actual size”,
round((blocks*8),2)-round((num_rows*avg_row_len/1024),2)||’kb’,
((round((blocks*8),2)-round((num_rows*avg_row_len/1024),2))/round((blocks*8),2))*100 -10 ” reclaimable space %”
from dba_tables
where table_name =’CURRENT_MONITOR’;
/
select owner,table_name,
round((blocks*8),2)||’kb’ “Fragmented size”,
round((num_rows*avg_row_len/1024),2)||’kb’ “Actual size”,
round((blocks*8),2)-round((num_rows*avg_row_len/1024),2)||’kb’,
((round((blocks*8),2)-round((num_rows*avg_row_len/1024),2))/round((num_rows*avg_row_len/1024),2)*100) “% Fragmented”
from dba_tables
where table_name =’LOGIN_DEVICE_INFO’;
/
select username,count(*)from gv$session
where status=’INACTIVE’ group by username;

select username, machine, program, status, count(*) from gv$session
where status=’INACTIVE’ and username=’VTRACKING’
group by username, machine, program, status
order by   machine;

select username,count(*)from gv$session
where status=’ACTIVE’ group by username;

–session
select username, machine, program, status, count(*) from gv$session
where status=’ACTIVE’ and username=’VTRACKING’ –and inst_id =3
group by username, machine, program, status
order by   machine;

select inst_id, count(*) from gv$session
where status=’ACTIVE’ and username=’VTRACKING’ –and inst_id =3
group by inst_id;

SELECT distinct sess.process,
sess.status,
machine,
program,sess.logon_time,
sql.sql_text
FROM v$session sess,
v$sql SQL
WHERE sql.sql_id(+) = sess.sql_id
AND sess.type       = ‘USER’
AND sess.status     = ‘ACTIVE’
ORDER BY program, sql_text,machine, sess.logon_time;

SELECT object_name,
created,
last_ddl_time, status
FROM dba_objects
WHERE object_type = ‘INDEX’
AND object_name LIKE ‘CORE_MSG_DATA%’;

SELECT INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS FROM ALL_INDEXES
where TABLE_NAME LIKE ‘CORE_MESSAGE%’;

SELECT owner,
table_name,
TRUNC(SUM(bytes)                             /1024/1024) Meg,
ROUND( ratio_to_report( SUM(bytes) ) over () * 100) Percent
FROM
(SELECT segment_name table_name,
owner,
bytes
FROM dba_segments
WHERE segment_type IN (‘TABLE’, ‘TABLE PARTITION’, ‘TABLE SUBPARTITION’)
UNION ALL
SELECT i.table_name,
i.owner,
s.bytes
FROM dba_indexes i,
dba_segments s
WHERE s.segment_name = i.index_name
AND s.owner          = i.owner
AND s.segment_type  IN (‘INDEX’, ‘INDEX PARTITION’, ‘INDEX SUBPARTITION’)
UNION ALL
SELECT l.table_name,
l.owner,
s.bytes
FROM dba_lobs l,
dba_segments s
WHERE s.segment_name = l.segment_name
AND s.owner          = l.owner
AND s.segment_type  IN (‘LOBSEGMENT’, ‘LOB PARTITION’)
UNION ALL
SELECT l.table_name,
l.owner,
s.bytes
FROM dba_lobs l,
dba_segments s
WHERE s.segment_name = l.index_name
AND s.owner          = l.owner
AND s.segment_type   = ‘LOBINDEX’
)
WHERE owner IN UPPER(‘vtracking’)
GROUP BY table_name,
owner
HAVING SUM(bytes)/1024/1024 > 10
ORDER BY SUM(bytes) DESC ;

select
fs.tablespace_name                          “Tablespace”,
(df.totalspace – fs.freespace)              “Used MB”,
fs.freespace                                “Free MB”,
df.totalspace                               “Total MB”,
round(100 * (fs.freespace / df.totalspace)) “Pct. Free”
from
(select
tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from
dba_data_files
group by
tablespace_name
) df,
(select
tablespace_name,
round(sum(bytes) / 1048576) FreeSpace
from
dba_free_space
group by
tablespace_name
) fs
where
df.tablespace_name = fs.tablespace_name;

col tablespace_name format a16;
col file_name format a36;
SELECT TABLESPACE_NAME, FILE_NAME, BYTES
FROM DBA_DATA_FILES order by TABLESPACE_NAME;

COL sid            FOR 999999
COL lock_type      FOR A38
COL mode_held      FOR A12
COL mode_requested FOR A12
COL lock_id1       FOR A20
COL lock_id2       FOR A20
COL kill_sid       FOR A50

SELECT s.sid,
l.lock_type,
l.mode_held,
l.mode_requested,
s.logon_time, s.status, s.program,
‘alter system kill session ”’|| s.sid|| ‘,’|| s.serial#|| ”’ immediate;’ kill_sid
FROM   dba_lock_internal l,
v$session s
WHERE  s.sid = l.session_id
AND    UPPER(l.lock_id1) LIKE ‘%PKG_CORE_DATA_SYNTHESIS’
order by logon_time;
–AND    l.lock_type = ‘Body Definition Lock’;

alter system kill session ‘4855,35361’ immediate;
alter system kill session ‘2674,44737’ immediate;

Hướng dẫn phát wifi

Bước 1: Tạo Modem phát wifi
Chạy CMD bằng cách vào run gõ cmd nhấn Enter.
cửa số CMD hiện ra các bạn gõ lệnh này vào
netsh wlan set hostednetwork mode=allow ssid=DinhBe key=12345678
Trong đó ssid và key có thể thay đổi tùy ý rồi nhấn Enter

Bước 2: Phát wifi
các bạn gõ tiếp dòng lệnh này rồi nhấn Enter
netsh wlan start hostednetwork
Bước 3: Sharing Internet
các bạn vào theo đường dẫn này Control Panel\Network and Internet\Network Connections sẽ thấy xuất hiện thêm một modum ảo có tên là Local Area connection * 12

Chuột phải vào biểu tượng Local Area connection * 12 chon propesties chuyển qua thẻ sharing tích vào
Allow other network users to connect through this computer’s internet connection rồi nhấn OK

Như vậy là máy tính của các bạn đã có thể phát wifi rồi .

Để Kiểm tra Các bạn gõ tiếp lệnh này
netsh wlan show hostednetwork
Để tắt hostednetwork đã tạo các bạn gõ lệnh
netsh wlan stop hostednetwork
Để xóa tất cả các bạn gõ lệnh
netsh wlan set hostednetwork mode=disallow ssid=DinhBe key=12345678
Chúc các bạn thành công !!!

ORACLE : How to DROP a User who is connected – forcefully

The ideal way for all development shops to work is to have each developer have his own database, but as you all know life is not that easy on us!.

First

  • find the sessions for the users/schema , as a DBA use : select sid,serial# from v$session where username = '<user_schema>'
  • Then kill them with : alter system kill session '<sid>,<serial#>'

A query that produces ready-built kill-statements could be

select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'

This will return one kill statement per session for that user – something like:

alter system kill session '375,64855';

alter system kill session '346,53146';

  • Now Drop the user : drop user <user_schema_name> cascade;

 

Import/Export an oracle db/schema

  • Import:
    • Oracle DB setup with default DB
    • the username that has access to the import DB
    • Remember to set the character set if importing Unicode
  • Import/Export:
    • ip-address, SID, user/pass (sysDBA)

To export/import a DB using telnet/linux console:

  1. Set the environment variables (should exist)
    1
    2
    3
    4
    5
    6
    7
    <span style="text-decoration: underline;">Linux</span>:
    $ORACLE_HOME = /u01/app/oracle/product/10.2.0/db_1/bin
    $ORACLE_SID = myoracl
    $PATH = /u01/app/oracle/product/10.2.0/db_1/bin
     
    <span style="text-decoration: underline;">Windows</span>:
    SET NLS_LANG=AMERICAN_AMERICA.ELI8MSWIN1253
  2. Startup the DB (if needed)
    1
    sqlplus /nolog

    SQL prompt:

    1
    2
    3
    connect user/pass as sysdba
    startup
    exit
  3. Startup the listener (if needed)
    1
    2
    cd to oracle app product path ($ORACLE_HOME/bin)
    ./lsnrctl start
  4. Startup the em console (web interface, if needed)
    1
    ./emctl start
  5. Export data
    1. entire database:
      1
      exp dbuser/password FULL=y FILE=exportDB.dmp LOG=exportDB.log
    2. schema only:
      1
      exp dbuser/password FIlE=scott.dmp OWNER=scott
  6. Importdata
    1. if needed, create the user for the DB:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      CREATE USER username IDENTIFIED BY "username"
      DEFAULT TABLESPACE "USERS"
      TEMPORARY TABLESPACE "TEMP"
      PROFILE DEFAULT
      QUOTA UNLIMITED ON "USERS";
      GRANT "CONNECT" TO username;
      GRANT "DBA" TO username;
      GRANT CREATE session to username;
      ALTER USER username DEFAULT ROLE NONE;
    2. login with new user and try an sql statement:
      1
      select sysdate from dual;
    3. entire database:
      1
      imp dbuser/password FULL=y FILE=exportDB.dmp LOG=importDB.log
    4. schema only:
      1
      imp dbuser/password FIlE=scott.dmp

    Notes:
    – If you get an error that the export was not done by the user doing the import, you need to do it with the user who actually exported the .dmp file.
    – If you get an error trying to import and it stops, you may need to add: dbuser/password@db

import/export tables only:

  1. Export tables [emp] and [dept] from “scott” user:
    1
    exp dbuser/password FILE=scott.dmp TABLES=(emp,dept)
  2. Import tables [dept] and [emp] from “scott” user:
    1
    imp dbuser/password FIlE=importDB.dmp FROMUSER=scott TABLES=(dept,emp)

Display image from database in Image control without using Generic Handler in ASP.Net

In this article I will explain how to display images stored in database in ASP.Net Image control without using Generic HTTP Handler.
The images stored as Binary data will be fetched as BYTE Array and then the BYTE Array will be converted to BASE64 string and then assigned to the ASP.Net image control.
I have already explained how to upload files save files as binary data in database in my article Save Files to SQL Server Database using FileUpload Control. The same database is used for this article.
 
Binary Images stored in Database
The following screenshot displays database table with three images stored in it. The backup file of the database is present in the attached sample.

Display image from database in Image control without using Generic Handler in ASP.Net

 
HTML Markup
The HTML Markup consists of a DropDownList control which will populate the list of image files in database and a Image control to display the selected image.
<asp:DropDownList ID=”ddlImages” runat=”server” AppendDataBoundItems=”true” AutoPostBack = “true” OnSelectedIndexChanged = “FetchImage”>
    <asp:ListItem Text=”Select Image” Value=”0″ />
</asp:DropDownList>
<hr />
<asp:Image ID=”Image1″ runat=”server” Visible = “false”/>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Populating the List of Images in DropDownList control
Inside the Page Load event, I have written code to populate the list of images from database table.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        ddlImages.DataSource = GetData(“SELECT Id, Name FROM tblFiles”);
        ddlImages.DataTextField = “Name”;
        ddlImages.DataValueField = “Id”;
        ddlImages.DataBind();
    }
}
 
private DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings[“constr”].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        ddlImages.DataSource = GetData(“SELECT Id, Name FROM tblFiles”)
        ddlImages.DataTextField = “Name”
        ddlImages.DataValueField = “Id”
        ddlImages.DataBind()
    End If
End Sub
 
Private Function GetData(query As String) As DataTable
    Dim dt As New DataTable()
    Dim constr As String = ConfigurationManager.ConnectionStrings(“constr”).ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                sda.SelectCommand = cmd
                sda.Fill(dt)
            End Using
        End Using
        Return dt
    End Using
End Function
 
 
Displaying the binary image from database in Image Control without using Generic Handler
The following event handler is executed on the SelectedIndexChanged event of the DropDownList control. Here the binary image is fetched from database as BYTE array and then the BYTE array is converted to BASE64 string and displayed in Image control.
To know more about displaying binary image using BASE64 string please refer Display Byte Array as Image without using generic handler in ASP.Net.
C#
protected void FetchImage(object sender, EventArgs e)
{
    string id = ddlImages.SelectedItem.Value;
    Image1.Visible = id != “0”;
    if (id != “0”)
    {
        byte[] bytes = (byte[])GetData(“SELECT Data FROM tblFiles WHERE Id =” + id).Rows[0][“Data”];
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        Image1.ImageUrl = “data:image/png;base64,” + base64String;
    }
}
 
VB.Net
Protected Sub FetchImage(sender As Object, e As EventArgs)
    Dim id As String = ddlImages.SelectedItem.Value
    Image1.Visible = id <> “0”
    If id <> “0” Then
        Dim bytes As Byte() = DirectCast(GetData(Convert.ToString(“SELECT Data FROM tblFiles WHERE Id =”) & id).Rows(0)(“Data”), Byte())
        Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
        Image1.ImageUrl = Convert.ToString(“data:image/png;base64,”) & base64String
    End If
End Sub