File Mail With Attachement In asp.net


For this Code go on this link

http://www.aspnettutorials.com/tutorials/network/net-fileupload-aspnet2-csharp.aspx

This Link Will Provide You Complete Code

http://www.codeproject.com/KB/aspnet/ASPNETwebmail.aspx

ASP.NET email with multiple attachments

A simple web form that lets the user upload multiple attachments to create and send email.

Introduction

This application demonstrates the use of some simple but useful things you can do with ASP.NET; uploading, saving and deleting files, and sending email.

There are three things we need to do to be able to run this code and I’m going to assume that you will be trying out this code at home on a Windows desktop computer.

First, you need to create a virtual directory in IIS to host this web application and set write permission because we will be saving and deleting files that will be email attachments. In the virtual directory, create a folder called “attachments“. This is where we will temporarily store the uploaded files to attach to the email.

The second thing to do is to make sure that the SMTP server is running and that it can relay mail. From the IIS MMC window, with “local computer” selected on the left, you should see the “Default SMTP Virtual Server“, if not you need to install it. Right-click it, go into “Properties”, the “Access” tab, and click the “Relay” button. With the “only the list below” radio button selected, you should see the local IP address: 127.0.0.1, if it’s not there, you need to add it.

The last thing is to set up the SMTP server in the application. In the code, look for this line (line # 149):

SmtpMail.SmtpServer = "localhost";

You need to replace “localhost” with the name or IP address of your SMTP mail server. On a Windows desktop computer, “localhost” is the default value and usually works.

Using the code

First of all, we create a new MailMessage object and we call it “email“. Then we set the FromToSubjectand Body properties as well as the BodyFormatof of this object to the values on our web form.

// Create a new blank MailMessage

 MailMessage email = new MailMessage ();

// Set the properties of the MailMessage to the

// values on the form

 if (rblMailFormat.SelectedItem.Text == "text")
  email.BodyFormat = MailFormat.Text;
 else
  email.BodyFormat = MailFormat.Html;
 email.From = txtSender.Text;
 email.To = txtReceiver.Text;
 email.Subject = txtSubject.Text;
 email.Body = txtBody.Text;

Now for the meat and potatoes of this little web application; the following block of code checks the first of threeOpen File Dialogs of our web form (the Open File Dialog is an HTML File Field control to which we’ve added therunat="server" property). If there is a value, the file is uploaded, saved on the server, and added as an attachment to the email. The processing of the two other Open File Dialogs are just the same.

// Beginning of attachments processing

// Check the first open file dialog for a value

 if (ofdAttachment1.PostedFile != null)
 {
  // Get a reference to PostedFile object

  HttpPostedFile ulFile = ofdAttachment1.PostedFile;
  // Get size of the file

  int nFileLen = ulFile.ContentLength; 
  // Make sure the size of the file is > 0

  if( nFileLen > 0 )
  {
   // Get the file name

   strFileName = Path.GetFileName(ofdAttachment1.PostedFile.FileName);
   // Preced the file name with "attachments/" so 

   // the file is saved to our attachments directory

   strFileName = "attachments/" + strFileName;
   // Save the file on the server

   ofdAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));
   // Create the email attachment with the uploaded file

   MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));
   // Attach the newly created email attachment

   email.Attachments.Add(attach);
   // Store filename so we can delete it later

   attach1 = strFileName;
  }
 }

Then we send the email and finish by deleting the attachments.

// Set the SMTP server and send the email

 SmtpMail.SmtpServer = "localhost";
 SmtpMail.Send (email);

// Delete the attachements if any

 if (attach1 != null)
  File.Delete(Server.MapPath(attach1));

Points of Interest

This little project shows a practical use of the System.Web.HttpPostedFile and theSystem.Web.Mail.SmtpMail objects. The HttpPostedFile object is probably the simplest way to let a web user upload a file. I also tried to create the file attachment using a FileStream, hoping that I would be able to create the attachment without having to first save the file. I haven’t figured that one out yet.

Advertisements

DLR VS CLR


1)

DLR Means dynamic language runtime

CLR Means Common language runtime

2)

the CLR has an instruction called InvokeVirtual, which is used for calling a virtual method on a class or interface instance. When the classloader reads a .NET assembly, it verifies that the method targets for InvokeVirtual are all valid methods for the classes/interfaces where they’re used.

DLR includes a new opcode called InvokeDynamic, which supports method invocations on unknown on non-existent methods.

3)

dynamic languages often allow classes to be dynamically redefined by program logic (which is disallowed by both the CLR and the JVM).

4)

From the beginning, Microsoft’s .NET framework was designed to support a broad range of different programming languages on a Common Language Runtime (CLR).  The CLR provides shared services to these languages ranging from a world-class GC and JIT to a sandboxed security model to tools integration for debugging and profiling.  Sharing these features has two huge benefits for languages on the CLR.

The new Dynamic Language Runtime (DLR) adds a small set of key features to the CLR to make it dramatically better.  It adds to the platform a set of services designed explicitly for the needs of dynamic languages.  These include a shared dynamic type system, standard hosting model and support to make it easy to generate fast dynamic code.  With these additional features it becomes dramatically easier to build high-quality dynamic language implementations on .NET.

ASP.NET Dynamic Language RunTime(DLR In Vs2010)


Dynamic Languages are a class of high-level programming languages that do not rely on static typing. Many decisions that are made at compile time by a statically typed language are instead made at run time by a dynamic language. For example, many dynamic languages use dynamic typing, where an object’s type is determined at run time instead of at compile time. These languages make a trade-off between compile-time type-checking in favor of increased flexibility at run time.

There are many good static languages, such as C#, and many good dynamic languages, such as IronPython. The choice of what type of language to use comes down to personal preference and to the nature of the project you’re working on.

Giving ASP.NET users the choice of languages was part of the design since our first version of ASP.NET, and this Dynamic Language Support is just another step in that direction. Unlike other Web platforms that support only one language, the ASP.NET team wants to enable users to choose the language that fits them best.

What is Run time and Compile Time

Run Time: When a program is running, or executing, it is said to be in runtime. The term is mostly used by software developers to specify when errors in a program occur. A “runtime error” is an error that happens while the program is executing. For example, if a program told you that 2 + 2 was 5000, that would be a runtime error. A memory leak, where the program sucks up excessive amounts of system memory is also a runtime error.

Compile Time : other major type of program error is a compile-time error, where the application will not even compile into an executable program. Examples of compile-time errors are syntax errors in the program code and file linking errors.

Compiler

To transform a program written in a high-level programming language from source code into object code. Programmers write programs in a form called source code. Source code must go through several steps before it becomes an executable program. The first step is to pass the source code through a compiler, which translates the high-level language instructions into object code.
The final step in producing an executable program — after the compiler has produced object code — is to pass the object code through a linker. The linker combines modules and gives real values to all symbolic addresses, thereby producing machine code

To transform a program written in a high-level programming language from source code into object code. Programmers write programs in a form called source code. Source code must go through several steps before it becomes an executable program. The first step is to pass the source code through a compiler, which translates the high-level language instructions into object code.The final step in producing an executable program — after the compiler has produced object code — is to pass the object code through a linker. The linker combines modules and gives real values to all symbolic addresses, thereby producing machine code

WHAT IS IN NEW AND OLD MS SQL SERVER (2008 TOPICS)


A)   Database Engine

i)                Architecture

ii)               Database Design(Designing Tables)

iii)            Constraints

iv)             Transact SQL:(Joins,SubQueries,Co-Related Queries)

v)                Store Procedure

vi)             User Define Functions(UDF)

vii)           Triggers

viii)          Cursors

ix)             Indexes

x)                User Define Types(New)

xi)              CLR Integration(New) 2005:

We can write same keywords like (System. SqlClient, System.Data) in SQL Server because of CLR but Oracle doesn’t support it.

xii)             Transactions.

xiii)           XML (Important)

xiv)          Security

xv)            Full Text Search(e.g: google, Alta-Vista)

xvi)          Backup & Recovery

B)   REPLICATION

C)   DISTRIBUTED QUERIES

D)   INTEGRATION SERVICES:-

For fetching the data from various types of the file like Notepad, Excel, Word, PDF etc. Manipulation is possible by the Integration Services.

E)     REPORTING SERVICES:-

It’s a reporting tool of Microsoft. It comes under the MS SQL only. No need to Install the IIS in 2008.

F)     ANALYSIS SERVICES:-

G)   SQL AGENT:

Scheduling is possible thought the SQL Agent. Scheduling means Automatic Email Sending and Daily Database Backup.

H)    SQL INJECTION

I)        SQL PROFILER:- It’ used for the optimization.

J)       ERROR HANDLING

K)    BCP (BULK COPY PROGRAM)

L)     SERVICE BROKER:(For messaging)

SQL Server 2008 delivers on Microsoft’s Data Platform vision by helping your organization manage any data, any place, any time. It enables you to store data from structured, semi‑structured, and unstructured documents, such as images and music, directly within the database. SQL Server 2008 delivers a rich set of integrated services that enable you to do more with your data such as query, search, synchronize, report, and analyze. Your data can be stored and accessed in your largest servers within the data center all the way down to desktops and mobile devices, enabling you to have control over your data no matter where it is stored.

SQL Server 2008 enables you to consume your data within custom applications developed using Microsoft .NET and Visual Studio and within your service‑oriented architecture (SOA) and business process through Microsoft BizTalk Server while information workers can access data directly in the tools they use every day, such as the 2007 Microsoft Office system. SQL Server 2008 delivers a trusted, productive, and intelligent data platform for all your data needs.

How can Get focus on textbox when page load in asp.net


Hello friends today you will learn how to use javascript function and call him on body load in asp.net

Step 1: You make a new web site as You know and then Select Your Default.aspx page and Go into source of your page

And Write down code as given below

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<head runat=”server”>
<script type=”text/javascript” language=”javascript” >
function getfocus() {
document.getElementById(“Text1“).focus();
}
</script>
<title></title>
</head>
<body onload=”Javascript:getfocus()”>
<form id=”form1″ runat=”server”>
<div>
<input id=”Text1″ type=”text” runat=”server”  /></div>
</form>
</body>
</html>

Serialization and Deserialization in ASP.NET


In simple words, we can say an object conversion in text stream is serialization and text stream conversion in object of a class is called deserialization

Types of Serialization

1) XML

2)Binary

3)Custom

Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set

Why Serialization and Deserialization

Let’s say we have a very complex object and we need XML format for our XSLT rendering on HTML page. Then we have one option that we will write a XML file in the disk after parsing object variable and than load the XML file in XmlDocument object. But is it really a good approach? No, of course not. Why so. This is because in large applications, we have so many users and we will be writing files for every one. This will take lots of space as well as it is risky that might be files are shared among the users or any human being can read that file.
So what do we do now? Yes at this time, go with serialization, get an XML string and just load it toXmlDocument. This will be done in code.

Let’s say we have a very complex object and we need XML format for our XSLT rendering on HTML page. Then we have one option that we will write a XML file in the disk after parsing object variable and than load the XML file in XmlDocument object. But is it really a good approach? No, of course not. Why so. This is because in large applications, we have so many users and we will be writing files for every one. This will take lots of space as well as it is risky that might be files are shared among the users or any human being can read that file.
So what do we do now? Yes at this time, go with serialization, get an XML string and just load it toXmlDocument

How Do We Achieve This

First note that for serialization and deserialization, we need to use System.Xml.Serialization, because we need to use XmlSerialization class which is provided in System.Xml.Serialization.

To understand this, we assume one example of Category and Items. We have two classes. One is Categoryand another is ItemsCategory has CategoryIDCategory Name and Array of Item. While Item hasItem IDItem NameItem Price and Item Quantity in Stock.

public class Category
{
    private int _CatID;
    private string _CatName;
    private Item[] _Item;

    public int CateboryID
    {
        get
        {
            return _CatID;
        }
        set
        {
            _CatID = value;
        }
    }

    public string CategoryName
    {
        get
        {
            return _CatName;
        }
        set
        {
            _CatName = value;
        }
    }

    public Item[] Item
    {
        get
        {
            return _Item;
        }
        set
        {
            _Item = value;
        }
    }
}

public class Item
{
    private int _ItemID;
    private string _ItemName;
    private int _ItemPrice;
    private int _ItemQtyInStock;

    public int ItemID
    {
        get
        {
            return _ItemID;
        }
        set
        {
            _ItemID = value;
        }
    }

    public string ItemName
    {
        get
        {
            return _ItemName;
        }
        set
        {
            _ItemName = value;
        }
    }

    public int ItemPrice
    {
        get
        {
            return _ItemPrice;
        }
        set
        {
            _ItemPrice = value;
        }
    }

    public int ItemQtyInStock
    {
        get
        {
            return _ItemQtyInStock;
        }
        set
        {
            _ItemQtyInStock = value;
        }
    }
}

private void Serialization()
    {
        Category Cat = new Category();
        Cat.CateboryID = 1;
        Cat.CategoryName = "Phone";
        Item[] Itm = new Item[5];
        for (int i = 0; i < 5; i++)
        {
            Itm[i] = new Item();
            Itm[i].ItemID = i;
            Itm[i].ItemPrice = i * 10;
            Itm[i].ItemQtyInStock = i + 10;
            Itm[i].ItemName = " Item Name : " + i.ToString();

        }
        Cat.Item = Itm;
        XmlSerializer ser = new XmlSerializer(Cat.GetType());
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter writer = new System.IO.StringWriter(sb);
        ser.Serialize(writer, Cat); 	// Here Classes are converted to XML String. 
				// This can be viewed in SB or writer.
        // Above XML in SB can be loaded in XmlDocument object
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());
    }

Here Ser is the object of System.Xml.Serialization.XmlSerializer
class. It gets the Type ofCategory class object by Cat.GetType().
ser.Serialize takes two parameters, one is
 string writer like a target object and another is Cat that is
 source object. This converts or Serializes Cat object and stores stream
into a writer object. Now object is converted into XML string and we
 can find that by usingstringbuilder’s object. Like sb.ToString(). This string 
can be loaded in XML document for further traversing.

Let’s have look at Deserialization

In our application, we have Deserialization function which is called by our click event or whenever this is required. In deserialization, we have created one object of Category  class.
protected void DeSerialize(string XmlString)
    {
        Category Cat = new Category();
        XmlDocument doc = new XmlDocument();
        doc.LoadXml (XmlString);
        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        XmlSerializer ser = new XmlSerializer(Cat.GetType());
        object obj = ser.Deserialize(reader);
        // Then you just need to cast obj into whatever type it is, e.g.:
        Category myObj = (Category)obj;
        Now Ser
    }

XMLString for DeSerialization

<?xml version="1.0" encoding="utf-16"?>
<Category>
      <CateboryID>1</CateboryID>
      <CategoryName>Phone</CategoryName>
      <Item>
            <Item>
                  <ItemID>0</ItemID>
                  <ItemName> Item Name : 0</ItemName>
                  <ItemPrice>0</ItemPrice>
                  <ItemQtyInStock>10</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>1</ItemID>
                  <ItemName> Item Name : 1</ItemName>
                  <ItemPrice>10</ItemPrice>
                  <ItemQtyInStock>11</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>2</ItemID>
                  <ItemName> Item Name : 2</ItemName>
                  <ItemPrice>20</ItemPrice>
                  <ItemQtyInStock>12</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>3</ItemID>
                  <ItemName> Item Name : 3</ItemName>
                  <ItemPrice>30</ItemPrice>
                  <ItemQtyInStock>13</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>4</ItemID>
                  <ItemName> Item Name : 4</ItemName>
                  <ItemPrice>40</ItemPrice>
                  <ItemQtyInStock>14</ItemQtyInStock>
            </Item>
      </Item>
</Category>

In the above code, we are passing one XML string. This will be
converted into a form of object. Here XMLstring is loaded into
 XmlDocument object and then XmlNodeReader is reading from it.
NowXmlSerialize object is created and we let it know the type of
 object by Cat.GetType(). Now Ser object knows that it has to
convert XML into an object of Category Type. Now ser.Deserialize
(reader) takes XML from reader object and converts into an Object.
Later this object is cast into category. If we add this object
into watch and view, we will find that it has created the class
hierarchy.


			

Client Side Validation with Java Script


Hello Friends today you will learn good thing which is mostly used in Companies by programmers

That’s Use of Java Script with Asp.net For client side validation

For this topic i will Give you Unique Article daily….

Today you learn simple validation with java script

This simple program will guide how to do client side validation of Form in JavaScript.

In this just make a form as follows:

  1. Name : <asp:TextBox ID=”txtName” />
  2. Email : <asp:TextBox ID=”txtEmail” />
  3. Web URL : <asp:TextBox ID=”txtWebUrl” />
  4. Zip : <asp:TextBox ID=”txtZip” />
  5. <asp:Button ID=”btnSubmit” OnClientClick=” return validate()”runat=”server” Text=”Submit” />

Now on the source code of this form in script tag write the following code:

<script language=”javascript” type=”text/javascript”>
function
validate()
{
if(document.getElementById(“<%=txtName.ClientID%>”).value==“”
)
{
alert(“Name Feild can not be blank”
);
document.getElementById(
“<%=txtName.ClientID%>”
).focus();
return false
;
}
if(document.getElementById(“<%=txtEmail.ClientID %>”).value==“”
)
{
alert(
“Email id can not be blank”
);
document.getElementById(“<%=txtEmail.ClientID %>”
).focus();
return false
;
}
var
emailPat = /^(\”.*\”|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById(“<%=txtEmail.ClientID %>”
).value;
var
matchArray = emailid.match(emailPat);
if (matchArray == null
)
{
alert(
“Your email address seems incorrect. Please try again.”
);
document.getElementById(
“<%=txtEmail.ClientID %>”
).focus();
return false
;
}
if(document.getElementById(“<%=txtWebURL.ClientID %>”).value==“”
)
{
alert(
“Web URL can not be blank”
);
document.getElementById(
“<%=txtWebURL.ClientID %>”).value=
http://&#8221;
document.getElementById(“<%=txtWebURL.ClientID %>”
).focus();
return false
;
}
var Url=
“^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$”
var tempURL=document.getElementById(“<%=txtWebURL.ClientID%>”
).value;
var
matchURL=tempURL.match(Url);
if(matchURL==null
)
{
alert(
“Web URL does not look valid”
);
document.getElementById(
“<%=txtWebURL.ClientID %>”
).focus();
return false
;
}
if (document.getElementById(“<%=txtZIP.ClientID%>”).value==“”
)
{
alert(
“Zip Code is not valid”
);
document.getElementById(
“<%=txtZIP.ClientID%>”
).focus();
return false
;
}
var digits=“0123456789”
;
var
temp;
for (var i=0;i<document.getElementById(“<%=txtZIP.ClientID %>”
).value.length;i++)
{
temp=document.getElementById(
“<%=txtZIP.ClientID%>”
).value.substring(i,i+1);
if
(digits.indexOf(temp)==-1)
{
alert(
“Please enter correct zip code”
);
document.getElementById(
“<%=txtZIP.ClientID%>”
).focus();
return false
;
}
}
return true
;
}
</script>

And in code behind file just write the below code.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
btnSubmit.Attributes.Add(
“onclick”, “return validate()”
)
End Sub

Now you will get a form with proper validation.

I hope this is going to help you.

For more example can download sample from these links

1) http://www.aspdotnetfaq.com/Faq/How-to-control-ASP-NET-Validator-Controls-Client-Side-validation-from-JavaScript.aspx

2) http://www.dotnetspider.com/resources/3139-Enable-or-Disable-Asp-validation-control-using.aspx

3) http://www.dotnetfunda.com/articles/article113.aspx

4) http://www.aspsnippets.com/Articles/TextBox-Validation-using-JavaScript.aspx

5) http://articles.sitepoint.com/article/form-validation-client-side

6) http://www.java2s.com/Code/ASP/Validation-by-Control/UseJavascriptandaspvalidationcontroltogetherVBnet.htm

7) http://devcenter.infragistics.com/Articles/ArticleTemplate.Aspx?ArticleID=2183

8) http://www.codetoad.com/javascript/is_valid_email.asp

9) http://www.codedigest.com/Articles/ASPNET/221_Using_JavaScript_Effectively_in_ASPNet_20_–_PART_2.aspx

10) http://dotnetslackers.com/articles/aspnet/javascriptwithaspnetservercontrols.aspx

11) http://articles.techrepublic.com.com/5100-10878_11-5031730.html

12) http://ondotnet.com/pub/a/dotnet/2003/09/15/aspnet.html