Wednesday, November 4, 2009

Send Email in ASP.Net 2.0 - Feed back Form


Introduction

We are using System.Web.Mail.SmtpMail to send email in dotnet 1.1 which is obsolete in 2.0. The System.Net.Mail.SmtpClient Class will provide us the same feature as that of its predecessor.

This article explains how to use System.Net.Mail namespace to send emails.

Using the code

The HTML Design contains provision to enter sender�s name, email id and his comments. On click of the send email button the details will be sent to the specified email (Admin).

The Send mail functionality is similar to Dotnet 1.1 except for few changes

  1. System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail (obsolete in Dotnet 2.0).
  2. System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage (obsolete in Dotnet 2.0)
  3. The System.Net.MailMessage class collects From address as MailAddress object.
  4. The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
  5. MailMessage Body Format is replaced by IsBodyHtml

The Code is Self explanatory by itself.

Collapse
      protected void btnSendmail_Click(object sender, EventArgs e)
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0

// System.Net.Mail.SmtpClient is the alternate class for this in 2.0

SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();

try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);

// You can specify the host name or ipaddress of your server

// Default in IIS will be localhost

smtpClient.Host = "localhost";

//Default port will be 25

smtpClient.Port = 25;

//From address will be given as a MailAddress Object

message.From = fromAddress;

// To address collection of MailAddress

message.To.Add("admin1@yoursite.com");
message.Subject = "Feedback";

// CC and BCC optional

// MailAddressCollection class is used to send the email to various users

// You can specify Address as new MailAddress("admin1@yoursite.com")

message.CC.Add("admin1@yoursite.com");
message.CC.Add("admin2@yoursite.com");

// You can specify Address directly as string

message.Bcc.Add(new MailAddress("admin3@yoursite.com"));
message.Bcc.Add(new MailAddress("admin4@yoursite.com"));

//Body can be Html or text format

//Specify true if it is html message

message.IsBodyHtml = false;

// Message body content

message.Body = txtMessage.Text;

// Send SMTP mail

smtpClient.Send(message);

lblStatus.Text = "Email successfully sent.";
}
catch (Exception ex)
{
lblStatus.Text = "Send Email Failed." + ex.Message;
}
}

License

original source :http://www.codeproject.com/KB/aspnet/EmailApplication.aspx
Thanks to the author :Gowrisankar K Location: India India

Monday, October 5, 2009

How to use a SqlTransaction SqlConnections in .NET? -

Here is one example :

SqlTransaction transaction = cnnGlobal.BeginTransaction(IsolationLevel.Serializable);//cnnGlobal is connection

try

{

SqlCommand cmdMaster = new SqlCommand(sql, cnnGlobal);//sql is sql command

cmdMaster.Transaction = transaction;

cmdMaster.ExecuteNonQuery();

SqlCommand cmdDetails;

for (int i = 0; i <>

{

cmdDetails = new SqlCommand(sql, cnnGlobal);

cmdDetails.Transaction = transaction;

cmdDetails.ExecuteNonQuery();

}

transaction.Commit();

transaction = null;

cmdMaster.Dispose();

cmdDetails.Dispose();

}

catch

{

if (transaction != null)

{

transaction.Rollback();

transaction = null;

}

}



other example :
static void Main(string[] args)
{
string insertQuery =
@"INSERT TESTTABLE (COLUMN1, COLUMN2) " +
"VALUES(@ParamCol1, @ParamCol2)";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
using (SqlCommand command =
connection
.CreateCommand())
{
SqlTransaction transaction = null;
try
{
// BeginTransaction() Requires Open Connection
connection
.Open();

transaction
= connection.BeginTransaction();

// Assign Transaction to Command
command
.Transaction = transaction;
for (int i = 0; i < 100; i++)
CommandExecNonQuery(command, insertQuery,
new SqlParameter[] {
new SqlParameter("@ParamCol1", i),
new SqlParameter("@ParamCol2", i.ToString()) });
transaction
.Commit();
}
catch
{
transaction
.Rollback();
throw;
}
finally
{
connection
.Close();
}
}
}
}

Tuesday, September 29, 2009

iis showCannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later

I am a new .Net developer.

i was given an existing DB, and modified it for my department.

I intalled Visual Studio on my PC, and I think I have IIS going correctly (I can create a virtual server). But when I go to launch my homepage I get:


The XML page cannot be displayed

Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.




A name was started with an invalid character. Error processing resource 'http://localhost/Publishtest/Home.aspx'. Line 1, ...

<%@ Reference Page="~/Search.aspx" %>

-^

I see this error all over these forums but i haven't been able to figure it out yet. Is there a bad path somewhere? Any help is appreciated, I'm so new.

Thanks!



try to run


%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i


or see


How to repair IIS mapping after you remove and reinstall IIS
http://support.microsoft.com/default.aspx?kbid=306005&product=aspnet

The solution is here

MORE INFORMATION

To fix IIS mappings for
ASP.NET, run the Aspnet_regiis.exe utility:
  1. Click Start, and then click
    Run.
  2. In the Open text box, type cmd, and then press ENTER.
  3. At the command prompt, type
    the following, and then press ENTER:
    "%windir%\Microsoft.NET\Framework\version\aspnet_regiis.exe" -i
    In this path, version represents the version number of the .NET Framework that you
    installed on your server. You must replace this placeholder with the actual
    version number when you type the command.

Tuesday, July 7, 2009

numericupdown trouble do not show decimal value.

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
string value = numericUpDown1.Value.ToString();
int numOfDecimalPlaces = 0;

if (value.Contains("."))
{
string[] splitString = value.Split(new char[] { '.' });
numOfDecimalPlaces = splitString[1].Length;
}

numericUpDown1.DecimalPlaces = numOfDecimalPlaces;
}

ref : http://www.dreamincode.net/forums/showtopic81889.htm

Monday, July 6, 2009

Xml Read and attibute read

xml file :



<customers>

<customer age="19" gender="female">

<name>Kevin Anders</name>

<phone>555.555.5555</phone>

</customer>

<customer age="22" gender="male">

<name>Staci Richard</name>

<phone>555.122.1552</phone>

</customer>

</customers>


using System;

using System.Xml;


namespace XML

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

static void Main(string[] args)

{


XmlDocument doc = new XmlDocument();

doc.Load("test.xml");

XmlNodeList customers = doc.SelectNodes("//customer");

foreach (XmlNode customer in customers)

{

Console.WriteLine("Age = {0}, Gender = {1}", customer.Attributes["age"].Value, customer.Attributes["gender"].Value);

}

Console.ReadLine();





}

}

}




XML :

XML :


<?xml version="1.0" encoding="ISO-8859-1"?>

<Setting>

<General_Properties>

<imagesXML value="images.xml"/>

<direction value="horizontal" />

<minThumbWidth value="50" />

<minThumbHeight value="50" />

<maxThumbWidth value="120" />

<maxThumbHeight value="120" />

<spacing value="5" />

<expandingDirection value="center" />

<imagesEasingSpeed value="70" />

<imagesInfluence value="200" />

<backgroundColor value="0xeeeeee" />

<dockWidth value="570" />

<dockHeight value="200" />

<startingPixel value="0" />

<gotoStartingPixelOnRollOut value="false" />

</General_Properties>

</Setting>


using System;
using System.Xml;

namespace XML
{
///
/// Summary description for Class1.
///

class Class1
{
static void Main(string[] args)
{

XmlDocument doc = new XmlDocument();
doc.Load("settings.xml");

XmlNodeList imagesXML = doc.SelectNodes("//imagesXML");

foreach (XmlNode name in imagesXML)
{
Console.WriteLine("Value {0}", name.Attributes["value"].Value);
}

///
XmlNodeList direction = doc.SelectNodes("//direction");

foreach (XmlNode name in direction)
{
Console.WriteLine("Value {0}", name.Attributes["value"].Value);
}


Console.ReadLine();


}
}
}


XmlTextReader.GetAttribute Method (String)

C#
using System;

using System.IO;
using System.Xml;

public class Sample
{
public static void Main()
{
XmlTextReader reader = null;

try

{
//Load the reader with the XML file.
reader = new XmlTextReader("attrs.xml");

//Read the ISBN attribute.
reader.MoveToContent();
string isbn = reader.GetAttribute("ISBN");
Console.WriteLine("The ISBN value: " + isbn);

}
finally
{
if (reader != null)
reader.Close();
}
}

} // End class


The example uses the file, attrs.xml, as input.

<book genre='novel' ISBN='1-861003-78' pubdate='1987'>

</book>

ref : http://msdn.microsoft.com/en-us/library/3c932kx5.aspx

Tuesday, May 12, 2009

Name 'ConfigurationManager' is not declared in VB.Net 2.0

in a ASP.Net 2.0 web Application, to get a connection string from Web.config, you would write:
ConfigurationManager.ConnectionStrings("DB").ConnectionString

trying to do the same in a Windows application, would give you the error :
Name 'ConfigurationManager' is not declared
even you did import "System.Configuration"...

well, after searching i found that you need to add reference to "System.Configuration.dll" : under Project > Add refrence > .Net > select System.Configuration

Friday, February 27, 2009

Convert a DataReader to DataTable in ASP.NET

Convert a DataReader to DataTable in ASP.NET

A DataReader is a read-only forward-only way of reading data. It is quiet fast when compared to fetching data using a DataSet. Infact internally, a DataSet uses a DataReader to populate itself. However at times, we need the best of both worlds. A dataset/datatable is extremely handy when it comes to binding it to a control like a GridView. So to make use of both the DataReader and DataTable in the same solution, we can fetch the data using a DataReader and then convert it to a DataTable and bind it to the control. In this article, we will explore how to do the conversion using two approaches; the first one, a direct method by using the DataTable.Load() and the second one, by manually converting a DataReader to a DataTable.

Step 1: Create a new ASP.NET application. Drag and drop two GridView controls to the page. We will fetch data from a DataReader into a DataTable and bind the DataTable to the GridView’s. Before moving ahead, add a web.config file to the project and add the following element.

<connectionStrings>

<addname="NorthwindConn"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security=true;"/>


</connectionStrings>

Step 2: Let us first see how to convert a DataReader to a DataTable using the easy way out. DataTable in ADO.NET 2.0 contains a Load() method which enables the DataTable to be filled using a IDataReader. This method is quiet handy when you need to quickly create a DataTable, without using a DataAdapter!! Let us see how.

C#

private void ConvertDateReadertoTableUsingLoad()


{

SqlConnection conn = null;

try

{

string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;


conn = new SqlConnection(connString);

string query = "SELECT * FROM Customers";

SqlCommand cmd = new SqlCommand(query, conn);


conn.Open();

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

DataTable dt = new DataTable();


dt.Load(dr);

GridView1.DataSource = dt;

GridView1.DataBind();


}

catch (SqlException ex)


{

// handle error

}

catch (Exception ex)


{

// handle error

}

finally

{

conn.Close();


}

}

VB.NET

Private Sub ConvertDateReadertoTableUsingLoad()

Dim conn As SqlConnection = Nothing


Try

Dim connString As String = ConfigurationManager.ConnectionStrings("NorthwindConn").ConnectionString

conn = New SqlConnection(connString)


Dim query As String = "SELECT * FROM Customers"

Dim cmd As SqlCommand = New SqlCommand(query, conn)


conn.Open()

Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Dim dt As DataTable = New DataTable()


dt.Load(dr)

GridView1.DataSource = dt

GridView1.DataBind()


Catch ex As SqlException


' handle error

Catch ex As Exception

' handle error

Finally


conn.Close()

End Try

End Sub

Note 1: If there is some existing data in the DataTable, the data coming from the DataReader is merged with the existing rows.


Note 2: If you need a DataReader back from a DataTable, use the DataTable.CreateDataReader() method.

Step 3: The method shown in the Step 2 was the easy way out. However, if for some reason(if you are not using ADO.NET 2.0), you would want to convert a DataReader to a DataTable ‘manually’, here’s the code. In the code below, a DataTable schema is created first using the GetSchemaTable() method of DataReader. The GetSchemaTable() returns a DataTable describing the column metadata of the IDataReader. Once done, we loop through the rows of the schema table and create a DataColumn object and set its properties. This DataColumn is also added to the List<> collection. We then read rows from the DataReader and populate the DataTable.

C#

private void ConvertDataReaderToTableManually()


{

SqlConnection conn = null;

try

{

string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;


conn = new SqlConnection(connString);

string query = "SELECT * FROM Customers";

SqlCommand cmd = new SqlCommand(query, conn);


conn.Open();

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

DataTable dtSchema = dr.GetSchemaTable();

DataTable dt = new DataTable();


// You can also use an ArrayList instead of List<>

List<DataColumn> listCols = new List<DataColumn>();


if (dtSchema != null)


{

foreach (DataRow drow in dtSchema.Rows)

{


string columnName = System.Convert.ToString(drow["ColumnName"]);

DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));


column.Unique = (bool)drow["IsUnique"];

column.AllowDBNull = (bool)drow["AllowDBNull"];

column.AutoIncrement = (bool)drow["IsAutoIncrement"];


listCols.Add(column);

dt.Columns.Add(column);

}

}


// Read rows from DataReader and populate the DataTable

while (dr.Read())


{

DataRow dataRow = dt.NewRow();

for (int i = 0; i < listCols.Count; i++)


{

dataRow[((DataColumn)listCols[i])] = dr[i];

}

dt.Rows.Add(dataRow);

}


GridView2.DataSource = dt;

GridView2.DataBind();

}

catch (SqlException ex)


{

// handle error

}

catch (Exception ex)


{

// handle error

}

finally

{

conn.Close();


}


}

VB.NET

Private Sub ConvertDataReaderToTableManually()

Dim conn As SqlConnection = Nothing


Try

Dim connString As String = ConfigurationManager.ConnectionStrings("NorthwindConn").ConnectionString

conn = New SqlConnection(connString)


Dim query As String = "SELECT * FROM Customers"

Dim cmd As SqlCommand = New SqlCommand(query, conn)


conn.Open()

Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Dim dtSchema As DataTable = dr.GetSchemaTable()


Dim dt As DataTable = New DataTable()

' You can also use an ArrayList instead of List<>

Dim listCols As List(Of DataColumn) = New List(Of DataColumn)()



If Not dtSchema Is Nothing Then

For Each drow As DataRow In dtSchema.Rows


Dim columnName As String = System.Convert.ToString(drow("ColumnName"))

Dim column As DataColumn = New DataColumn(columnName, CType(drow("DataType"), Type))


column.Unique = CBool(drow("IsUnique"))

column.AllowDBNull = CBool(drow("AllowDBNull"))

column.AutoIncrement = CBool(drow("IsAutoIncrement"))

listCols.Add(column)


dt.Columns.Add(column)

Next drow

End If


' Read rows from DataReader and populate the DataTable


Do While dr.Read()

Dim dataRow As DataRow = dt.NewRow()

For i As Integer = 0 To listCols.Count - 1


dataRow((CType(listCols(i), DataColumn))) = dr(i)

Next i

dt.Rows.Add(dataRow)

Loop

GridView2.DataSource = dt


GridView2.DataBind()

Catch ex As SqlException

' handle error

Catch ex As Exception


' handle error

Finally

conn.Close()

End Try



Step 4: Call the two methods on the PageLoad()


C#

protected void Page_Load(object sender, EventArgs e)

{


ConvertDateReadertoTableUsingLoad();

ConvertDataReaderToTableManually();

}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


ConvertDateReadertoTableUsingLoad()

ConvertDataReaderToTableManually()

End Sub

The DataTable.Load(IDataReader) is extremely handy when you want to quickly bind the data coming from a DataReader to a control like the GridView. The DataTable.Load() method has three overloads. We have explored one of them. I would encourage you to explore the other two over here.




I hope this article was useful and I thank you for viewing it

Source : http://www.dotnetcurry.com/ShowArticle.aspx?ID=143

Counter