Saturday, January 12, 2013

Grid view Column- Apply Word wrap to work in all browser

Sometimes in gridview we have a column which has too much information so it is not shown properly on page.

We can achieve with the help of CSS.
.word_wrap
{
    white-space: pre; /* CSS 2.0 */
    white-space: pre-wrap; /* CSS 2.1 */
    white-space: pre-line; /* CSS 3.0 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap; /* HP Printers */
    word-wrap: break-word; /* IE 5+ */
}
We have defined a css class, and we can assign this cssclass to column which has too much information.

<asp:TemplateField HeaderText="Name On Document" meta:resourcekey="HeaderText_NameOnResource1">
    <HeaderStyle Width="100px" Font-Bold="true" />
        <ItemTemplate>
            <div style="word-wrap: break-word; width: 100px;">
                 <%# Eval("NameOnDocument")%>
            </div>
        </ItemTemplate>
        <ItemStyle Width="100px" CssClass="word_wrap" Wrap="true" />
</asp:TemplateField>

Happy Coding!!

Wednesday, January 9, 2013

Encrypt connection string in web.config file

This time we have written a generalize function which will encrypt an decrypt connection strings.

Following code snippet will help to encrypt connection string in web.config file.

  protected void encryptConfi(bool bencrypt)
        {
            string webconfigfilepath = "~/";
            Configuration config = WebConfigurationManager.OpenWebConfiguration(webconfigfilepath);
            ConfigurationSection configsec = config.GetSection("connectionStrings");
            if (bencrypt)
            {
                configsec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            }
            else
            {
                configsec.SectionInformation.UnprotectSection();
            }
            config.Save();
        }

Happy Coding!!

Sunday, December 30, 2012

The Difference Between “Add Web Reference” and “Add Service Reference”


I was playing around with building a simple WCF ASP.NET client in Visual Studio 2008 and wanted to make a reference to my WCF service (that used basicHttpBinding).

I have built plenty of ASMX web services in the past so simply selected “Add Web Reference”, pointed to my .svc file hosted in IIS– everything worked as expected.
Then I checked the “Add Service Reference” menu option and thought – why this option is given?
In interview sometimes this question will be asked to check your understanding of web services.

Add Web Reference

It is a wrapper over wsdl.exe and can be used to create proxies for .NET 1.1 or 2.0 clients. Of course this means when you are pointing to a WCF service you have to be pointing to an endpoint that uses basicHttpBinding.

Add Service Reference 

It is a wrapper over svcutil.exe and also creates clients proxies (and additionally web.config entries). These proxies, however, can only be consumed by .NET 3.0+ clients.

Happy Coding!!

Wednesday, December 19, 2012

Download File in Asp.net

Following is a snippet required to download a file


    private void StartDownloadFile(string attachmentPath)
        {
            FileInfo file = new FileInfo(attachmentPath);
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AppendHeader("Content-Disposition", "attachment; filename = " + file.Name);
            Response.AppendHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/download";
            Response.WriteFile(file.FullName);
            Response.Flush();
            Response.Close();
            Response.End();
        }

This is generalize function, you need to pass path of filename. With the help of above code snippet browser will popup download box where you need to give the path.

Happy Coding!!

Tuesday, June 26, 2012

hyperlink in template column gridview

following snippet is useful to insert hyperlink template column in grdview 

    <asp:TemplateField  HeaderText="User name">
                <ItemTemplate>
                    <asp:HyperLink runat="server" ID="lnkRedirect"  NavigateUrl='<%# String.Format("~/UserDetails.aspx?username={0}",Container.DataItem) %>' Text='<%# Container.DataItem %>'></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>

if you are binding arraylist to gridview & grdview contains template column then in controls text property use Text='<%# Container.DataItem %>' instead of Text='<%# ColumnName %>' because columnName is not available in arraylist

Happy Coding!!

add Serial Number in gridview

sometimes we need to add serial numbers in gridview. we can achieve it through following code snippet.
<asp:TemplateField>
<HeaderTemplate> Serial No. </HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label> </ItemTemplate>
</asp:TemplateField>

This code works as same when we apply paging.

We cannot use this on BoundFields because they support only those objects who have Databinding event.

Happy Coding!!

Sunday, June 3, 2012

Sending SMTP email from SQL Server using CDO

Sending SMTP email from SQL Server using CDO

In one article we check how to send an email from Gmail server.

Today we will check how to send an email from SQL Server.

exec sendMail_With_CDOMessage
'SMTP server name Or SMTP IP'
, '1'
,'25'
,'SMTP User name'
,'SMTP User Password'
,'From which email'
,'To which email'
,'Email Subject'
,'Email Body Message'
,'Email attachment from the SQL with full window path <optional>'


Make sure that your SMTP is confugure to have relay option from the sending server.
SMTP can be configure on the server itself with IIS. Or you can use external SMTP server to send email.

It is very useful when you want to send some automated message from SQL server itself based on certain task completion or failure.

You need to give grant permisions on following stored procedures. Following procedures are present in Master Database so you need to give grant permision to your user in master database.
sp_oacreate ,sp_OADestroy,sp_OAGetErrorInfo ,sp_OASetProperty,sp_OAMethod 

CREATE PROCEDURE sendMail_With_CDOMessage
@smtpserver nvarchar(120)
,@smtpauthenticate nvarchar(120)
,@smtpserverport nvarchar(120)
,@sendusername nvarchar(120)
,@sendpassword nvarchar(120)
,@From nvarchar(120)
,@To nvarchar(120)
,@Subject nvarchar(120)=" "
,@Body nvarchar(4000) =" "
,@attachment nvarchar(400) = null
/*********************************************************************
This stored procedure takes the above parameters and sends an e-mail.
All of the mail configurations are hard-coded in the stored procedure.
Reference to the CDOSYS objects are at the following MSDN Web site:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_messaging.asp
***********************************************************************/

AS
Declare @iMsg int
Declare @hr int
Declare @source varchar(255)
Declare @description varchar(500)
Declare @output varchar(1000)

--************* Create the CDO.Message Object ************************
EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT
if @hr <> 0
print 'CDO.Message Create failed'

--***************Configuring the Message Object ******************
-- This is to configure a remote SMTP server.
-- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'
if @hr <> 0
print 'sendusing sp_OASetProperty failed'

-- This is to configure the Server Name or IP address.
-- Replace MailServerName by the name or IP of your SMTP Server.
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', @smtpserver
if @hr <> 0
print 'smtpserver sp_OASetProperty failed'

exec @hr = sp_oasetproperty @imsg, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate").value', @smtpauthenticate
if @hr <> 0
print 'smtpauthenticate sp_OASetProperty failed'

EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport").Value', @smtpserverport
if @hr <> 0
print 'smtpserverport sp_OASetProperty failed'

EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusername").Value', @sendusername
if @hr <> 0
print 'sendusername sp_OASetProperty failed'

EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendpassword").Value', @sendpassword
if @hr <> 0
print 'sendpassword sp_OASetProperty failed'



-- Save the configurations to the message object.
EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null
if @hr <> 0
print 'Configuration.Fields.Update sp_OAMethod failed'

-- Set the e-mail parameters.
EXEC @hr = sp_OASetProperty @iMsg, 'To', @To
if @hr <> 0
print 'To sp_OASetProperty failed'
EXEC @hr = sp_OASetProperty @iMsg, 'From', @From
if @hr <> 0
print 'From sp_OASetProperty failed'
EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject
if @hr <> 0
print 'Subject sp_OASetProperty failed'

--adding an attachment: pwf
IF @attachment IS NOT NULL
EXEC @hr = sp_OAMethod @iMsg,'AddAttachment', NULL, @attachment
if @hr <> 0
print 'AddAttachment sp_OASetProperty failed'


-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.
EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body
if @hr <> 0
print 'TextBody sp_OASetProperty failed'

EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL
if @hr <> 0
print 'Send sp_OASetProperty failed'


-- Sample error handling.
IF @hr <>0
BEGIN
    EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT
    IF @hr = 0
    BEGIN
        SELECT @output = ' Source: ' + @source
        PRINT @output
        SELECT @output = ' Description: ' + @description
        PRINT @output
    END
ELSE
    BEGIN
        print ' sp_OAGetErrorInfo failed.'
        RETURN
    END
END

-- Do some error handling after each step if you need to.
-- Clean up the objects created.
EXEC @hr = sp_OADestroy @iMsg
GO

Above code snippet will help you to send an email from SQL Server.

Happy Coding!!