Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday 20 June 2015

Code to set ShortCut Keys in winforms

Introduction:
The shortcut keys are used to make your application user friendly and easy to use. But as you know there are some default short keys prepared by Microsoft Windows and some times you need to override these shortkeys.

Code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.B))  //Key combination
            {
                 // your code here
                return true;    // indicate that you handled this keystroke
            }

            if (keyData == Keys.Control) //Single Key
            {
                txtamount.Focus();
                return true;
            }

            // Call the base class
            return base.ProcessCmdKey(ref msg, keyData);
        }


Thursday 18 June 2015

Code to read content of Word/.doc file

Introduction: In this article I will explain how to read the content of a .doc file and show this in a Rich Textbox. And further we will filter the Email IDs form the content of the file.

NameSpace :
First of all you need to add a reference for ‘Microsoft.Office.Interop.Word’
And the use this namespace on your page.

using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
    
Code :
Here is the complete code:
private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op1 = new OpenFileDialog();
            op1.Multiselect = false;
            op1.ShowDialog();
            int count = 0;
            string[] FName;
            foreach (string s in op1.FileNames)
            {
                FName = s.Split('\\');
                //createting the object of application class 
                Microsoft.Office.Interop.Word.Application Objword = new Microsoft.Office.Interop.Word.Application();

                //creating the object of document class 
                Document objdoc = new Document();

                //get the uploaded file full path 
                dynamic FilePath = s;

                //pass the optional (missing) parameter to API 
                dynamic NA = System.Type.Missing;

                //open Word file document  
                objdoc = Objword.Documents.Open
                              (ref FilePath, ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA, ref NA,
                               ref NA, ref NA, ref NA

                               );


                //creating the object of string builder class 
                StringBuilder sb = new StringBuilder();

                for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)
                {
                    string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();

                    if (Filedata != string.Empty)
                    {
                        //Append word files data to stringbuilder 
                        sb.AppendLine(Filedata);
                    }

                }

                //closing document object  
                ((_Document)objdoc).Close();

                //Quit application object to end process 
                ((_Application)Objword).Quit();

                //assign stringbuilder object to show text in textbox 
                richTextBox1.Text = Convert.ToString(sb);
            }


            // Code to Find Email Ids from the file content.
            MatchCollection mc;
            mc = Regex.Matches(richTextBox1.Text, "([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})");
            string res = (mc.Count - 1).ToString();
            for (int i = 0; i < mc.Count; i++)
            {
                MessageBox.Show (mc[i].Value);
            }
        }


Code to Receive Email using Outlook in C#

Introduction: Here is the code to read mail from outlook. The outlook is software developed by Microsoft to configure your mail box on your computer. And by using this code we can use outlook mails to process our requirement. The attachment with mails is also processed in this article.

NameSpace :
First of all you need to add a reference for ‘Microsoft.Office.Interop.Outlook’
And the use this namespace on your page.

using OutlookApplication = Microsoft.Office.Interop.Outlook;
    
Code :
Here is the complete code to read mails from outlook :

{
       OutlookApplication._Application outlook = new OutlookApplication.ApplicationClass();
            OutlookApplication._NameSpace Oname = outlook.GetNamespace("MAPI");

            Oname.Logon("your default outlook profile name", Missing.Value, false, false);
            OutlookApplication._SyncObject _syncObject = null;
            _syncObject = Oname.SyncObjects[1];
            _syncObject.Start();

            //System.Threading.Thread.Sleep(30000);

            _syncObject.Stop();
            _syncObject = null;

            Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = Oname.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            OutlookApplication.Items attachItems = myInbox.Items;

            string filter = "@SQL=" + "urn:schemas:httpmail:subject LIKE '%HELLO%' AND "
                                           + "urn:schemas:httpmail:datereceived >= '"
                                           + (DateTime.Now.ToUniversalTime()).ToString("MM/dd/yyyy") + "' AND "
                                           + "urn:schemas:httpmail:hasattachment = True";

            attachItems = attachItems.Restrict(filter);
            if (attachItems.Count > 0)
            {
                foreach (OutlookApplication.MailItem mail in attachItems)
                {
                    //mail.SenderEmailAddress;
                    foreach (OutlookApplication.Attachment attach in mail.Attachments)
                    {
                        //check for Path.GetExtension(attach.FileName) == ".zip"
                        if (attach.Size > 0 & attach.Type == OutlookApplication.OlAttachmentType.olByValue)
                        {
                            //SAVE FILE
                            mail.UnRead = false;
                        }
                    }
                }
            }

            attachItems = null;
            myInbox = null;
            Oname.Session.Logoff();
            Oname.Logoff();
            Oname = null;
            outlook.Quit();
            outlook = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
}


Tuesday 9 June 2015

Upload file to FTP from windows form applications

Overview : Sometimes we need to upload some files to a web server from our desktop application. The file upload task is pretty easy in web applications but in desktop applications it is confusing because in websites we upload the files on the same server where we are working but in desktop applications we are working on a local computer and the server is come where else.
To overcome this issue I have created a function which will do this task for you.

public static void Fileuploader(string localpath, string username, string password)
        {
            var fileName = Path.GetFileName(localpath);
            var request = (FtpWebRequest)WebRequest.Create("ftp://www.example.com/httpdocs/_sft0258/" + fileName);

            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            using (var fileStream = File.OpenRead(localpath))
            {
                using (var requestStream = request.GetRequestStream())
                {
                    fileStream.CopyTo(requestStream);
                    requestStream.Close();
                }
            }

            var response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Success: {0}", response.StatusDescription);
            response.Close();
        }


By calling this function with correct parameters the upload file task will be completed smoothly.

Tuesday 12 May 2015

Creating simple login and registration form in WPF

Download the source code of the project from here : Login.ZIP

Introduction : 
In this article we are going to create a WPF application for simple login and registration process.

Step 1.
Open Visual Studio 2010 -> File -> New -> Project.
New project template will display and select WPF Application like as follows:


Give your project a meaningful name, I am naming my project as “CustomerRelationManagement”

Step 2. 
Here you will get MainWindow.xaml window, you can rename it to Login.xaml

Step 3.
Code in app.xaml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="conn"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Step 4.
Login.xaml

<Window x:Class="CustomerRelationManagement.Login"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Login" Height="400" Width="500" WindowStartupLocation="CenterScreen">
    <Grid Height="390" Width="475">
        <TextBox Height="23" HorizontalAlignment="Left" Margin="130,104,0,0" Name="txtemail" VerticalAlignment="Top" Width="246" BorderBrush="#FF1A0202" />
        <PasswordBox Height="23" HorizontalAlignment="Left" Margin="130,144,0,0" Name="txtpassword" VerticalAlignment="Top" Width="246" BorderBrush="#FF1A0202" />
        <Label Content="Email ID :" Height="28" HorizontalAlignment="Left" Margin="55,99,0,0" Name="label1" VerticalAlignment="Top" Foreground="#FF0062FF" FontSize="13" FontWeight="Bold" />
        <Label Content="Password :" Height="28" HorizontalAlignment="Left" Margin="48,139,0,0" Name="label2" VerticalAlignment="Top" Foreground="#FF0062FF" FontSize="13" FontWeight="Bold" />
        <Button Content="Login" Height="23" HorizontalAlignment="Left" Margin="130,192,0,0" Name="button1" VerticalAlignment="Top" Width="246" Click="button1_Click" />
        <Label Content="Sample Login Form" Height="35" HorizontalAlignment="Left" Margin="83,27,0,0" Name="label3" VerticalAlignment="Top" Width="282" HorizontalContentAlignment="Center" Foreground="Red" FontSize="15" FontWeight="SemiBold" />
        <Label Content="New User" FontSize="13" FontWeight="Bold" Foreground="#FF0062FF" Height="28" HorizontalAlignment="Left" Margin="207,257,0,0" Name="label4" VerticalAlignment="Top" />
        <Button Content="Register Here" Height="23" HorizontalAlignment="Left" Margin="282,262,0,0" Name="button2" VerticalAlignment="Top" Width="122" Click="button2_Click" />
    </Grid>
</Window>

Step 5. 
Login.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace CustomerRelationManagement
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Window
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
        public Login()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Register reg = new Register();
            reg.Show();
            this.Hide();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select * from employee where email = '" + txtemail.Text.Trim() + "' and password = '" + txtpassword.Password.Trim() + "'", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                Welcome wel = new Welcome(dt.Rows[0]["name"].ToString());
                wel.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("Invalid Details.");
            }
        }
    }
}


Step 6. 
Register.xaml

<Window x:Class="CustomerRelationManagement.Register"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Register" Height="500" Width="500" WindowStartupLocation="CenterScreen">
    <Grid Height="480" Width="480">
        <Label Content="Sample Registration Form" FontSize="15" FontWeight="SemiBold" Foreground="Red" Height="35" HorizontalAlignment="Left" HorizontalContentAlignment="Center" Margin="71,27,0,0" Name="label3" VerticalAlignment="Top" Width="282" />
        <TextBox BorderBrush="#FF1A0202" Height="23" HorizontalAlignment="Left" Margin="126,97,0,0" Name="txtemail" VerticalAlignment="Top" Width="246" />
        <Label Content="Email ID :" FontSize="13" FontWeight="Bold" Foreground="#FF0062FF" Height="28" HorizontalAlignment="Left" Margin="51,92,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox BorderBrush="#FF1A0202" Height="23" HorizontalAlignment="Left" Margin="126,139,0,0" Name="txtname" VerticalAlignment="Top" Width="246" />
        <Label Content="Name :" FontSize="13" FontWeight="Bold" Foreground="#FF0062FF" Height="28" HorizontalAlignment="Left" Margin="66,134,0,0" Name="label2" VerticalAlignment="Top" />
        <PasswordBox BorderBrush="#FF1A0202" Height="23" HorizontalAlignment="Left" Margin="126,180,0,0" Name="txtpassword" VerticalAlignment="Top" Width="246" />
        <Label Content="Password :" FontSize="13" FontWeight="Bold" Foreground="#FF0062FF" Height="28" HorizontalAlignment="Left" Margin="44,177,0,0" Name="label4" VerticalAlignment="Top" />
        <Button Content="Register" Height="23" HorizontalAlignment="Left" Margin="126,230,0,0" Name="btnreg" VerticalAlignment="Top" Width="246" Click="button1_Click" />
        <Button Content="Back to Login" Height="23" HorizontalAlignment="Left" Margin="12,296,0,0" Name="button2" VerticalAlignment="Top" Width="122" Click="button2_Click" />
    </Grid>
</Window>

Step 7.
Register.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Configuration;
using System.Data.SqlClient;

namespace CustomerRelationManagement
{
    /// <summary>
    /// Interaction logic for Register.xaml
    /// </summary>
    public partial class Register : Window
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
        public Register()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Login log = new Login();
            log.Show();
            this.Hide();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (txtemail.Text.Trim() != "" && txtname.Text.Trim() != "" && txtpassword.Password.Trim() != "")
            {
                try
                {
                    if (con.State == System.Data.ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    SqlCommand cmd = new SqlCommand("proc_register", con);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@email", txtemail.Text.Trim());
                    cmd.Parameters.AddWithValue("@name", txtname.Text.Trim());
                    cmd.Parameters.AddWithValue("@password", txtpassword.Password.Trim());
                    int i = cmd.ExecuteNonQuery();
                    if (i > 0)
                    {
                        MessageBox.Show("Registration Successfull.");
                        Login log = new Login();
                        log.Show();
                        this.Hide();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    con.Close();
                }
            }
            else
            {
                MessageBox.Show("Please fill all details");
            }
        }
    }
}


Step 8. 
Welcome.xaml

<Window x:Class="CustomerRelationManagement.Welcome"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Welcome" Height="300" Width="500" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Label" Height="33" HorizontalAlignment="Left" Margin="100,95,0,0" Name="label1" VerticalAlignment="Top" Width="303" />
    </Grid>
</Window>


Step 9. 
Welcome.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CustomerRelationManagement
{
    /// <summary>
    /// Interaction logic for Welcome.xaml
    /// </summary>
    public partial class Welcome : Window
    {
        static string nm;
        public Welcome(string name)
        {
            InitializeComponent();
            nm = name;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            label1.Content = "Welcome " + nm;
        }
    }
}

 Step 10. 
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="conn"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

 Step 11. 
Add service base database model to your project, in my case I have named it as Database1.mdf
And create a table named employee as


And a stored procedure named proc_register as

ALTER PROCEDURE dbo.proc_register
       @email nvarchar(max), @name nvarchar(max), @password nvarchar(max)
AS
begin
if not exists(select * from employee where email <> @email)
begin
  insert into employee(name, email, password)
  values(@name, @email, @password)
end  
end


to learn more about sql click here...




download the source code for the file from here : Login.ZIP