Monday 5 March 2012

SQL Connection



Connected Procedure : -

SqlConnection con = new SqlConnection("Pass the Connection String here");

SqlCommand com = new SqlCommand("select * from table3", con);

con.Open();

SqlDataReader dr = com.ExecuteReader();

GridView1.DataSource = dr;

GridView1.DataBind();

con.Close();

How to Send a Mail in Asp Dot Net



public partial class mailer : System.Web.UI.Page
{
MailMessage mailmsg;
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["admin"] == null)
{
Response.Redirect("index.aspx");
}
//if (Request.QueryString["id"] != null)
//{
//    txtToAddress.Text = Request.QueryString["id"];
//}
if(!IsPostBack)
{
String user = Session["admin"].ToString();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["name"].ConnectionString);
con.Open();
cmd = new SqlCommand("select email from registration where username='" + user + "'",con );
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
txtFromAddress.Text = dr.GetString(0);
}
dr.Close();
}
}
protected void btnSendmail_Click(object sender, ImageClickEventArgs e)
{
try
{
String to = txtToAddress.Text;
String from = txtFromAddress.Text;
String cc = txtCCAddress.Text;
String bcc = txtBCC.Text;
String subject = txtSubject.Text;
String body = txtMessage.Text;
mailmsg = new MailMessage();
mailmsg.From =new MailAddress( from );
mailmsg.To.Add ( new MailAddress(to));
if ((cc != null) && (cc != string.Empty))
{
mailmsg.CC.Add(new MailAddress(cc));
}
if ((bcc != null) && (bcc != string.Empty))
{
mailmsg.Bcc.Add(new MailAddress(bcc));
}
mailmsg.Subject = subject;
mailmsg.Body = body;
if (fileAttachment.HasFile)
{
mailmsg.Attachments.Add(new Attachment(fileAttachment.PostedFile.FileName));
}
// Set the format of the mail message body as HTML
mailmsg.IsBodyHtml = true;
// Set the priority of the mail message to normal
mailmsg.Priority = MailPriority.Normal;
SmtpClient smtpclient = new SmtpClient();
smtpclient.Host = ConfigurationManager.AppSettings["hostname"];
smtpclient.Send(mailmsg);
}
catch (Exception ex)
{
lblmsg.Text = "Your mail has been sent..";
}
}
}



File Handling In Asp Dot Net : Insert Into File


Protected Void InsertIntoFile()

{

if (TextBox1.Text != "" && TextBox2.Text != "" && TextBox3.Text != "" && TextBox4.Text != "")

{

FileStream fs = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Append, FileAccess.Write);

StreamWriter sw = new StreamWriter(fs);

sw.WriteLine(TextBox1.Text);

sw.WriteLine(TextBox2.Text);

sw.WriteLine(TextBox3.Text);

sw.WriteLine(TextBox4.Text);

sw.WriteLine();

sw.Flush();

sw.Close();

fs.Close();

}

else Response.Write("Please fill all the fields.");

total = 0;

FileStream fs1 = new FileStream(Server.MapPath("Temp/temp.txt"), FileMode.Open, FileAccess.Read);

StreamReader sr = new StreamReader(fs1);

while (!sr.EndOfStream)

{

for (int i = 0; i < 5; i++)

{

sr.ReadLine();

}

total++;

}

}


Use of File upload Control in Asp Dot Net


protected void Page_Load(object sender, EventArgs e)

{

        Image1.Visible = false;

}

protected void Button_Upload_Click(object sender, EventArgs e)

{

        String str = "Pass the path wher you want to save the uploaded file

                           (For example : D:\\Visual studio\\Website\\FileUpload\\

                           Images\\)" + FileUpload1.FileName;

        FileUpload1.SaveAs(str);

        Image1.ImageUrl = "~//Images//" + FileUpload1.FileName;

        Image1.Visible = true;

}


How to get IP address by Hostname from Domain name Server in C#

This code is in c# to retrieve IP address corresponding to any hostname from Domain name server

string hostname = http://www.dotnetspider.com/;

IPAddress[] addresslist = Dns.GetHostAddresses(hostname);

foreach (IPAddress theaddress in addresslist)

{

Response.Write(theaddress.ToString());

Response.Write("NewLine");

}

in the second response we have a line brake. age is not visible so i am placing "NewLine" there.

don't forget to use

using System.Net;

Auto Complete Extender In Asp Dot Net


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
  TargetControlID="TextBox1" ServiceMethod="GetCompletionList"
  ServicePath="AjaxLearning.asmx" MinimumPrefixLength="1"
  ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>
Using Service File Method : (.asmx)
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
SqlConnection conn = new                    SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT Username FROM Table_Login WHERE Username LIKE '" + prefixText + "%'", conn);
com.CommandType = CommandType.Text;
conn.Open();
SqlDataReader reader = com.ExecuteReader();
List<string> strarr = new List<string>();
while (reader.Read())
{
strarr.Add(reader.GetString(0));
}
conn.Close();
return strarr.ToArray();
}
Using Handler : (.ashx)
public class AutocompleteData : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string firstname = context.Request.QueryString["q"];
string sql = "select top 10 Username from Table_Login where Username like '" + firstname + "%'";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
context.Response.Write(reader.GetString(0) + Environment.NewLine);
}
}
}
}
public bool IsReusable {
get {
return false;
}
}
}


How To Use Image Map Control In Dot Net


ImageMap.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageMap.aspx.cs" Inherits="ImageMap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>asp.net ImageMap: how to use</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">ImageMap</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Medium"
ForeColor="DodgerBlue"
>
</asp:Label>
<br />
<asp:ImageMap
ID="ImageMap1"
runat="server"
ImageUrl="~/Images/Doll.gif"
HotSpotMode="PostBack"
OnClick="ImageMap1_Click"
>
<asp:RectangleHotSpot
Top="0"
Bottom="360"
Left="0"
Right="180"
AlternateText="Green Doll"
PostBackValue="Green Doll"
/>
<asp:RectangleHotSpot
Top="0"
Bottom="360"
Left="181"
Right="360"
AlternateText="Pink Doll"
PostBackValue="Pink Doll"
/>
</asp:ImageMap>
</div>
</form>
</body>
</html>



ImageMap.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class ImageMap : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label1.Text = "Click any doll!";
ImageMap1.BorderWidth = 3;
ImageMap1.BorderStyle = BorderStyle.Double;
ImageMap1.BorderColor = System.Drawing.Color.Crimson;
}
}

protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
Label1.Text = "You ckecked: " + e.PostBackValue;
}
}


How to Compress the File using Dot Net Application

we are going to discuss about how to compress the file using asp.net application , ie: for compression there are some third party tools like CSharpZip (not sue about the name of the tools..) ,gzip, etc..
Asp.net has inbuilt with Compression ie: derive from the Class
using System.IO.Compression;
There are two compression derived from this namespace.
1) Gzipstream
2) Deflate stream
Deflate seems to be must faster than the Gzipstream but Deflate doesn't uncompress other formats , but Gzipstream decompress the other files like winzip, winrar .
Now we are going to see Gzipstream it has a class which contains filename and compression mode , Compression mode has two values Compress and Decompress.
Button_ClickEvent
CompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"),;
Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"));
Here you have to give two parameter first one is Sourcefilename to be compressed , second is path where you have to place the compressed file. it will check if the file exists the compressed file has been placed there, else it will create on the fly.
Method definition
public static void CompressFile(string sourceFileName, string destinationFileName)
    {
 
 FileStream outStream;
 
 FileStream inStream;
 
 //Check if the source file exist.          
 
 if (File.Exists(sourceFileName))
    {
 
 //Read teh input file
 
 //Check if the destination file exist else create once
 outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);
 
 GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress);
 
 //Now create a byte array to hold the contents of the file
 
 byte[] fileContents = new byte[inStream.Length];
 
 //Read the contents to this byte array
 
 inStream.Read(fileContents, 0, fileContents.Length);
 
 zipStream.Write(fileContents, 0, fileContents.Length);
 
 //Now close all the streams.
 
 zipStream.Close();
 
 inStream.Close();
 
 outStream.Close();
 
    }
 
    }

How To Decompress File Using Dot Net Application

In previous post we seen how to compress the file this will helpful when the file is large you can
compress the file.

Now we will see how to Decompress the file
Button_Click event.
DecompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"));

Here i just swap the filename so it may confuse so use some different path(Folder) or filename

Decompress Method

    public static void DecompressFile(string        
    sourceFileName, string destinationFileName)
    {
    FileStream outStream;
    FileStream inStream;
    //Check if the source file exist.          
    if (File.Exists(sourceFileName))
      {
    //Read teh input file
    inStream = File.OpenRead(sourceFileName);
    //Check if the destination file exist else create once
    outStream = File.Open(destinationFileName, 
    FileMode.OpenOrCreate);
    //Now create a byte array to hold the contents of the 
    file
    //Now increase the filecontent size more since the 
    compressed file
    //size will always be less then the actuak file.
    byte[] fileContents = new byte[(inStream.Length * 
    100)];
    //Read the file and decompress
    GZipStream zipStream = new GZipStream(inStream, 
    CompressionMode.Decompress, false);
    //Read the contents to this byte array
    int totalBytesRead = zipStream.Read(fileContents, 0, 
    fileContents.Length);
    outStream.Write(fileContents, 0, totalBytesRead);
    //Now close all the streams.
    zipStream.Close();
    inStream.Close();
    outStream.Close();
        }
    }

Sunday 4 March 2012

Introduction Of Asp Dot Net

  
Active Server Pages .NET (ASP.NET) is the infrastructure built inside the .NET  Frame work for running Web applications. As a programmer, you interact with it using appropriate types in the class libraries to write programs and design web forms . When a client request a page, the ASP.NET service runs (inside CLR), executes your code and creates a final HTML page to send to the client.         
The ASP.NET infrastructure consists of two main parts:
  1. A set of classes and interfaces that enables communication between browser and Web     server. These classes are organized in the System. Web namespace of the FCL.
            2. A runtime host that handles the Web request for ASP.NET resources. The ASP.NET runtime host (also known as the ASP.NET worker process) loads the CLR into a process, creates the application domains within the process, and then loads and executes the requested code within the application domains.
         ASP.NET is a powerful and flexible server-side technology for creating dynamic Web pages.
      Salient features :
Ø  ASP stands for Active Server Pages and it is a server side technology.
Ø  ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services.
Ø  Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface.
Ø  ASP.NET is the next generation ASP but it's not an upgraded version of ASP.
Ø  ASP.NET is a Microsoft Technology
Ø  ASP stands for Active Server Pages
Ø  ASP.NET is a program that runs inside IIS
Ø  IIS (Internet Information Services) is Microsoft's Internet server
Ø  IIS comes as a free component with Windows servers
Ø  IIS is also a part of Windows 2000 and XP Professional
Ø  Like ASP, ASP.NET is a server-side technology
     ASP Object Model:-
Ø ASP itself is not Object-Oriented. ASP can use objects but cannot define new objects
Ø Composed of
n     5 objects
n     ASP Objects:-
Ø  Request
Ø  Response
Ø  Server
Ø  Application
Ø  Session
     ASP.NET 3.5 Extensions:-
Ø ASP.NET MVC Framework
n  Model View Controller framework for ASP.NET ( now in Beta )
Ø ASP.NET Dynamic Data
n  Dynamic data controls for displaying/editing table data in ASP.NET
Ø ASP.NET AJAX
n  Browser history support
Ø ADO.NET Data Services
n  Create REST addressable services endpoints for your data and consume with AJAX and Silver light
Ø Silver light Controls for ASP.NET
Ø Integrate Silver light into ASP.NET applications
         Advantages of ASP.NET:-
1.  Use services provided by the .NET Framework
                  The .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services, data access, or even debugging. We will go into more detail on some of them in this module.
2.       Graphical Development Environment
                  Visual Studio .NET provides a very rich development environment for Web developers. You can drag and drop controls and set properties the way you do in Visual Basic 6. And you have full IntelliSense support, not only for your code, but also for HTML and XML.
3.  State management
To refer to the problems mentioned before, ASP.NET provides solutions for session and application state management. State information can, for example, be kept in memory or stored in a database. It can be shared across Web farms, and state information can be recovered, even if the server fails or the connection breaks down.
4.  Update files while the server is running
Components of your application can be updated while the server is online and clients are connected. The Framework will use the new files as soon as they are copied to the application. Removed or old files that are still in use are kept in memory until the clients have finished.
5.  XML-Based Configuration Files
                        Configuration settings in ASP.NET are stored in XML files that you can easily read and edit. You can also easily copy these to another server, along with the other files that comprise your application.
6.  Enhanced Application Development Model
ASP.NET supports the rapid     application development (RAD) and object oriented programming (OOP) techniques that were traditionally available only to desktop applications. Two significant improvements in ASP.NET bring the development of Web applications closer to desktop applications:
1.   ASP.NET allows you to work with HTML elements as objects .Using properties,          methods, and events associated with these objects greatly simplifies the programming model.
2.   What distinguishes a Web application most from a desktop application is that Web is stateless because of the inherent nature of HTTP protocol. To simplify the programming model , .NET automatically maintains the state of a page and the controls on that page during the page-processing life cycle.
7.  Rich Class Library Support
                        In your ASP.NET programs, you have access to all the classes of FCL. You can use these classes to accomplish complex tasks. For example, ADO.NET classes that belong to the System . Data namespace allow you to access data from different sources, whereas the classes in the System . Web . Services namespace allow you to create XML based Web services.
8.     Performance
                        All ASP.NET pages are compiled before they are executed. Overall  performance of compiled code is much better than the interpreted code. In addition to    this, ASP.NET supports caching that allows ASP.NET to reuse the compiled version if no changes were made to the source file since the last compilation. Caching further increases the performance of ASP.NET by saving the time involved in the repeated compilation of a page.
9.     Scalability
                        ASP.NET supports running the Web applications in a Web garden and Web farm scenario. In a Web garden, processing work is distributed among several processors of a multiprocessor computer. In a Web farm scenario, processing work is distributed among several computers making up the Web farm. Web gardens and Web farms allow you to scale your Web application by adding more processing power as the number of hits on the Web site increases.
10.   Security
                        As part of the .NET Framework, ASP.NET has access to all the built-in security features of the .NET Framework, such as code access security and role-based user access security. ASP.NET also offers various authentication modes for Web applications. In addition to Windows-based authentication, ASP.NET has two new modes of authentication—forms-based and Passport authentication.
11.  Manageability
                        ASP.NET configuration files are stored as XML files. Applying new  settings to a Web application is as simple as just copying the configuration files to, the server . Most of the configuration changes do not even require a server restart.
         Microsoft Intermediate Language(MSIL):-
                        When the code is compiled, the compiler translates your code into Microsoft intermediate language (MSIL). The common language runtime includes a JIT compiler for converting this MSIL then to native code.
                        MSIL contains metadata that is the key to cross language interoperability. Since this metadata is standardized across all .NET languages, a program written in one language can understand the metadata and execute code, written in a different language. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.
—  .NET languages are not compiled to machine code.  They are compiled to an Intermediate Language (IL).
—  CLR accepts the IL code and recompiles it to machine code.  The recompilation is just-in-time (JIT) meaning it is done as soon as a function or subroutine is called.
—  The JIT code stays in memory for subsequent calls.  In cases where there is not enough memory it is discarded thus making JIT process interpretive.
Compilers that are compliant with the CLR generate code that is targeted for the runtime, as opposed to specific CPU. This code, known variously as Microsoft Intermediate Language(MSIL), is an assembler-type language  that is packaged in EXE or DLL file. These are not standard executable files and require that the runtime’s Just-in-Time compiler convert IL in them to machine specific code when an application actually runs. Because the common language runtime is responsible for managing this IL, the code is known as Managed code.