Thursday, December 26, 2013

Login Autherntication using LDAP in asp.net

protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            string path = ConfigurationSettings.AppSettings["ldap"].ToString();
            DirectoryEntry objEntry = new DirectoryEntry(path, txtUserName.Text.Trim(), txtPassword.Text.Trim());
            DirectorySearcher search = new DirectorySearcher(objEntry);
            search.Filter = "(&(objectCategory=person)(SAMAccountName=" + txtUserName.Text.Trim() + "))";
            //search.Filter = "(&(objectCategory=person)(SAMAccountName=AjayK))";
            SearchResult result = search.FindOne();
            if (result != null)
            {
                DirectoryEntry de = result.GetDirectoryEntry();
                PropertyValueCollection groups = de.Properties["memberOf"];

                foreach (string s in groups)
                {
                    //Response.Write(s + "<br/>");
                    if (s.Contains("Managers ABC"))
                        Session["isMgr"] = true;
                }
                Session["name"] = txtUserName.Text.Trim();
                //Session["name"] = "rupeshm";
                Response.Redirect("Index.aspx");
            }
        }
        catch (DirectoryServicesCOMException)
        {
            {
               
              lblMsg.Text = "Invalid User Name or Password!!";
           
            }
        }
    }

Friday, December 20, 2013

How to add double quotes in URL in c#

I have URL

http://abc.io/v3/companies?filters={"info":"ddil"}&api_key=tk5qgu

and i Changes and handle double quotes like below

var url = "http://abc.io/v3/companies?filters={\"info\":\"ddil\"}&api_key=tk5qgu";


Thursday, December 12, 2013

Tuesday, December 10, 2013

Calculate mid string in sql

create function dbo.MidString(@string varchar(100))
RETURNS varchar(100)
as
begin
Declare @strtloc int
Declare @endloc int
declare @result varchar(50)
set @strtloc = charindex('|',@string)+1
set @endloc = charindex('|',substring(@string,@strtloc,len(@string)))-1
if @endloc = -1  
begin
set @endloc=len(@string)  
end  
set @result=substring(@string,@strtloc,@endloc)
return @result
end

How to find first name,Middle name,last name in sql

SELECT
LEFT(transaction_claimant_Firstname,CHARINDEX('|',transaction_claimant_Firstname + '|')-1) AS FirstName,
CASE WHEN LEN(transaction_claimant_Firstname) - LEN(REPLACE(transaction_claimant_Firstname,'|','')) > 1  THEN PARSENAME(REPLACE(transaction_claimant_Firstname,'|','.'),2) ELSE NULL END AS MiddleName,
CASE WHEN LEN(transaction_claimant_Firstname) - LEN(REPLACE(transaction_claimant_Firstname,'|','')) > 0 THEN PARSENAME(REPLACE(transaction_claimant_Firstname,'|','.'),1) ELSE NULL END AS LastName
FROM tablename

Monday, October 28, 2013

how to add ‘st’,’nd’,’rd’,’th’ to dates in SQL Server

Create function [dbo].[get_Custome_date]
(
    @date datetime = null
)
returns nvarchar(50)
as begin
     
    declare @d int,
    @m nvarchar(15),
    @y nvarchar(4),
    @end nvarchar(1),
    @return nvarchar(50)
 
    if @date is null
        set @date=getdate()
    select @d=datepart(d, @date), @m=datename(m, @date), @Y=
datename(yyyy,@date), @end=right(convert(nvarchar(2), @d),1)
    set @return=
        convert(nvarchar(2), @d)
        +case
            when @d in(11, 12, 13) then 'th'
            when @end='1' then 'st'
            when @end='2' then 'nd'
            when @end='3' then 'rd'
            else 'th'  
        end
        +' '+@m+' '+@y
    return @return
 
end


======

select dbo.get_Custome_date(getdate()) AS Customedate

Result is

3rd November 2013

Wednesday, October 16, 2013

Various sql Finction


1.How to calculate age

SELECT DATEDIFF(DD,'1981-01-05 00:00:00.000',GETDATE())/365 AS AGE

2.How to calulate first day of previous month
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)

Here 0 indicate as default date of sql(01/01/1900)

3. How to calculate last day of previous month

SELECT GETDATE()-DATEPART(dd,GETDATE())

Thursday, October 10, 2013

Left padding with zero in sql

  SELECT RIGHT(REPLICATE('0',10) + CAST(isnull(cast(56589 as decimal(8,2)),0) AS VARCHAR(10)),10)

Monday, October 7, 2013

SQL 2005 and SQL 2000 implementation of ROW_NUMBER

-- SQL 2005 version

SELECT 
    RowNumber = ROW_NUMBER() OVER (ORDER BY c.LastName ASC)
    ,c.LastName
    ,c.FirstName
FROM SalesLT.Customer c


And the SQL 2000 version:
SELECT 
    RowNumber   = IDENTITY(INT,1,1)
    ,c.LastName
    ,c.FirstName
INTO #Customer_RowID
FROM SalesLT.Customer c
ORDER BY c.LastName ASC

Thursday, September 26, 2013

Encrypt Or Decrypt QueryString at Asp.net gridview Hyperlink using .net 3.5

Encrypt Or Decrypt QueryString at Asp.net gridview Hyperlink using .net 3.5

1.Include the namespace
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Cryptography;
using System.IO;

2.Add Hyperlink in template field of gridveiw

<asp:TemplateField HeaderText="Reference No." SortExpression="fullref">
                <ItemTemplate>      
                <asp:hyperlink
                runat="server"
                id="hyperlink1"
             
                text='<%# Eval("fullref") %>'>
                </asp:hyperlink>
                </ItemTemplate>
            <HeaderStyle BackColor="#660066" ForeColor="White"></HeaderStyle>
                </asp:TemplateField>  

3. Add the menthod to encrypt

 private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
 public string Encrypt(string stringToEncrypt, string SEncryptionKey)
    {
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }


4.Use the follwing menthod to bind encrypted querystring on rowdatabaound event of gridveiw


  protected void GDVClientView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;

            if (e.Row.DataItem == null) return;

            HyperLink hlobj = (HyperLink)e.Row.FindControl("hyperlink1") ;

            hlobj.NavigateUrl = String.Format("warrantdetailclient.aspx?fullref={0}",
                                                       Server.UrlEncode(Encrypt(hlobj.Text, "r0b1nr0y")));
        }
        catch (Exception ex)
        {
            //
        }

    }


5.Now on next page use the decript method as:
 protected void Page_Load(object sender, EventArgs e)
    {
 if (Request.Params["fullref"] != null)
        {
            string decrpval = Decrypt(Request.Params["fullref"].ToString(), "r0b1nr0y");
}
}

     private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
    public string Decrypt(string stringToDecrypt, string sEncryptionKey)
    {
        byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(stringToDecrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

Wednesday, September 25, 2013

Cannot resolve the collation conflict In LINQ

Cannot resolve the collation conflict IN LINQ Can be resolved using AsEnumerable() with Table Like as mention below



 DataClassesDataContext tdc = new DataClassesDataContext();

        var  warid = (from id in tdc.SP_Cases.AsEnumerable()
                      join defe in tdc.Defendant_Masters.AsEnumerable() on id.WarrantID   equals defe.WarrantID
                      join defAd in tdc.Defendant_Addresses.AsEnumerable() on defe.CID equals defAd.Def_Id
                     where id.WarrantID == "SPC1080"
                     select new { id.WarrantID, id.JudgCost, id.EntryDate,defe.DefendantName,defAd.Add1 }).FirstOrDefault();

        if (warid != null)
        {
            Label1.Text = warid.WarrantID;
            Label2.Text = warid.JudgCost.ToString();
            Label3.Text = warid.DefendantName;
            Label4.Text = warid.Add1;
        }

Tuesday, September 24, 2013

Error executing child request for ChartImg.axd

While working working with MS Chart control in .net 3.5,i am getting following error :
"Error executing child request for ChartImg.axd " and it is solved by following steps:

Add in webconfig 

1.Add chart image saving folder name as
<appSettings>
 <add key="ChartImageHandler" value="storage=file;timeout=20;dir=C:\TempImageFiles\;" /></appSettings>

2. add http handler as:

<httpHandlers>
  <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>

3.Add Handler as

<handlers>
  <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>


4.Make sure you need to add Chart Image save location(ImageLocation) tag in Chart control as:

 <asp:Chart ID="Chart2" runat="server"  Height="536px" Width="680px" ImageStorageMode="UseImageLocation" ImageLocation="TempImageFiles/ChartPic_#SEQ(300,3)" EnableViewState="true">
                        <Titles>
                        <asp:Title Name="Title1" Text="Enforceble Pie" 
                        Alignment="TopCenter" Font="Verdana, 12pt, style=Bold" ForeColor="Purple">
                        </asp:Title>
                        </Titles>
                        <Series>
                        <asp:Series Name="Series1" ChartType="Pie" CustomProperties="PieLabelStyle=outside, CollectedThresholdUsePercent=False, PieLineColor=Purple" Legend="Legend1"   >
                        </asp:Series>

                        </Series>
                        <Legends>
                        <asp:Legend Name="Legend1" BackImageAlignment="Bottom" Docking="Bottom" 
                                Font="Verdana, 7.25pt" IsTextAutoFit="False"  >
                        </asp:Legend>

                        </Legends>
                        <ChartAreas>
                        <asp:ChartArea Name="ChartArea1" >
                        </asp:ChartArea>
                        </ChartAreas>
                        </asp:Chart>
            












Thursday, September 19, 2013

How to pass logon information to reportdocument object to export in pdf from crystal report in sqlsever2005/2008 and Sql Aure



 logon information to reportdocument object in sqlsever2005/2008




ReportDocument repDoc = new ReportDocument();
   repDoc.Load(repFilePath);

// This is for  logon information to reportdocument object in sqlsever2005/2008
 repDoc.SetDataSource(getCustomerData(clientid));
  repDoc.SetDatabaseLogon("userid", "Password", "Sever Name", "Database name");
  repDoc.SetParameterValue(0, clientid);

//  logon information to reportdocument object in Sql Azure

repDoc.SetDataSource(getCustomerData(clientid));
  repDoc.DataSourceConnections[0].SetConnection("ServerName", "database Name", "User ID", "Password");
   repDoc.DataSourceConnections[0].SetLogon("User id", "Password");
                 
   repDoc.SetParameterValue(0, clientid);


 // Stop buffering the response
                    Console.Clear();
                 
                    ExportOptions CrExportOptions;

                    DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                    PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                    CrDiskFileDestinationOptions.DiskFileName =  filePathName + ".pdf";
                    CrExportOptions = repDoc.ExportOptions;
                    {
                        CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                        CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                        CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                        CrExportOptions.FormatOptions = CrFormatTypeOptions;

                    }
                    repDoc.Export();



        // Business layer class to get the data from database
        private DataSet getCustomerData(string clientid)
        {

            SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["SherpaSQLConnString"].ToString());
            SqlCommand cmd = new SqlCommand("ClientMIPage1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@cclientid", SqlDbType.VarChar, 36));
            cmd.Parameters[0].Value = clientid;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(ds);
            return ds;

        }


Friday, August 16, 2013

Use of COALESCE in SQL Server

 use of COALESCE in SQL Server?




declare @i varchar(500)
select @i=COALESCE(@i,RoleTitle)+','+RoleTitle from ProfileMaster

print @i

result is :

Administrator,Administrator,EO,Admin Team,Agent,Print Queue User,Client

Thursday, June 13, 2013

Piovt using sql query

SELECT * FROM (SELECT
convert(char(3), transaction_timestamp, 0) as transaction_timestamp1,transaction_serviceType FROM transactions_history 
where transaction_timestamp >='2013-01-01 00:00:00' and  transaction_timestamp<='2013-06-11 23:59:00'
and transaction_status in('OK'))
as PV
PIVOT
(
      count(transaction_timestamp1)
      --COUNT(transaction_serviceType)
      FOR transaction_timestamp1 IN ([JAN],[FEB],[MAR],[APR],[MAY],[JUN])
)

AS PVT 

and output would be as mention below:


transaction_serviceType JAN   FEB   MAR   APR   MAY   JUN
Sherforce               43    48    46    44    27    7
SherforcePlus           3     2     3     1     1     1
Shergroup Enforcement   2     6     2     13    16    16
ShergroupLegal          0     4     0     2     0     0

Thursday, May 30, 2013

Sql function for Proper case

Create function properCase(@string varchar(8000)) returns varchar(8000) as    
begin    
 if len(@string)>0  
 begin  
        set @string = lower(@string)    
        declare @i int    
        set @i = ascii('a')    
        while @i <= ascii('z')    
        begin    
               set @string = replace( @string, ' ' + char(@i), ' ' + char(@i-32))    
               set @i = @i + 1    
        end    
        set @string = char(ascii(left(@string, 1))-32) + right(@string, len(@string)-1)    
 end  
        return @string    
end

call this funcrion as :

select dbo.ProperCase('AJAY')

result is:
Ajay

Wednesday, May 29, 2013

Code for merging serveral PDF into single PDF in asp.net

For merging PDF into single PDF we need to include  namespace  mention below

using iTextSharp.text;
using iTextSharp.text.pdf;

and for it you need to add reference of ItextSharp DLL.

Now use this function for merging PDF.....


public  void MergeFiles(string destinationFile, string[] sourceFiles)
    {
        try
        {
            int f = 0;
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(sourceFiles[f]);
            // we retrieve the total number of pages
            int n = reader.NumberOfPages;
            //Console.WriteLine("There are " + n + " pages in the original file.");
            // step 1: creation of a document-object
            Document document = new Document(reader.GetPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
            // step 3: we open the document
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page;
            int rotation;
            // step 4: we add content
            while (f < sourceFiles.Length)
            {
                int i = 0;
                while (i < n)
                {
                    i++;
                    document.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document.NewPage();
                    page = writer.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                    //Console.WriteLine("Processed page " + i);
                }
                f++;
                if (f < sourceFiles.Length)
                {
                    reader = new PdfReader(sourceFiles[f]);
                    // we retrieve the total number of pages
                    n = reader.NumberOfPages;
                    //Console.WriteLine("There are " + n + " pages in the original file.");
                }
            }
            // step 5: we close the document
            document.Close();
           
        }
        catch (Exception e)
        {
            string strOb = e.Message;
        }
    }
    public int CountPageNo(string strFileName)
    {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(strFileName);
        // we retrieve the total number of pages
        return reader.NumberOfPages;
    }


Calling of above function.....

 MergeFiles(ConfigurationManager.AppSettings["ReportPDFMergepath"].ToString() + "ClientMI-" + filePathName + ".pdf", sourceFiles);

Friday, April 5, 2013

How to release/kill word object in asp.net

This can be done using a foreach loop and include namespace

using System.Diagnostics;



foreach (Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    p.CloseMainWindow();
                    p.Kill();
                }
                throw ex;



Friday, March 1, 2013

How to make textbox Readonly and getting their value


1.On Page Load  use code like this
 txtyears.Attributes.Add("readonly", "readonly");
            txtMonths.Attributes.Add("readonly", "readonly");


2.Now you ca use textbox value simply as u always do

string test=txtyears.text

Wednesday, February 20, 2013

how to change collation in sql server 2008 r2


ALTER TABLE dbo.Defendant_master ALTER COLUMN WarrantID
            varchar(36)COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL

Monday, February 18, 2013

Row_Number() in sql


Select ROW_NUMBER()
        OVER (ORDER BY  columnName) AS Rownum from abc

how to change row data in column and display in gridview cell in asp.net


1. using sql query add CHAR(13) in various column and it will display like below text

    12 street town CLEVELAND pcode

2. Now  on GVLetter_RowDataBound event replace spcace with line break(<BR/>) as mention below

protected void GVLetter_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       
        int id;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Cells[1].Text = e.Row.Cells[1].Text.Replace("\r", "<br />");
            e.Row.Cells[2].Text = e.Row.Cells[2].Text.Replace("\r", "<br />");

            id = Convert.ToInt32(e.Row.Cells[4].Text);
            if (id == 100)
            {
                ((ImageButton)e.Row.FindControl("ImagConfirm")).Visible = true;

            }
            else
            {
                ((ImageButton)e.Row.FindControl("ImagConfirm")).Visible = false;
            }
        }
    }

Result in griedview cell will as mention below


12
street
town
CLEVELAND
pcode

Monday, February 11, 2013

code for catching error and saving in database in asp.net


 void Application_Error(object sender, EventArgs e)
    {
        //Code that runs when an unhandled error occurs
     
        //PS: This functionality stores all errors in database and these errors can be vieved
        //directly in database in 'ErrorLog' table. Or can also be viewed by browsing the
        //page 'errorlog.aspx' directly from the root of application.
     
        //Note: This logic will failed only in the case;
        //if database connection will not established due to some reasons.
        //so this is single case and can be trapped by developers. OR
        //In web.config; set <customErrors mode="Off"> and see the error.

        clsGenericClass objGen = new clsGenericClass();

        Exception objErr = new Exception();
        objErr = Server.GetLastError().GetBaseException();

        objGen.InsertErrorLog(objErr.Message, "Error Caught in Application_Error event",
            Request.Url.ToString(), objErr.Source, "", DateTime.Now);

        Server.ClearError();
    }

Wednesday, February 6, 2013

SQL function for getting mid string


CREATE function [dbo].[MidString](@string varchar(100))
RETURNS varchar(100)
as
begin
Declare @strtloc int
Declare @endloc int
declare @result varchar(50)
set @strtloc = charindex('|',@string)+1
set @endloc = charindex('|',substring(@string,@strtloc,len(@string)))-1
if @endloc = -1
begin
set @endloc=len(@string)
end
set @result=substring(@string,@strtloc,@endloc)
return @result
end

Wednesday, January 23, 2013

Convert Datareader to Datatable in asp.net



using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
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;

public partial class _Default : System.Web.UI.Page
{
    IDataAdapter da;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(string));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        DataRow drQuery;
      
      
        da = getReader();

        da.Fill(ds);
        int QCount1 = 0;
        while (QCount1 < ds.Tables[0].Rows.Count)
        {
            drQuery = dt.NewRow();

            drQuery["ID"] = Convert.ToString(ds.Tables[0].Rows[QCount1][1].ToString());
            drQuery["Name"] = ds.Tables[0].Rows[QCount1][3].ToString();
            drQuery["Age"] = ds.Tables[0].Rows[QCount1][2].ToString();
            drQuery["Address"] = ds.Tables[0].Rows[QCount1][9].ToString();
            dt.Rows.Add(drQuery);
            QCount1 = QCount1 + 1;
        }
      
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    private IDataAdapter getReader()
    {
     
    
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["testcon"].ToString());
        SqlDataAdapter da = new SqlDataAdapter("select * from t_users",con);
      


        return da;
    }
}



Thursday, January 17, 2013

Cross-Site Scripting Protection in ASP.NET(A potentially dangerous Request.Form value was detected from the client)

This is basically to  catches malicious scripting code used by hacker.This is simply done in ASP.net by using a filter....
We need to add this in webconfig file as: 



<configuration>
    <system.web>
        <httpModules>
            <add name="ValidateInput" 
               type="Corillian.Web.ValidateInput,ValidateInputASPNET10" />
        </httpModules>
    </system.web>
</configuration>




For more reference use this link
http://msdn.microsoft.com/en-us/library/ms972967.aspx


Tuesday, January 15, 2013

How to Enable TLS for SMTP Authentication ?

I have made a function for sending email and inside here smtp client object is created and set TLS for it



public Boolean SendMailNew(string filename, bool isAttach)
        {
            mailSent = false;
            Boolean IsSuccess = false;
            try
            {

                MailAddress senderAddress = new MailAddress(fromAddress, fromWhom);
                MailMessage message = new MailMessage();
                string messageString = "";
                message.From = senderAddress;
                string[] toAddressArray = ToAddressArray(toAddress);
                foreach (string recAddress in toAddressArray)
                {
                    message.To.Add(new MailAddress(recAddress, recAddress));
                }

                if (ccAddress != null && ccAddress.Trim().Length > 0)
                {
                    string[] ccAd = ToAddressArray(ccAddress);
                    foreach (string ccAddStr in ccAd)
                    {
                        MailAddress ccAddr = new MailAddress(ccAddStr);
                        message.CC.Add(ccAddr);
                    }
                }

                if (bccAddress != null && bccAddress.Trim().Length > 0)
                {
                    string[] bccAd = ToAddressArray(bccAddress);
                    foreach (string bccAddStr in bccAd)
                    {
                        MailAddress bcc = new MailAddress(bccAddStr);
                        message.Bcc.Add(bcc);
                    }
                }

                string path = ConfigurationSettings.AppSettings["ImagePath"].ToString();

                LinkedResource lnkResource1 = new LinkedResource(path + "header1.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource1.ContentId = "headerPict1";
                LinkedResource lnkResource2 = new LinkedResource(path + "dotted.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource2.ContentId = "dottedPict1";
                LinkedResource lnkResource3 = new LinkedResource(path + "footer.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource3.ContentId = "footerPict1";
                LinkedResource lnkResource4 = new LinkedResource(path + "f.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource4.ContentId = "fPict1";
                LinkedResource lnkResource5 = new LinkedResource(path + "t.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource5.ContentId = "tPict1";
                LinkedResource lnkResource6 = new LinkedResource(path + "yt.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource6.ContentId = "ytPict1";
                LinkedResource lnkResource7 = new LinkedResource(path + "l.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource7.ContentId = "lPict1";
                LinkedResource lnkResource8 = new LinkedResource(path + "robot.jpg", MediaTypeNames.Image.Jpeg);
                lnkResource8.ContentId = "RobotPict1";

                ContentType ct = new ContentType();
                ct.MediaType = MediaTypeNames.Text.Html;
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(messageBody, ct);

                htmlView.LinkedResources.Add(lnkResource1);
                htmlView.LinkedResources.Add(lnkResource2);
                htmlView.LinkedResources.Add(lnkResource3);
                htmlView.LinkedResources.Add(lnkResource4);

                htmlView.LinkedResources.Add(lnkResource5);
                htmlView.LinkedResources.Add(lnkResource6);
                htmlView.LinkedResources.Add(lnkResource7);
                htmlView.LinkedResources.Add(lnkResource8);
                message.AlternateViews.Add(htmlView);

                messageString = messageBody;
                message.Subject = subjectLine;

                if (isAttach)
                {
                    Attachment attach = new Attachment(filename);
                    // Add time stamp information for the file.
                    ContentDisposition disposition = attach.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(filename);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(filename);
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(filename);
                    // Add the file attachment to this e-mail message.
                    message.Attachments.Add(attach);
                }
               

                message.IsBodyHtml = true;
                message.Body = messageString;
             
                //NetworkCredential loginInfo = new NetworkCredential(ConfigurationSettings.AppSettings["UserId"].ToString(), ConfigurationSettings.AppSettings["Password"].ToString());
                //SmtpClient client = new SmtpClient("pod51014.outlook.com", 587);
               
                //client.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["SMTPport"]);
                //client.EnableSsl = true;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //client.UseDefaultCredentials = false;
                //client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //client.Credentials = loginInfo;

                SmtpClient client = new SmtpClient(smtpClientString);
                client.EnableSsl = true;
               //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);


                client.Send(message);
                message.Attachments.Clear();
                message.Dispose();

                return (IsSuccess = true);

            }
            catch (Exception exc)
            {
                exc.ToString();
                return IsSuccess;
                //throw exc;
            }
        }


======================

Add the setting in webconfig file,Here from adress address must be same as user name

<system.net>
<mailSettings>
<smtp from="abc@test.net" deliveryMethod="Network">
<network userName="abc@test.net" password="5ama" host="po.outlook.com" port="587" />
</smtp>
</mailSettings>
</system.net>