Tuesday, January 17, 2012

Catching SQLException in C#.Net


Catching SQLException in C#.Net :

Example : 



    public void InsertAttendance()
    {
        try
        {
            using (SqlConnection Con = new SqlConnection("ConnectionString"))
            {
                SqlCommand InserCmd = new SqlCommand();
                InserCmd.Connection = Con;
                InserCmd.CommandType = CommandType.StoredProcedure;
                InserCmd.CommandText = "SP_Name";


                Con.Open();
                InserCmd.ExecuteNonQuery();
                Con.Close();
            }
        }
        catch (SqlException SqlEx)
        {
            StringBuilder ErrorText = new StringBuilder();


            ErrorText.Append("Errors Count : " + SqlEx.Errors.Count + "<BR />");


            foreach (SqlError DBInsertErr in SqlEx.Errors)
            {
                ErrorText.Append("Error No. " + DBInsertErr.Number + " - " + DBInsertErr.Message + "<BR />");
            }


            Response.Write(ErrorText.ToString());
        }


        catch (Exception Ex)
        {
            Response.Write(ErrorText.ToString());
        }


    }

Error Handling in SQL Server


Error Handling in SQL Server 

Handling errors in SQL Server Stored Procedures is very essential and important from the prospective of performance and managing appropriate data in the palliation.  In the earlier version of SQL Server handling errors was not so easy task, you could test the value of @@ERROR or check @@ROWCOUNT, but if the error was a fatal error you did not have a lot of options.

With SQL Server 2005, new error handling technique has been introduced with the TRY...CATCH processing. From the Developer’s point view this new technique is very similar to TRY...CATCH processing that is there .Net. First it executes the SQL statement which we have written in the TRY block and if any error occurs, then it will get executed the CATCH block.

Syntax: 

BEGIN TRY
// SQL Statements
END TRY
BEGIN CATCH
//Handle the exception details
END CATCH

Below is the list Error handling properties : 

1. ERROR_NUMBER() : returns the error number regardless of how many times it is run, or where it is run within the scope of the CATCH block
2. ERROR_STATE() :  returns the error state regardless of how many times it is run, or where it is run within the scope of the CATCH block.
3. ERROR_SEVERITY() : returns the severity of the error message that caused the CATCH block to be run  
4. ERROR_LINE() : Returns the line number at which the error occurred. Also Returns the line number in a routine if the error occurred within a stored procedure or trigger. Returns NULL if called outside the scope of a CATCH block
5. ERROR_PROCEDURE() : returns the stored procedure name where the error occurred. Returns NULL if the error did not occur within a stored procedure or trigger. Returns NULL if called outside the scope of a CATCH block.
6. ERROR_MESSAGE() :  returns the complete text of the error message that caused the CATCH block to be run. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
7. RAISERROR() : CATCH blocks can use RAISERROR to rethrow the error that invoked the CATCH block by using system functions such as ERROR_NUMBER and ERROR_MESSAGE to retrieve the original error information. 

Example :

CREATE PROCEDURE Test
AS
BEGIN
BEGIN TRY
-- Generate a divide-by-zero error.
SELECT 1/0;
END TRY

BEGIN CATCH
DECLARE @ErrorNumber INT;
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
DECLARE @ErrorProcedure NVARCHAR(4000);
DECLARE @ErrorLine INT;
DECLARE @ErrorMessage NVARCHAR(4000);

SELECT
@ErrorNumber = ERROR_NUMBER(), 
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE(),
@ErrorProcedure = ERROR_PROCEDURE(),
@ErrorLine = ERROR_LINE(),
@ErrorMessage  = ERROR_MESSAGE();

RAISERROR(
@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
END
GO

Send Mail through Gmail or Hotmail using C#.Net


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;


public class SendMail_App
{

    public static bool SendMail(string message, string mailFrom, string mailTo, string subject)
    {
        //  Set Mail Properties
        MailMessage ourMessage = new MailMessage();
        ourMessage.To.Add(new MailAddress(mailTo));
        ourMessage.From = new MailAddress(mailFrom);
        ourMessage.Body = message;
        ourMessage.IsBodyHtml = true;
        ourMessage.Subject = subject;


        //  Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
        //SmtpClient Client = new SmtpClient("smtp.live.com", 25); //Send Mail using Hotmail
        SmtpClient Client = new SmtpClient("smtp.gmail.com", 587); //Send Mail using Hotmail
        Client.EnableSsl = true;
        Client.Credentials = new System.Net.NetworkCredential("Your Email ID", "Password");


        try
        {
            Client.Send(ourMessage);    // Send your mail.
            return true;                // IF Mail sended Successfully
        }
        catch (Exception ex)
        {
            return false;              // Send error
        }
    }

}