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

html to pdf using itextSharp

In previous article we checked how to convert gridview to pdf.

https://blogabhijeet.blogspot.com/2012/06/gridview-to-pdf-using-itextsharp.html

First of all you need to convert contents of html to Pdf. There is an third party dll:- iTextSharp dll which will help us to convert html contents to pdf.

Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/

Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.

Currently we have taken form and we are showing contents of current page in pdf.

Design Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowCurrentContentPageinPdf.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceholderPdf" runat="server"></asp:PlaceHolder>
    <div>
        <table border="1">
            <tr>
                <td colspan="2">
                    aspdotnetcodebook
                </td>
            </tr>
            <tr>
                <td>
                    cell1
                </td>
                <td>
                    cell2
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblLabel" runat="server" Text="Label Test"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    <p>
        &nbsp;</p>
    <p>
        xzcv</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        sdvasd</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    </form>
</body>
</html>
Code Behind Page 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }

    protected override void Render(HtmlTextWriter writer)
    {
        MemoryStream mem = new MemoryStream();
        StreamWriter twr = new StreamWriter(mem);
        HtmlTextWriter myWriter = new HtmlTextWriter(twr);
        base.Render(myWriter);
        myWriter.Flush();
        myWriter.Dispose();
        StreamReader strmRdr = new StreamReader(mem);
        strmRdr.BaseStream.Position = 0;
        string pageContent = strmRdr.ReadToEnd();
        strmRdr.Dispose();
        mem.Dispose();
        writer.Write(pageContent);
        CreatePDFDocument(pageContent);


    }
    public void CreatePDFDocument(string strHtml)
    {

        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
        StringReader se = new StringReader(strHtml);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        document.Close();
        ShowPdf(strFileName);



    }
    public void ShowPdf(string strFileName)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        //Response.WriteFile(strFileName);
        Response.TransmitFile(strFileName);
        Response.End();
        Response.Flush();
        Response.Clear();
    }
}
We have created 1 more class file

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}
Above code snippet will help us to convert HTML page to pdf.

 Happy Coding !!


GridView to Pdf using iTextSharp

First of all you need to convert contents of gridview to Pdf. There is an third party dll:- iTextSharp dll which will help us to convert gridview contents to pdf.

1. Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/

2. Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.

Currently we have taken 1 gridview & button on form.
You can bind your data to gridview as you required. I have just created dataset manually & assign it to gridview

Design Form
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="pdf.aspx.cs" Inherits="pdf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
   <form id="form1" runat="server">
  <div>
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
      <asp:Button ID="btnExportToPdf" runat="server" OnClick="btnExportToPdf_Click"
          Text="Pdf" /></div>
</form>
</body>
</html>

Code Behind File
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Collections.Generic;

public partial class pdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
    }

    public DataSet GetData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("Product");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
        dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
        dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
        for (int i = 1; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i * 2;
            dr[2] = 1 * 3;
            dt.Rows.Add(dr);
        }
        ds.Tables.Add(dt);
        Session["dt"] = dt;
        return ds;
    }

    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        MyPage tmpPage = new MyPage();
        HtmlForm form = new HtmlForm();

        form.Controls.Add(GridView1);

        tmpPage.Controls.Add(form);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        form.Controls[0].RenderControl(htmlWriter);
        string htmlContent = sw.ToString();
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\Sample.pdf", FileMode.Create));
       

        // step 3: we open the document
        document.Open();

        // step 4: we add a paragraph to the document

        //document.Add(new Paragraph(htmlContent.ToString()));

        System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

        //HtmlParser.Parse(document, _xmlr);
        using (TextReader sReader = new StringReader(sw.ToString()))
        {
            List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
            foreach (IElement elm in list)
            {
                document.Add(elm);
            }
        }

        // step 5: we close the document
        document.Close();

        //  Response.Write(document);
        string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sample.pdf";
        ShowPdf(Path);
    }

    private void ShowPdf(string strS)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
        Response.TransmitFile(strS);
        Response.End();
        Response.Flush();
        Response.Clear();
    }

}

 We have created 1 more class file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}

Above code snippet will help you to generate pdf.

 Happy Coding !!