This blog is about the dotnet.all types of codes,news about dotnet including asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.ncluding asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.asp.net programming,dot net programming,dotnet programs,dotnet source code,source code.

Free Hosting

Free Hosting

Friday, May 16, 2008

Convert database tables into XML and Schema in 12 lines

These 12 lines of VB.NET code in an ASP.NET file successfully convert a table from an Access database into a DataSet and then write this information about to an XML file and a Schema file. You can see with this example that XML is really at the center of .NET, fantastic!


Sub Page_Load()
Dim strConnect As String
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\edward\Association.mdb"
Dim strSelect As String
strSelect = "SELECT * FROM Members"
Dim objDataSet As New DataSet
Dim objConnect As New OleDbConnection(strConnect)
Dim objDataAdapter As New OleDbDataAdapter(strSelect, objConnect)
objDataAdapter.Fill(objDataSet, "Members")

Dim strVirtualPath As String = Request.ApplicationPath & "/Members.xml"
Dim strVSchemaPath As String = Request.ApplicationPath & "/Members.xsd"
objDataSet.WriteXML(Request.MapPath(strVirtualPath))
objDataSet.WriteXMLSchema(Request.MapPath(strVSchemaPath))
End Sub

Using Transaction in asp.net

Transaction is the execution of multiple DML(Data Manupulation Lanugage) Statements like Insert Update and Delete any record from a database table as a single execution means either all the statement will be executed or none, if there occurs any error between the excution whole execution will be terminated with no database record affected.

To implement transaction in c# with SQL server as database you have to import following below namespaces.

Using System.Data;
Using System.Data.sqlclient;


Now declare all the ADO.net objects with SQLTransaction variable

Sqlconnection sqlcon;
Sqlcommand sqlcmd;
SqlTransaction sqltr;
sqlcon=new sqlconnection(ConnectionString);


Now Open Connection and Call the connection's BeginTransaction() function. which will create a Transaction Object for this Connection which you can hold in your variable


try
{
sqlcon.open();
sqltr=sqlcon.BeginTransaction();
}

catch (Exception ex)
{
Response.Write(ex.ToString());
sqlcon.Close();
return;
}


Now set the all the SqlCommand oject/objects (if multiple Sqlcommand objects) Transcation property. and after sucessful exection call commit() of sqltransaction object and if any exception occured then call rollback().

try
{
sqlcmd.Transaction=sqltr;
sqlcmd=new sqlcommand("User Storedproc or Direct Table");

sqlcmd.executenonquery();

sqlcmd.parameters.clear();

sqlcmd.commandtext="Userstroedproc or direct Table";

sqltr.commit();
sqlcmd.executenonquery();
}

catch(Exception ex)
{
Response.Write(ex.ToString());
sqltr.Rollback();
sqlcon.Close();
}
finally
{
sqlcon.Close();
}

Extracting extesion of file while uploading

Many times in web application we need to upload file and require its extension to check the type of file, for this first import below namespace.
using System.IO;

Now extact extension with following code

fileUploadid="UpFile";
string fileExtension=System.IO.Path.GetExtensionUpFile.PostedFile.FileName);

Javascript confirm box on linkbutton

The below code attach a javascript confirmation dialog box on the click event of a link button. This code is applicable in asp.net 2.0 and above.

<asp :linkbutton id="btnDelete" runat="server" causesvalidation="false" commandname="Delete" onclientclick="return confirm('Are you want to delete this item?')" text = "Delete" />

Paypal Integration in asp.net

Paypal is the most popular payment gateway. Here I am describing the procedure to easly integrate your Asp.net e-commerce application with paypal. For this you must have a

Paypal account.

Step 1.

The below should be written on checkout button Click Event.
This code will redirect user to paypal website for payment and send the product and price information to paypal website.


string redirect;
redirect += "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" + Registered_Paypal_Email_ID;
redirect += "&item_name=" + "Item Name";
redirect += "&amount=" + String.Format("{0:0.00} ", amount);
redirect += "&item_number=" + itemID;
redirect += "¤cy=USD";
//redirect += "&add =1";
redirect += "&return=http://www.yoursite.com/returnurl.aspx";
redirect += "&cancel_return=http://www.yoursite.com/cancelUrl.aspx";
redirect += "¬ify_url=http://www.Yoursite.com/noftify.aspx";
redirect += "&custom=" + OrderID;
Response.Redirect(redirect);



When the payment is recived on your paypal account then paypal will send a notification to your site on "http://www.Yoursite.com/noftify.aspx" page that you have mentioned as

notify_url on above code.

Now on receiving the notification the your application must update your database regarding order confirmation.

now Below is the c# code that you have to write on notify.aspx.cs file's onLoad() event


string requestUriString;
CultureInfo provider = new CultureInfo("en-us");

string strFormValues = Encoding.ASCII.GetString(
this.Request.BinaryRead(this.Request.ContentLength));

requestUriString = "https://www.paypal.com/cgi-bin/webscr";


HttpWebRequest request =(HttpWebRequest)WebRequest.Create(requestUriString);


// Set values for the request back
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string obj2 = strFormValues + "&cmd=_notify-validate";
request.ContentLength = obj2.Length;

// Write the request back IPN strings
StreamWriter writer =
new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(RuntimeHelpers.GetObjectValue(obj2));
writer.Close();

//send the request, read the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(responseStream, encoding);

char[] buffer = new char[0x101];
int length = reader.Read(buffer, 0, 0x100);

while (length > 0)
{
// Dumps the 256 characters to a string
string OrderID;
string IPNResponse = new string(buffer, 0, length);
length = reader.Read(buffer, 0, 0x100);

try
{
// getting the total cost of the goods in
// cart for an identifier
// of the request stored in the "custom" variable
if (String.Compare(IPNResponse, "VERIFIED", false) == 0)
{


OrderID = this.Request["custom"].ToString();

if (String.Compare(OrderID, "", false) == 0)
{
Response.Write("Invalid Order ID");
return;
}

// Below on this block you can write the code to Update the status of your order in database for orderID
//

}


}
catch (Exception exception)
{
//Response.Write(exception.ToString());

return;
}


}

}

Create Squence No on a Datagrid with Paging

This Snip of code shows you how to create Squence No on a Datagrid with Paging.

<asp:DataGrid id="DataGrid1" runat="server" PagerStyleNumericPages   PageSize="10" AutoGenerateColumns="False" AllowPaging="True">
<Columns>

<asp:templatecolumn headertext="Row
Number">       

<itemtemplate>


<%# (DataGrid1.PageSize*DataGrid1.CurrentPageIndex)+ Container.ItemIndex+1%>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn   runat="server" DataField="CompanyName"
HeaderText="Company Name">

</asp:boundcolumn>
 

<asp:boundcolumn runat="server" DataField="Address"
HeaderText="Address">

</asp:boundcolumn>

</Columns>


</asp:DataGrid>


Tweak in the code is very simple, instead
of only using container.itemindex to get the sequence number. You need to
use Pagesize and currentpageindex to find out the starting number of that
page and then add container.itemindex to that.

Creating Javascript Tab Control.

This article will tell you how to create a javascript tab in your webpage.

Steps-

1) Create a Table in which the first row will contain the buttons used as Tab on different cell.
and there id should be relvent to the tab content for example.

<input id="btnGrid" type="button">


2) The below rows contain the div tags used as container for tab. There should be equal no of div tags to that of button and their id should relevent to the content and must be

such that removing the prefix of the corresponding button prefix it should be same. for example
Our button has id=btnGrid here btn is button prefix. Now you div should have id=Grid that means removing btn prefix.

set style="display:none; for each div tag except first one which should shown by default

3) Now make a javascript function lets call ShowHide()

<script type="text/javascript" language="javascript">

function Showhide(el)
{
// first hide all the div tags by setting style="display:none" and also set the button style to inactive on by just setting its css clss to inactive class if you have

the knowledge of css otherwis use

document.getElementById("btnGrid").style.backgroundColor="##EEEEEE"; // button
document.getElementById("Grid") = 'none'; // div

document.getElementById("btnGraph").style.backgroundColor="##EEEEEE"; // button
document.getElementById("Graph") = 'none'; // div
// and so on
// Now set display:block for the element that called the function and button to active color

document.getElementById('btn'+el).style.backgroundColor="##cccccc"; //for button
var e = document.getElementById(el); // for div
var st=e.style.display;

if(st == 'none')
e.style.display = 'block';
else
e.style.display = 'none';

}
lt;script>

4) Now call the function from each button like on its click event. for eg.

<input id="cmdGrid" type="button" value="Grid" onclick="showhideBenifits('Grid');" style="backgroundColor="##EEEEEE""/>

Now you are done.

Note. Set the first (default display) div display:block and button to active color and rest to display:none and button to inactive color.

You can also customize your own setting through css if have the knowledge.

This Tab is implemented in Codegenerator tool on this site you can see this on codegenerator page and view its source code too.

Recursive function and Tree control Population in ASP.NET C#

I had seen many people facing the problem in recursive function building so they try and avoid recursive function but recursive function’s are really help full in many places at the time of programming in looping through a unknown length of tables and fast too although try and use recursive function more carefully other wise they could also slow down the process many a time (if condition are not applied properly recursive function can fall in end less looping). We can avoid recursive function but some time recursive function are required and unavoidable (e.g. an building a tree function for ASP.NET Tree control) I have given a code for simple example in ASP.NET of Tree control as I needed it myself so I build itJ.

I had taken back end (Database) as MS SQL 2000 created a table called tree having Following Structure:

1. ID (Primary Key)

2. ItemName

3. ParentID

4. Active

You can add more fields according to your needs

ParentID will be 0 for root Node

e.g. like 'TV' is at parent and 'LG TV' an 'Samsung TV' are as child of 'TV' Data will be like.

----------------------------------

ID | ItemName | ParentID | Active

----------------------------------

23 | TV | 0 | 1

24 | Samsung TV | 23 | 1

25 | LG TV | 23 | 1

26 | Wash Machine | 0 | 1

27 | IFB WM | 26 | 1

28 | Whirlpool | 26 | 1

This is the following code

Please include following namespaces at the top

using System.Data.SqlClient;

using System.IO;

//Connection string CON used from web.config file

string constr = System.Configuration.ConfigurationManager.ConnectionStrings["CON"].ToString();

//Load first time only to avoid unnessary Recursion loops

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

PopulateTree();

}

}

//Called at first time to populate Root node values

private void PopulateTree()

{

SqlConnection con = new SqlConnection(constr);

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "Select * from Tree where active=1";

cmd.Connection = con;

DataTable dtMenu = new DataTable();

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dtMenu);

DataView dv = new DataView(dtMenu);

dv.RowFilter = "ParentID=0";

int i;

TreeView_Control.Nodes.Clear();

for (i = 0; i <>

{

TreeNode node = new TreeNode();

node.Value = dv[i]["ID"].ToString();

node.Text = dv[i]["ItemName"].ToString();

TreeView_Control.Nodes.Add(node);

RecFillTree(dtMenu, node);

}

}

//recursive function Called by PopulateTree() to populate Child of //nodes will go to any u nbroken depth and start by next ParentNode

private void RecFillTree(DataTable dtMenu, TreeNode ParentNode)

{

DataView dv = new DataView(dtMenu);

dv.RowFilter = "ParentID =" + ParentNode.Value;

int i;

if (dv.Count > 0)

{

for (i = 0; i <>

{

TreeNode node = new TreeNode();

node.Value = dv[i]["ID"].ToString();

node.Text = dv[i]["ItemName"].ToString();

ParentNode.ChildNodes.Add(node);

RecFillTree(dtMenu, node);

}

}

}

//displaying the value and text of the select node

protected void TreeView_Control_SelectedNodeChanged(object sender, EventArgs e)

{

LblTreeNode_Text.Text=TreeView_Control.SelectedNode.Text;

LblTreeNode_Value.Text = TreeView_Control.SelectedNode.Value;

}

}

I think this articales will help in your various Recurcive Looping and Tree control building problem.

Free Webservice to Send SMS

If you neew your webapplication to send SMS on mobile phones, here is the free webservice to do that.
Service Path: http://www.webservicex.net/SendSMS.asmx?WSDL

Here i am describing how to use it in your asp.net application through C# implementation.

Steps to refer webservice.
1. Goto Explores window in Visual Studio.
2. Right click on project and select Add Web Reference from the context menu that opened after right clicking
3. Add web reference window will be opend. Now paste "http://www.webservicex.net/SendSMS.asmx?WSDL" on url address bar and click on go button.
4.After few seconds depending on your internet speed the service descrition and method will be shown to you. Just click on Add reference button to add this service to your project.

C# Code to implement this service
net.webservicex.www.SendSMS smsIndia = new net.webservicex.www.SendSMS();
smsIndia.SendSMSToIndia("mobile no","your email id", "Message");


Note: You can send SMS to India only and Network Covered: Airtel,Idea Cellular,Skycell ,RPG Cellular,Hutch now vodaphone,Celforce / Fascel,BPL Mobile,Escotel.

Free Currency Conversion webservice in .net

Sometimes the webapplications espcially ecommerce websites needs currency conversion services to show their product exact price in other currencies. We cant do it by just multiplying with other conversion rates as there currency rates always changes. Here in this article a currency conversion xml webservice is described. The sevice path is http://www.webservicex.net/CurrencyConvertor.asmx?wsdl..

Here i am describing how to use it in your asp.net application through C# implementation.

Steps to refer webservice.
1. Goto Explores window in Visual Studio.
2. Right click on project and select Add Web Reference from the context menu that opened after right clicking
3. Add web reference window will be opend. Now paste "http://www.webservicex.net/CurrencyConvertor.asmx?wsdl" on url address bar and click on go button.
4.After few seconds depending on your internet speed the service descrition and method will be shown to you. Just click on Add reference button to add this service to your project.

C# Code to implement this service

net.webservicex.www.CurrencyConvertor MyExRate = new net.webservicex.www.CurrencyConvertor();
double conversionRate = MyExRate.ConversionRate((net.webservicex.www.Currency)Enum.Parse(typeof(net.webservicex.www.Currency), "Currency Code From"), (net.webservicex.www.Currency)Enum.Parse(typeof(net.webservicex.www.Currency),"Currency COde To"));

double result = pricetoConvert * conversionRate;


Note: You have to replace Currency Code From and Currency Code to to respective Currency code

List of Supported Currency With their Currency Code

UAE Dirham-AED
Afghanistan Afghani-AFA
Albanian Lek-ALL
Neth Antilles Guilder-ANG
Argentine Peso-ARS
Australian Dollar-AUD
Aruba Florin-AWG
Barbados Dollar-BBD
Bangladesh Taka-BDT
Bahraini Dinar-BHD
Burundi Franc-BIF
Bermuda Dollar-BMD
Brunei Dollar-BND
Bolivian Boliviano-BOB
Brazilian Real-BRL
Bahamian Dollar-BSD
Bhutan Ngultrum-BTN
Botswana Pula-BWP
Belize Dollar-BZD
Canadian Dollar-CAD
Swiss Franc-CHF
Chilean Peso-CLP
Chinese Yuan-CNY
Colombian Peso-COP
Costa Rica Colon-CRC
Cuban Peso-CUP
Cape Verde Escudo-CVE
Cyprus Pound-CYP
Czech Koruna-CZK
Dijibouti Franc-DJF
Danish Krone-DKK
Dominican Peso-DOP
Algerian Dinar-DZD
Estonian Kroon-EEK
Egyptian Pound-EGP
Ethiopian Birr-ETB
Euro-EUR
Falkland Islands Pound-FKP
British Pound-GBP
Ghanian Cedi-GHC
Gibraltar Pound-GIP
Gambian Dalasi-GMD
Guinea Franc-GNF
Guatemala Quetzal-GTQ
Guyana Dollar-GYD
Hong Kong Dollar-HKD
Honduras Lempira-HNL
Croatian Kuna-HRK
Haiti Gourde-HTG
Hungarian Forint-HUF
Indonesian Rupiah-IDR
Israeli Shekel-ILS
Indian Rupee-INR
Iraqi Dinar-IQD
Iceland Krona-ISK
Jamaican Dollar-JMD
Jordanian Dinar-JOD
Japanese Yen-JPY
Kenyan Shilling-KES
Cambodia Riel-KHR
Comoros Franc-KMF
North Korean Won-KPW
Korean Won-KRW
Kuwaiti Dinar-KWD
Cayman Islands Dollar-KYD
Kazakhstan Tenge-KZT
Lao Kip-LAK
Lebanese Pound-LBP
Sri Lanka Rupee-LKR
Liberian Dollar-LRD
Lesotho Loti-LSL
Lithuanian Lita-LTL
Latvian Lat-LVL
Libyan Dinar-LYD
Moroccan Dirham-MAD
Moldovan Leu-MDL
Malagasy Franc-MGF
Macedonian Denar-MKD
Myanmar Kyat-MMK
Mongolian Tugrik-MNT
Macau Pataca-MOP
Mauritania Ougulya-MRO
Maltese Lira-MTL
Mauritius Rupee-MUR
Maldives Rufiyaa-MVR
Malawi Kwacha-MWK
Mexican Peso-MXN
Malaysian Ringgit-MYR
Mozambique Metical-MZM
Namibian Dollar-NAD
Nigerian Naira-NGN
Nicaragua Cordoba-NIO
Norwegian Krone-NOK
Nepalese Rupee-NPR
New Zealand Dollar-NZD
Omani Rial-OMR
Panama Balboa-PAB
Peruvian Nuevo Sol-PEN
Papua New Guinea Kina-PGK
Philippine Peso-PHP
Pakistani Rupee-PKR
Polish Zloty-PLN
Paraguayan Guarani-PYG
Qatar Rial-QAR
Romanian Leu-ROL
Russian Rouble-RUB
Saudi Arabian Riyal-SAR
Solomon Islands Dollar-SBD
Seychelles Rupee-SCR
Sudanese Dinar-SDD
Swedish Krona-SEK
Singapore Dollar-SGD
St Helena Pound-SHP
Slovenian Tolar-SIT
Slovak Koruna-SKK
Sierra Leone Leone-SLL
Somali Shilling-SOS
Surinam Guilder-SRG
Sao Tome Dobra-STD
El Salvador Colon-SVC
Syrian Pound-SYP
Swaziland Lilageni-SZL
Thai Baht-THB
Tunisian Dinar-TND
Tonga Pa'anga-TOP
Turkish Lira-TRL
Turkey Lira-TRY
Trinidad & Tobago Dollar-TTD
Taiwan Dollar-TWD
Tanzanian Shilling-TZS
Ukraine Hryvnia-UAH
Ugandan Shilling-UGX
U.S. Dollar-USD
Uruguayan New Peso-UYU
Venezuelan Bolivar-VEB
Vietnam Dong-VND
Vanuatu Vatu-VUV
Samoa Tala-WST
CFA Franc (BEAC)-XAF
Silver Ounces-XAG
Gold Ounces-XAU
East Caribbean Dollar-XCD
CFA Franc (BCEAO)-XOF
Palladium Ounces-XPD
Pacific Franc-XPF
Platinum Ounces-XPT
Yemen Riyal-YER
Yugoslav Dinar-YUM
South African Rand-ZAR
Zambian Kwacha-ZMK
Zimbabwe Dollar-ZWD<

C-sharp Code to Upload a file through ftp

Here I am giving the code to access ftp server thruogh your .net applcation. The code works on both windows as well as web. You can upload a file through ftp and make your own ftp client by researching more on this top.

System.Net.FtpWebRequest ftpClient=System.Net.FtpWebRequest.Create("ftp://Yoursite.com/yourdirectory/"+"Filename");
ftpClient.Credentials = new System.Net.NetworkCredential("loginname", "password");
ftpClient.Method=System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary=true;
System.IO.FileInfo fi= new System.IO.FileInfo("Local FilePath to be Uploaded");
ftpClient.ContentLength=fi.Length;
int bufferSize=2048;
byte[] content= new byte[bufferSize-1];
int dataread;
System.IO.FileStream fs=fi.OpenRead();
try
{
}
catch (Exception ex)
{
System.IO.Stream rs=ftpClient.GetRequestStream();
do{
dataread=fs.Read(content,0,bufferSize);
rs.Write(content,0,dataread);
}while(dataread<bufferSize);
}


finally
{
fs.Close();

Formatting Multiline Textbox content

When you display multiple lines of data from the database you loose the spacing or formatting between multiple lines of data. Also in some applications like Forums, where users can post HTML content directly which can lead to some serious problems, Someone can post a link to some malicious coded page and all the users can become easy targets which can cause some serious security implications.

There is a common solution to both the above problems, you have to parse the Text content from the Database into respective HTML tags.

1) Formatting Solution: In HTML denotes a extra white space. So every 2 white spaces should be substituted by a single white space and .
Also every line terminator should be replaced by the break tag
, which will result in the next character starting for a new line.

2) HTML Content: The solution to this is a bit tricky, in HTML every valid tag is contained within the <> brackets. So to make all the HTML tags in your post invalid just change the <> tags to their HTML counter parts < and > respectively. Also one other formatting change to be made is that the double quotation mark " has to be changed into its HTML equivalent "


Code

1) ParseText method :- The method to convert Text into HTML
public string parsetext(string text, bool allow)
{
//Create a StringBuilder(using System.Text namesapace) object from the string input
//parameter
StringBuilder sb = new StringBuilder(text) ;
//Replace all double white spaces with a single white space
//and
sb.Replace(" "," ");
//Check if HTML tags are not allowed
if(!allow)
{
//Convert the brackets into HTML equivalents
sb.Replace("<","<") ; sb.Replace(">",">") ;
//Convert the double quote
sb.Replace("\"",""");
}
//Create a StringReader from the processed string of
//the StringBuilder
StringReader sr = new StringReader(sb.ToString());
StringWriter sw = new StringWriter();
//Loop while next character exists
while(sr.Peek()>-1)
{
//Read a line from the string and store it to a temp
//variable
string temp = sr.ReadLine();
//write the string with the HTML break tag
//Note here write method writes to a Internal StringBuilder
//object created automatically
sw.Write(temp+"
") ;
}
//Return the final processed text
return sw.GetStringBuilder().ToString();
}


2) textparser.aspx - A sample consumer for the Text to HTML parser
private void Post_Text(object sender, EventArgs e)
{
//Check if there is some text inside the TextBox
if(mess.Text!="")
{
//Check if option to Parse Text is selected
if(parse.Checked)
{
//Check if option to convert HTML tags to text is selected
if(htmlpost.Checked)
{
//Call the parsetext method
//Pass the text content from the textbox and false so that
//HTML tags do not get converted to text
postmess.Text=parsetext(mess.Text,false) ;
}
else
{
//Call the parsetext method
//Pass the text content from the textbox and true so that
//HTML tags get converted to text
postmess.Text=parsetext(mess.Text,true) ;
}
}
else
{
//Just post the text without any parsing
postmess.Text=mess.Text ;
}
}
}

//Method to parse Text into HTML
public string parsetext(string text, bool allow)
{
//Create a StringBuilder object from the string input
//parameter
StringBuilder sb = new StringBuilder(text) ;
//Replace all double white spaces with a single white space
//and
sb.Replace(" "," ");
//Check if HTML tags are not allowed
if(!allow)
{
//Convert the brackets into HTML equivalents
sb.Replace("<","<") ; sb.Replace(">",">") ;
//Convert the double quote
sb.Replace("\"",""");
}
//Create a StringReader from the processed string of
//the StringBuilder object
StringReader sr = new StringReader(sb.ToString());
StringWriter sw = new StringWriter();
//Loop while next character exists
while(sr.Peek()>-1)
{
//Read a line from the string and store it to a temp
//variable
string temp = sr.ReadLine();
//write the string with the HTML break tag
//Note here write method writes to a Internal StringBuilder
//object created automatically
sw.Write(temp+"
") ;
}
//Return the final processed text
return sw.GetStringBuilder().ToString();
}

Creating XML File in DotNet

For creating dynamic xml file you need to import System.Xml namespace

Private void CreateXmlFile()
{
// Creating XML with saving file location
XmlTextWriter xmlWriter = new XmlTextWriter(Server.MapPath(".") "propertydetails.xml", System.Text.Encoding.UTF8);
xmlWriter.WriteStartDocument();
//For Creating XML Root Element
xmlWriter.WriteStartElement("RootElemet");

//For Creating ChildXMlNode
xmlWriter.WriteStartElement("ChildNode");

//For Creating XMLSubChildNode
xmlWriter.WriteElementString("SubChildNode", "TextforSubChildNode");
// Closing XMLChildNodexmlWriter.WriteEndElement();// Closing XMLChildNode
// Closing XMLRootNode
xmlWriter.WriteEndDocument();
//Closing File
xmlWriter.Close();
}

Creating Thumbnail of an Image with maintained aspect ratio in C Sharp

For creating thumnail images C# has function in System.Drawing in namespace. System.Drawing.Image class contains GetThubnailImage function which creates thumbnail of an image but use this function wisely to create thubnail which maintains the aspect ratio of image thumbnai. Below is the C# function which creates the thumbnail of an image with maintained aspect ratio.

public static void Create_Thumbnails(int size, string FilePath, string ThumbPath)
{
// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(FilePath);
try
{
int thumbHeight, thumbWidth;
decimal h = image.Height;
decimal w = image.Width;
if (image.Height > image.Width)
{
thumbHeight = size;
decimal tWidth = (w / h) * thumbHeight;
thumbWidth = Convert.ToInt32(tWidth);
}
else
{
thumbWidth = size;
decimal tHeight = (h / w) * thumbWidth;
thumbHeight = Convert.ToInt32(tHeight);
}

// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);
image.Dispose();

// put the image into the memory stream
thumbnailImage.Save(ThumbPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
image.Dispose();
throw ex;
}
}

Adding Meta Tag Dynamically on your Asp.net Web page

Web programmers are familier with the use of Meta Tags on a web page. The meta tags are used to provides keywords, Title, description etc in an HTML page which describes the website to search engines. ASP.NET 2.0, you can add these meta tags programmatically. The HtmlMeta class provides programmatic access to the HTML <meta> element on the server. The HTML <meta> element is a container for data about the rendered page, but not page content itself.

The Name property of HtmlMeta provides the property name and the Content property is used to specify the property value. The Scheme property to specify additional information to user agents on how to interpret the metadata property and the HttpEquiv property in place of the Name property when the resulting metadata property will be retrieved using HTTP.

The code below shows how to add meta tags to a page programmatically.

HtmlMeta hm= new HtmlMeta();
HtmlHead head=(HtmlHead)Page.Header;
hm.Name="Keywords";
hm.Content="your Keywords content";
head.Controls.Add(hm);

Similarly, you can add Description, Title , Abstract etc meta tags to the web page header.

How to send Email in ASP.Net 2.0

How to send Email in ASP.Net 2.0
have changed from ASP.Net1.1 and ASP.Net 2.0, for email sending. The namespace has changed from System.Web.Mail to System.Net.Mail. and to get the email working, there are two classes that need to be addressed:

  • MailMessage()
  • SmtpClient()
To use these, it will look something like this:
using System.Net.Mail;
SmtpClient MailClient=new SmtpClient("127.0.0.1");
MailMessage Msg = new MailMessage(SenderAddress,ReceiptAddress);
Msg.Subject = "YourSubject";
string Message="";
Message="";
Message += "";
Message += "";
Message += "
Thank you for registerting in allabout-dotnet.blogspot.com
Your EMail:" + txtEMail.Text.ToString() + "
Your Password:" + TxtPassword.Text.ToString() + "
";
Msg.Body = Message;
Msg.IsBodyHtml = true;
try
{
MailClient.Send(Msg);
}
catch (System.Exception ex)
{
Response.Write(ex.toString());
}

As said earlier, several things have changed, and, it's not quite as easy as it was with ASP.Net version 1.1, but still, emailing in ASP.Net is not complicated at all.

Email address verification for your C#, VB.NET, and ASP.NET applications


The Email Checker .NET component offers .NET developers sophisticated email verification
from within their applications. Validate email address syntax and verify against the domain’s mail server.



The Email Checker provides full syntax checking of email addresses as well as
domain verification and user name testing using SMTP. Select the level of
checking you require from a fast syntax check, to a DNS server MX record lookup
to ensure the domain name is valid and a mail server is configured, to finally
an SMTP check of the user name against the mail server.



Part of the award winning .NET Internet Component Suite,
the component is designed specifically for .NET and is written in 100% managed C# code.



What's Included




Checking an Email Address



  • Specify the type of check to perform: syntax, domain name, user name


  • Perform email address checks either synchronously or asynchronously



Syntax Checking



  • Full syntax checking as per RFC 2822


  • Extract email address components including display name, user name and domain name



Domain Name Verification



  • Validates the domain name by performing a DNS query to retrieve the domain's MX records


  • Supports using DNS A records if no MX records are configured


  • Uses default list of DNS servers or optionally specify which DNS servers to use


  • Supports DNS server outages by automatically trying backup DNS servers




Email Address Verification



  • Validates the email address by communicating with the mail server using SMTP (RFC 2821)*


  • No email is sent to the user


  • Supports SMTP server outages by automatically trying backup SMTP servers



Designed for .NET



  • Object oriented design specifically for the .NET framework


  • 100% managed code written in C#


  • Make either synchronous or asynchronous (Begin/End) calls


  • Asynchronous calls may either use events or callbacks





The Email Checker .NET component offers .NET developers sophisticated email verification
from within their applications. Validate email address syntax and verify against the domain’s mail server.



The Email Checker provides full syntax checking of email addresses as well as
domain verification and user name testing using SMTP. Select the level of
checking you require from a fast syntax check, to a DNS server MX record lookup
to ensure the domain name is valid and a mail server is configured, to finally
an SMTP check of the user name against the mail server.



Part of the award winning .NET Internet Component Suite,
the component is designed specifically for .NET and is written in 100% managed C# code.



What's Included




Checking an Email Address



  • Specify the type of check to perform: syntax, domain name, user name


  • Perform email address checks either synchronously or asynchronously



Syntax Checking



  • Full syntax checking as per RFC 2822


  • Extract email address components including display name, user name and domain name



Domain Name Verification



  • Validates the domain name by performing a DNS query to retrieve the domain's MX records


  • Supports using DNS A records if no MX records are configured


  • Uses default list of DNS servers or optionally specify which DNS servers to use


  • Supports DNS server outages by automatically trying backup DNS servers




Email Address Verification



  • Validates the email address by communicating with the mail server using SMTP (RFC 2821)*


  • No email is sent to the user


  • Supports SMTP server outages by automatically trying backup SMTP servers



Designed for .NET



  • Object oriented design specifically for the .NET framework


  • 100% managed code written in C#


  • Make either synchronous or asynchronous (Begin/End) calls


  • Asynchronous calls may either use events or callbacks




dotnet(.Net) Project Source code Downloads and Tutorials

Email Subscrption



Enter your email address:

Delivered by FeedBurner

Feedburner Count

Unique Visitor

Design by araba-cı | MoneyGenerator Blogger Template by GosuBlogger