Monday, 9 March 2015

Send Mail in java Example

Send Mail

here is java program to send a mail to one or more recipients.


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {

public boolean sendMail(String file,String camp,String recipients)
{

     String[] recipientsList=recipients.split(";");
   
     String to = "to_address";
     String from = "from_address";

        // Assuming you are sending email from localhost
         String host = "yoursmtpserver";
     // Get system properties
     Properties properties = System.getProperties();

     // Setup mail server
     properties.setProperty("mail.smtp.host", host);
     properties.setProperty("mail.transport.protocol","smtp");
                      properties.setProperty("mail.smtp.starttls.enable","true");
     properties.put("mail.smtp.port", "587");
     properties.put("mail.smtp.auth", "true");
     properties.put("mail.debug", "true");
   
   
     // Get the default Session object.
     Session session = Session.getDefaultInstance(properties,new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication("from_address", "PASSWORD");
               }
           });

     try{
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
     
     
        for (String string : recipientsList) {
        message.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(string));
}
     
     
        // Set Subject: header field
        message.setSubject("Subject Here");

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText("MSG Body");
     
        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = file;
        DataSource source = new FileDataSource(filename);
     
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart );

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
     }catch (MessagingException mex) {
        mex.printStackTrace();
     }
return true;
  }





}

create custom list view in android


To create custom list view we need to follow following steps.


1) create new adapter we call it as CustomAdapter
   

public class CustomAdapter extends BaseAdapter {

        Context context;
        String[] UserName;
        String[] UserStatus;
       
        private static LayoutInflater inflater = null;

        public CustomAdapter(Context context, String[] data,String[] data1) {
            // TODO Auto-generated constructor stub
            this.context = context;
            this.UserName = data;
            this.UserStatus=data1;
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return UserName.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return UserName[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
           
              View vi = convertView;
                if (vi == null)
                    vi = inflater.inflate(R.layout.custome_listview_item, null);
                ImageView Uimg=(ImageView) vi.findViewById(R.id.imageView1);
                Uimg.setImageResource(R.drawable.header_bg_brown);
                TextView text = (TextView) vi.findViewById(R.id.ItemHeader);
                text.setText(UserName[position]);
                TextView textt = (TextView) vi.findViewById(R.id.Itemtext);
                textt.setText(UserStatus[position]);
                return vi;
      
        }
   }

2) then create layout file for custom list view row. we are calling it row because this layout will use to design  each row of list.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/royalblue_color"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:nextFocusRight="@+id/ItemHeader"
            />

       
        <TextView
            android:id="@+id/ItemHeader"
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:nextFocusLeft="@id/imageView1"
            android:text="Header"
            android:textColor="@color/white_color"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/Itemtext"
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/ItemHeader"
            android:text="Text"
            android:textColor="@color/white_color"
            android:textStyle="italic" />

    </RelativeLayout>

</LinearLayout>

3) adding item to list on activity 

ApplicationObjectsClass aoc = new ApplicationObjectsClass();

public class WebViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

                Users user = new Users();
                                        user.setUserID("Test1");
                                        user.setUserID("Test2");
                                        //as new user will come we will add them to this list
                                       
                                        aoc.addOnlineUser(user);
                                       
                                        int usercount = aoc.getOnlineUserList()
                                                .size();
                                        int count = 0;
                                       
                                        String[] listItem = new String[usercount];
                                        String[] listItemStatus = new String[usercount];
                                       
                                        for (Users object2 : aoc.getOnlineUserList()) {
                                       
                                            listItem[count] = object2.getUserID();
                                            listItemStatus[count] = "Status of "+ object2.getUserID();
                                           
                                            count++;
                                        }

                                       
                                        CustomAdapter custAdapter;
                                        custAdapter = new CustomAdapter(getBaseContext(), listItem,
                                                listItemStatus);
                                        ListView listV = (ListView) findViewById(R.id.listView1);
                                       
                                        listV.setAdapter(custAdapter);
                                       
                                        listV.setOnItemClickListener(new OnItemClickListener() {
                                           
                                        public void onItemClick(android.widget.AdapterView<?> adapter, View view, int position, long id) {
                                           
                                        Object item = adapter.getAdapter().getItem(position);
                                       
                                        Log.d("Get Item",item.toString());
                                           
                                        Intent intent = new Intent(getBaseContext(),ChatActivity.class);
                                        intent.putExtra("connectTo", item.toString());
                                       
                                       
                                        startActivity(intent);
                                           
                                        }});   
                                       
                                        final LinearLayout lm = (LinearLayout) findViewById(R.id.LinearLayout1);
                                       
        }
    }

Tuesday, 24 February 2015

Generate entity class from database table SQL server 2000



DECLARE @TableName VARCHAR(8000)
set @TableName = 'Your Table Name' -- Replace 'Your Table Name' with your table name
DECLARE @TableSchema VARCHAR(8000)
set @TableSchema = 'dbo' -- Replace 'dbo' with your schema name
DECLARE @result varchar(8000)
set @result = ''

SET @result = @result + 'using System;' + CHAR(13) + CHAR(13)

IF (@TableSchema IS NOT NULL)
BEGIN
    SET @result = @result + 'namespace ' + @TableSchema  + CHAR(13) + '{' + CHAR(13)
END

SET @result = @result + 'public class ' + @TableName + CHAR(13) + '{' + CHAR(13)

SET @result = @result + '#region Instance Properties' + CHAR(13) 

SELECT @result = @result + CHAR(13)
    + ' public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)
FROM
(
    SELECT  c.COLUMN_NAME   AS ColumnName
        , CASE c.DATA_TYPE  
            WHEN 'bigint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
            WHEN 'binary' THEN 'Byte[]'
            WHEN 'bit' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END           
            WHEN 'char' THEN 'String'
            WHEN 'date' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                       
            WHEN 'datetime' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                       
            WHEN 'datetime2' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                       
            WHEN 'datetimeoffset' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                   
            WHEN 'decimal' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                   
            WHEN 'float' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                   
            WHEN 'image' THEN 'Byte[]'
            WHEN 'int' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
            WHEN 'money' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                               
            WHEN 'nchar' THEN 'String'
            WHEN 'ntext' THEN 'String'
            WHEN 'numeric' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                           
            WHEN 'nvarchar' THEN 'String'
            WHEN 'real' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                       
            WHEN 'smalldatetime' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                   
            WHEN 'smallint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END           
            WHEN 'smallmoney' THEN 
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                       
            WHEN 'text' THEN 'String'
            WHEN 'time' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                                                                   
            WHEN 'timestamp' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
            WHEN 'tinyint' THEN
                CASE C.IS_NULLABLE
                    WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                               
            WHEN 'uniqueidentifier' THEN 'Guid'
            WHEN 'varbinary' THEN 'Byte[]'
            WHEN 'varchar' THEN 'String'
            ELSE 'Object'
        END AS ColumnType
        , c.ORDINAL_POSITION
FROM    INFORMATION_SCHEMA.COLUMNS c
WHERE   c.TABLE_NAME = @TableName and ISNULL(@TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA 
) t
ORDER BY t.ORDINAL_POSITION

SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13) 

SET @result = @result  + '}' + CHAR(13)

IF (@TableSchema IS NOT NULL)
BEGIN
    SET @result = @result + CHAR(13) + '}'
END


PRINT @result

Thursday, 21 August 2014

Send Email With ASP.NET C# with Formated Text

Send Email With ASP.NET C# with Formated Text

Here i have implemented Email send program with the console application just you need to use your email address and password from where you want to send the email.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Data;
namespace TaskRunner
{
    class Program
    {
        public static string connectionString="ServerName;Initial Catalog=DataBaseName;Persist Security Info=True;User";
   
   
        static void Main(string[] args)
        {
            Program p = new Program();
            p.SendMail();
        }
       
    protected void SendMail()
    {
 
        SqlConnection cn = new SqlConnection(@""+connectionString+"");
        DataSet ds = new DataSet();
        DateTime d = new DateTime();
        string yesterday = DateTime.Today.ToString("yyyy-MM-dd");
        string nextday = DateTime.Today.AddDays(1).ToString("yyyy-MM-dd");
   
        SqlDataAdapter da = new SqlDataAdapter("select * from Table where id=1", cn);
        da.Fill(ds);
        int i=0;
        for (i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            Console.WriteLine("Please wait ...");
            System.Net.Mail.MailMessage ms = new System.Net.Mail.MailMessage();
            var fromAddress = "from@gmail.com";      // Gmail Address from where you send the mail
            MailAddress to = new MailAddress("to@abc.com"); // Address to whome you send the mail
       
            string body = "Hi XYZ, <br>";
            body += "<h2>How are You?</h2><h3>Dear<br> Thank you, <br> From Jayesh Jakhaniya";
       
            ms.From = new MailAddress("from@gmail.com");
            ms.To.Add(to);
            ms.Subject = "Subject";
            ms.IsBodyHtml = true;
            ms.Body = body;
       
            var fromPassword = "password";
       
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
       
            smtp.Send(ms);
        }
   
    }
    }


}