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
        }
    }

}

Friday, December 23, 2011

Nunit 2.5.2 dose not work with Visual Studio 2010 (i.e. with framework 4.0


Hi All

As we all know Nunit 2.5.2 dose not work with Visual Studio 2010 (i.e. with framework 4.0). By updating appropriate ‘config’ files of Nunit we can make it run for Visual Studio 2010.

Please follow the below steps:

1.    Go to flowing folder : C:\Program Files\NUnit 2.5.2\bin\net-2.0\
2.    Open the file ‘nunit.exe.config’ and/Or  ‘nunit-agent.exe.config’ and update it with the below attributes

Under <configuration> add:
<startup>
  <supportedRuntime version="v4.0.30319" />
</startup>

And under <runtime> add:
<loadFromRemoteSources enabled="true" />

Enjoy J

Thursday, December 22, 2011

ASP.Net DataBound Controls and their Differences

1. GridView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
4. Filter
5. Sort
(Renders Multiple records at time)
Additional Information Supports default as well as custom paging. Allows adding custom column and apply custom formatting to columns. Supports Data bound filed, DataControl filed, Command filed and Hyperlink filed.
2. DetailsView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Single records at a time)
Additional Information Supports default as well as custom paging if underlying data source supports paging. Supports Databound filed, DataControl filed, Command filed and Hyperlink filed.
3. FormView
Layouts Has no default layout and Need to set the custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Single records at a time)
Additional Information Supports default as well as custom paging if underlying data source supports paging. We can also customize the display format of FormView control by using style properties like EditRowStyle, EmptyDataRowStyle, FooterStyle, HeaderStyle, InsertRoStyle and PageStyle
4. Repeater
Layouts The Repeater control dose not have built in rendering of its own, which means we have to provide the layout for the repeater control by creating the Templates
Events Supported Read-only Data Presentation 
Additional Information Repeater control contains Header Template, ItemTemplete and Footer Template. Repeater control dose not support Paging, Insertion,  Selection, Editing, Deleting as this is Read-only data display control
5. DataListView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Multiple records at a time)
Additional Information DataListView control contains Header Template, Alternate Item Template, ItemTemplete and Footer Template. DataListView dose not support Sorting and Paging but dose support Selection and Editing.
6. ListView
Layouts Has no default layout and Need to set the custom layout
Events Supported 1. Insert
2. Update
3. Delete
4. Filter
5. Sort
(Renders Multiple records at a time)
Additional Information To show the data in the ListView Control we need to use the LayoutTmplete, ItemTempltete.
  

Hope this helps to understand the basic difference between the ASP.Net DataBound Controls

Check If URL Exists in ASP.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

namespace MyHttpHandler
{
public class URLChecker
{
protected bool DoseUrlExits(String UrlToCheck)
{
WebRequest req = WebRequest.Create(UrlToCheck);
WebResponse res;

bool IfUrlExitsFlag = false;
try
{
res = req.GetResponse();
IfUrlExitsFlag = true;
}
catch (Exception)
{
IfUrlExitsFlag = false;
}

return IfUrlExitsFlag;
}
}
}

Tuesday, December 20, 2011

Forms Authentication Configuration

Forms Authentication Configuration

The default attribute values for forms authentication are shown in the following configuration-file fragment.

The default attribute values are described below:

1. loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.
2. protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.
3. timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
4. name and path are set to the values defined in the application's configuration file.
5. requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.
6. slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
7. defaultUrl is set to the Default.aspx page for the application.
8. cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.
8. enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

Original Source : http://msdn.microsoft.com/en-us/library/ff647070.aspx