2012

Friday, December 28, 2012

Email Sender (Windows Form Application Sending Email Using using System.Net.Mail)



This application can send email using System.Net.Mail library...



#region  - Sending Method -
void SendReport(string host, 
string port,
string from, 
string password, 
string to, 
string bcc, 
string cc, 
string subject, 
string body)
{
 retry:
 try
 {
    MailMessage mMailMessage = new MailMessage();
    mMailMessage.From = new MailAddress(from);
    mMailMessage.To.Add(new MailAddress(to));
    if ((bcc != null) && (bcc != string.Empty))
    {
        mMailMessage.Bcc.Add(new MailAddress(bcc));
    }
    if ((cc != null) && (cc != string.Empty))
    {
        mMailMessage.CC.Add(new MailAddress(cc));
    }
    mMailMessage.Subject = subject;
    mMailMessage.Body = body;
    mMailMessage.IsBodyHtml = true;
    mMailMessage.Priority = MailPriority.Normal;
    SmtpClient smtp = new SmtpClient();
    if ((host != null) && (host != string.Empty))
    {
        smtp.Host = host;
    }
    else
    {
        smtp.Host = "smtp.gmail.com";
    }
    if(port!=null) && (port != string.Empty))
    {
        smtp.Port = int.Parse(port);
    }
    else
    {
        smtp.Port = int.Parse("587");
    }
    smtp.EnableSsl = true;
    smtp.Credentials = new System.Net.NetworkCredential(from, password);
    smtp.SendCompleted +=new SendCompletedEventHandler(smtp_SendCompleted);
    smtp.SendAsync(mMailMessage, new object());
    sendThread = new Thread(new ThreadStart(WhileSending));
    sendThread.Start();
}
catch (Exception ex)
{
    //??????????????????? Youre code here....
    if (You want to retry)
    {                   
        goto retry;
    }
}
}
#endregion  - Sending Method -
 #region - Method While Sending -
void WhileSending()
{
    int number = 4;
    while (IsSending)
    {
        Thread.Sleep(500);
        lblStatus.Text = "Sending email report ....".Substring(0, 20 + number);
        lblStatus.Image = global::ReportEmailer.Properties.Resources.send;
        number--;
        number = number <= 0 ? 4 : number;
    }
}
#endregion - Method While Sending -

System iMonitoring (Windows Form application using File System Watcher Control)










using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SystemEyeWatcher
{
public partial class SystemWatcher : Form
{
    enum Type
    {
        CREATED,
        CHANGED,
        RENAMED,
        DELETED
    }
    string name = String.Empty;
    public SystemWatcher()
    {
        InitializeComponent();
    }
    private void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ",
        DateTime.Now.ToString(), Type.CHANGED);
    }
    private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
        DateTime.Now.ToString(), Type.CREATED);
    }
    private void Watcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
        DateTime.Now.ToString(), Type.DELETED);
    }
    private void Watcher_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.OldFullPath, 
        e.OldName, e.Name, DateTime.Now.ToString(), Type.RENAMED);
    }
    private void watcherNew_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        SystemOptions sysOptions = new SystemOptions();
        sysOptions.ShowDialog();
        Cursor.Current = Cursors.Default;
    }
    private void watchStart_Click(object sender, EventArgs e)
    {
        lblStatus.Text = "Watching...";
        Watcher.Path = <Your Path>
        Watcher.Filter = <???>;
        Watcher.IncludeSubdirectories = true;
        Watcher.EnableRaisingEvents = true;
    }
    private void watchStop_Click(object sender, EventArgs e)
    {
        lblStatus.Text = "Ready...";
        Watcher.EnableRaisingEvents = false;
    }
    private void FillListWatch(ListView listViewWatch,
    string type,
    string objects, 
    string objectname, 
    string newobject, 
    string details, 
    Type objectsType)
    {
        ListViewItem item = new ListViewItem(type);
        item.SubItems.Add(objects);
        item.SubItems.Add(objectname);
        item.SubItems.Add(newobject);
        item.SubItems.Add(details);
        lblWatchType.Text = type;
        lblObjectName.Text = objectname + " : " + newobject;
        lblObjectPath.Text = objects;
        switch (objectsType)
        {
            case Type.CREATED:
                item.ImageIndex = 8;
                item.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
                break;
            case Type.CHANGED:
                item.ImageIndex = 9;
                item.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
                break;
            case Type.RENAMED:
                item.ImageIndex = 6;
                item.BackColor = System.Drawing.Color.FromArgb(128, 255, 128);
                break;
            case Type.DELETED:
                item.ImageIndex = 5;
                item.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
                break;
        }
        listViewWatch.Items.AddRange(new ListViewItem[] { item });
        lblEntries.Text = "Watched Entries : " + listViewWatch.Items.Count;
    }
    private void SystemWatcher_FormClosing(object sender, FormClosingEventArgs e)
    {
        ExitingApplication();
        Application.Exit();
    }
}
}

Saturday, October 27, 2012

Browser Database History ( Viewing Browser History and System History using SQLite in C# Windows Application )











public void GetDBTables(string databasePath, string filename)
{
    SQLiteConnection conn = new SQLiteConnection(@"Data Source=" + databasePath);
    try
    {
        conn.Open();
        SQLiteCommand cmd = new SQLiteCommand();
        cmd.Connection = conn;
        string[] restrictions = new string[4];
        restrictions[3] = "Table";
        DataTable tables = conn.GetSchema("Tables", restrictions);
        conn.Close();
        treeViewTables.Node tableNodes = new treeViewTables.Node(filename.Replace(".sqlite", " "));
        tableNodes.Name = "mdbNodes";
        tableNodes.ImageIndex = treeIndex;
        for (int i = 0; i < tables.Rows.Count; i++)
        {
            treeViewTables.Node dbTables = new treeViewTables.Node(tables.Rows[i][2].ToString().ToUpper());
            dbTables.ImageIndex = treeIndex;ex
            tableNodes.Nodes.Add(dbTables);
        }
        advTreeMDB.Nodes.Add(tableNodes);
        lblTableCount.Text = tables.Rows.Count + " Tables";
        mdbFile = databasePath;
    }
    catch (Exception ex)
    {
        if (ex.Message.Contains("Not a valid password."))
        {
            Password pwd = new Password();
            if (pwd.ShowDialog() == DialogResult.OK)
            {
                dbPwd = Password.dataPassword;
                GetDBTables(databasePath, filename);
            }            
        }
        return;
    }
}
private void GetColumns(string databasePath, string tables, string dbPwd)
{
    lstViewHistory.Clear();
    List<String> colList = new List<String>();
    string priKey = "";
    try
    {
        SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=" + databasePath);
        sqliteConn.Open();
        SQLiteDataReader reader;
        SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tables, sqliteConn);
        reader = cmd.ExecuteReader();
        
        //Create schemaTable
        DataTable schemaTable = reader.GetSchemaTable();
        for (int i = 0; i < schemaTable.Rows.Count; i++)
        {
            lstViewHistory.Columns.Add(schemaTable.Rows[i][0].ToString().ToUpper(), 100);
            colList.Add(schemaTable.Rows[i][0].ToString());
        }
        lblColumnCount.Text = schemaTable.Rows.Count + " Columns";
    }
    catch
    {
        <???????>
        return;
    }
    GetColumnsItems(databasePath, priKey, tables, colList, dbPwd);
}
private void GetColumnsItems(string databasePath, string PrimaryKey, string table, List<string> columns, string dbPwd)
{
    SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=" + databasePath);
    sqliteConn.Open();
    SQLiteCommand com = new SQLiteCommand("Select * From " + table, sqliteConn);
    SQLiteDataReader dr = com.ExecuteReader();
    int i = 1;
    while (dr.Read())
    {
        ListViewItem lv = new ListViewItem(dr[0].ToString());
        lv.ImageIndex = imgIndex;
        for (int col = 1; col < columns.Count; col++)
        {
            lv.SubItems.Add(dr[col].ToString());
        }
        if (lstViewHistory.Items.Count % 2 != 0)
            lv.BackColor = Color.White;
        else
            lv.BackColor = Color.WhiteSmoke;
        lstViewHistory.Items.AddRange(new ListViewItem[] { lv });
        lblRowCount.Text = i + " Rows";
        i++;
    }
}

CATE ( Converting Access To Excel using C# Windows Application)








This code snippet is used in converting access(.mdb,.accdb) to excel(.xls,xlsx);





int row = 1;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
 
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
 
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Columns.EntireColumn.NumberFormat = "@";
xlWorkSheet.Columns.NumberFormat = "@";
 
xlWorkSheet.Columns.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
xlWorkSheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
 
OleDbConnection oledbConn = new OleDbConnection(mdbConn);
oledbConn.Open();
OleDbCommand thisCommand = oledbConn.CreateCommand();
thisCommand.CommandText = "SELECT " + mdbColumns.Remove(mdbColumns.Length - 2) + " FROM " + mdbTable + "";
OleDbDataReader dr = thisCommand.ExecuteReader();
while (dr.Read())
{
    row++;
    int col = 1;
    foreach (string listColumn in columnList)
    {
    ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col]).Value2 = dr[listColumn].ToString();
    col++;
    }
bgWorker.ReportProgress(row);
}
 
dr.Close();
oledbConn.Close();
xlWorkBook.SaveAs(xlsFile + "\\" + xlsfilename + ".xls", 
    XlFileFormat.xlWorkbookNormal, misValue,
    misValue, misValue, misValue, 
    XlSaveAsAccessMode.xlExclusive,
    misValue, misValue, misValue, 
    misValue, misValue);
    
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
 
ImPixObject.ReleaseObject(xlWorkSheet);
ImPixObject.ReleaseObject(xlWorkBook);
ImPixObject.ReleaseObject(xlApp);



Saturday, September 15, 2012

Hexa-Decimal Coversion





   Hex Value             Decimal Value 
  0                         0
  1                         1
  2                         2
  3                         3
  4                         4
  5                         5
  6                         6
  7                         7
  8                         8
  9                         9
   A                         10
   B                         11
   C                         12
   D                         13
   E                         14
   F                         15
   .                          .
   .                          .
 so on ...........                    

  



Maximum Number (Retrieve Maximun Number Of Array)







public class MaximumNumber 
{
      public static void main(String[] args)
      {
       int[] numbers = {3,4,5,7};
        int max = 0;      

        for(int i=0;i<numbers.length;i++)
        {
           if(numbers[i] > max)
           {
               max = numbers[i];
           }
       } 
       System.out.println("Max Number In Array : " + max);
   }

}


EvenOdd-Number (Determine Even-Odd Number - Try Catch Handler)




import java.io.*;

public class EvenOddNumber{
    public static void main(String[] args) throws IOException{
    try{
       int n;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Enter Number : "); 
    n = Integer.parseInt(in.readLine()); 
    if (n % 2 == 0){
       System.out.println("Given number is Even.");
    }else{    
       System.out.println("Given number is Odd.");
    }
     }catch(NumberFormatException e){
     System.out.println(e.getMessage() + " is not a numeric value.");
           System.exit(0);
     }
    }
}


Anagrams ( Creating Anagrams -Entered Words )





import  java.io.*;
 
public class Anagrams
{
   public static void main(String[] args)throws IOException
   {
       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter a string:"); 
          String s = r.readLine(); 
              
          char[] text = new char[s.length()]; 
       for (int i=0; i<s.length(); i++)
       {
           text[i] = s.charAt(i);
       }
       System.out.println("Here are all the anagrams of " + s);
       printAnagrams(text, 0); 
   
   }
   
   public static void printAnagrams(char[] a, int i)
   {
       if (i == a.length-1)  printArray(a);
       else {
           for (int j=i; j< a.length; j++) {
               //swap a[i] with a[j]
               char c = a[i]; 
               a[i] = a[j]; 
               a[j] = c;
               printAnagrams(a, i+1);
               //swap back
               c = a[i]; 
               a[i] = a[j]; 
               a[j] = c;
           }
       }
   }
   static void printArray(char [] a)
   {
       for (int i=0; i< a.length; i++) System.out.print(a[i]); 
       System.out.println();
   } 
}