Archive for March, 2008

How to send mail using SMTP server in ASP.NET?

Friday, March 28th, 2008

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

Code:

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

Posted by Mahesh ( Tryangled )

How to read an Excel file into a Datagrid?

Monday, March 24th, 2008

This simple code reads in an Excel file and displays it as a datagrid using the OleDbDataAdapter. The first line of your excel file has to have the column headers.
protected void btnImportExcelFile_Click(object sender, EventArgs e)
{
string strConn;
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” +
“Data Source=C:\\exceltest.xls;” +
“Extended Properties=Excel 8.0;”;
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter myCommand = new OleDbDataAdapter(”SELECT * FROM [Tabelle1$]”, strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, “ExcelInfo”);
DataGrid1.DataSource = myDataSet.Tables[”ExcelInfo”].DefaultView;
DataGrid1.DataBind();
}

Posted by Mahesh ( Tryangled )

How to get text of a website at the command line using ASP.NET(C#)?

Monday, March 24th, 2008

//including all namespaces..
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace WebRequestorApp
{
class Program
{
static void Main(string[] args)
{
‘To Request for website
WebRequest req = WebRequest.Create(”http://www.tryangled.com”);
WebResponse resp = req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.ASCII);
Console.WriteLine(reader.ReadToEnd());
}
}
}

Posted by Mahesh ( Tryangled )

Windows performance monitoring in ASP.NET(C#)?

Monday, March 24th, 2008

Using the namespace of System.Diagnostics to monitor Windows performance, e.g. performance counter,threads and processes.
‘To get the data from Windows performance counter

using System;
using System.Net;
using System.Diagnostics;

At first declare three PerformanceCounter instances, define the category and counters in performance monitor
Then display the values obtained in different Labels.

By the looping of PerformanceCounterCategory.GetCategories method to go through all available categories

PerformanceCounter objMemperf = new PerformanceCounter(”Memory”,”Available Bytes”);
PerformanceCounter objProcperf = new PerformanceCounter(”System”, “Processes”);
PerformanceCounter objComperf = new PerformanceCounter(”System”, “Threads”);
Label1.Text = string.Format(”{0:#,###}”, objMemperf.NextValue()) + “Byte”;
Label2.Text = objProcperf.NextValue().ToString();
Label3.Text = objComperf.NextValue().ToString();
if (!Page.IsPostBack)
{
foreach(PerformanceCounterCategory objPer in PerformanceCounterCategory.GetCategories())
{
ListBox1.Items.Add(new ListItem(objPer.CategoryName));
}
}
The whole code behind front page
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;
using System.Text;
using System.Diagnostics;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PerformanceCounter objMemperf = new PerformanceCounter(”Memory”,”Available Bytes”);
PerformanceCounter objProcperf = new PerformanceCounter(”System”, “Processes”);
PerformanceCounter objComperf = new PerformanceCounter(”System”, “Threads”);

Label1.Text = string.Format(”{0:#,###}”, objMemperf.NextValue()) + “Byte”;
Label2.Text = objProcperf.NextValue().ToString();
Label3.Text = objComperf.NextValue().ToString();

if (!Page.IsPostBack)
{
foreach(PerformanceCounterCategory objPer in PerformanceCounterCategory.GetCategories())
{
ListBox1.Items.Add(new ListItem(objPer.CategoryName));
}
}
}
}

Posted by Mahesh ( Tryangled )

Convert A Binary String to A Decimal Number?

Monday, March 24th, 2008

Following code shown to convert a binary string to a decimal number.

Public Function Bin_To_Dec(ByVal Bin As String)
‘function to convert a binary number to decimal
Dim dec As Double = Nothing
Dim length As Integer = Len(Bin)
Dim temp As Integer = Nothing
Dim x As Integer = Nothing
For x = 1 To length
temp = Val(Mid(Bin, length, 1))
length = length - 1
If temp <> “0″ Then
dec += (2 ^ (x - 1))
End If
Next
Return dec
End Function

Posted by Mahesh ( Tryangled )

Custom Paging results in ASP.NET?

Monday, March 24th, 2008

<%@ Page Language=”VB” Debug=”true” %>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>

<script language=”VB” runat=”server”>
Public objCon As New SQLConnection(”server=localhost;User id=SA;password=;database=Northwind”)

Sub Page_Load(Source as Object, E as EventArgs)
dim currentPage as integer
if request.querystring(”page”) = “” then
currentpage = 1
else
currentpage = request.querystring(”page”)
end if
getRst(currentPage)
getPaging(currentPage)
end sub

public sub getRst(page as integer)
dim pageNo as integer
dim sql as string
pageNo = 10 * (page - 1)
Dim ds as DataSet=New DataSet()
sql = “select * from tryemp”
Dim cmd As SQLDataAdapter = New SQLDataAdapter(sql, objCon)
cmd.Fill(ds, pageNo , 10, “results”)
rst_table.DataSource = ds.Tables(”results”).DefaultView
rst_table.databind()
end sub

Sub getPaging(cPage as integer)
Dim cmd As SQLCommand = New SQLCommand(”Select count(*) from Products”, objCon)
objCon.Open()
Dim totalRecords as integer = cmd.ExecuteScalar().toString
Dim totalPages As integer
if totalRecords MOD 10 = 0 then
totalPages = int(totalRecords / 10)
else
totalPages = int(totalRecords / 10) + 1
end if
Dim i as integer
Dim pageTxt As String = “More Pages :    ”

if cpage > 1 then
pageTxt += “<a href=paging.aspx?page=” & cPage - 1 & “>Previous</a>    ”
end if
for i = 1 to totalPages
if cPage = i then
pageTxt += “<b>” & i & “</b>    ”
else
pageTxt += “<a href=paging.aspx?page=” & i & “>” & i & “</a>    ”
end if
next i
if cpage < totalPages then
pageTxt += “<a href=paging.aspx?page=” & cPage + 1 & “>Next</a>    ”
end if
showpages.text = pageTxt
end sub
</script>
<html><body>
<asp:DataGrid runat=”server” Id=”rst_table” cellpadding=”0″ cellspacing=”2″ width=”96%” font-size = “10pt” RepeatColumns=”1″
/>
<asp:label id=”showpages” runat=”server” Font-Names=”Verdana” Font-Size=”12px”/>
</body></html>

Posted by Mahesh ( Tryangled )

How do I customize error messages for my site?

Monday, March 24th, 2008

You can customize error messages (404 Not Found, for example) by creating a file called .htaccess and including the appropriate entries. This file should be uploaded to your root directory (i.e., the “www” folder for your account).

Some of the most common messages are as follows:
Error in Client
400 Bad syntax
401 Unauthorized
402 Not Used (Payment Granted)
403 Forbidden
404 Not Found

Error in Server
500 Internal Error
501 Not Implemented
502 Overloaded
503 Gateway Timeout

You can customize error messages for your site as follows:
Create the HTML page you want to use as your error message and upload it to your web directory (/home/username/www). Next, edit your .htaccess file (or create one using a text editor) and add lines which specify the substitution.

Here are three examples of specifying error documents which will be called for a given error condition (note that you can use relative “thisfile.html” or absolute addressing “http://www .yourdomain.com/thisfile.html”):

ErrorDocument 401 http://yourdomain.com/nopasswordd.html
ErrorDocument 403 /forbidden.html
ErrorDocument 404 http://www.yourdomain.com/nofile.html

note: that Windows will not allow you to create a file called .htaccess. It will be necessary to create this file using another name and then rename it once you have uploaded it to your site.

Posted by Mahesh ( Tryangled )

I cant see .htaccess files in my FTP program. What can I do?

Monday, March 24th, 2008

Some FTP programs dont show dot files, files or directories that starts with a “.”, by default.
Below is instructions on how to show dot files in popular FTP programs.

FileZilla

1. View -> Show hidden files.

Cute FTP

1. Open the Site Manager (press F4) and click on the name of the relevant site.
2. Click the Actions tab, then click Filter.
3. Select the Enable Filtering check box.
4. In Server side filtering, select the Enable Server Side Filtering check box.
5. In the Remote Filter box, type -a.
6. Click OK, then click Connect.

WS_FTP Pro (7.62)

1. Sites
2. Organize sites
3. Site options
4. Startup tab
5. In Remote Filter Mask box enter -a

Posted by Mahesh ( Tryangled )

How do I make a .htaccess file on Windows?

Monday, March 24th, 2008

Windows will not let you rename a file to “.htaccess”. You will get an error “You must type a filename” if you try. Instead you can open the file you want to rename in a text editor, ie Notepad. Choose “Save as..” and select “All types (*.*)” next to file type. Now type the filename “.htaccess” and click save.

Posted by Mahesh ( Tryangled )

How to Ban a user based on IP address in ASP?

Monday, March 24th, 2008

This example shows how to prevent a user accessing your website , as long as you now their IP address .
<%
‘variables to store banned IP and the users IP
Dim strIP , strBannedIP
‘this is the banned IP address
strBannedIP = “127.0.0.1″
‘get the users IP address
strIP = Request.ServerVariables(”LOCAL_ADDR”)
‘if users address is the same as the banned IP address
‘display a message
If strBannedIP = strIP Then
Response.Write “You are not permitted to view this website”
‘if usersa ddress is different welcome message is displayed
Else
Response.Write “welcome”
End If
%>

Posted by Mahesh ( Tryangled )