January 30, 2011

AJAX in ASP.NET using UpdatePanel/ScriptManager


Fetch Data From Database in AJAX Way (Without Post Back)Using AJAX Extensions in ASP.NET

I have a student table in DB with columns Student_id,FirstName,LastName
On form I have a Student DropdownList and Displaytext is Firstname
On page load I am fetching this data from Database
When There is change in student selection ,It should get the Corresponding Record From DB and Display  in GridView in Asynchronous way (AJAX)

 Below is the code
AJAXAssignment2.aspx

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    
    </div>
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlStudent"  />
        </Triggers>
        <ContentTemplate >
          
            <asp:GridView ID="gvStudent" runat="server">
            </asp:GridView>
        </ContentTemplate>
           
        </asp:UpdatePanel>
         <asp:DropDownList id="ddlStudent" AutoPostBack=true  runat="server"  OnSelectedIndexChanged="ddlStudent_SelectedIndexChanged" >
            </asp:DropDownList>
    </form>
</body>
</html>



AJAXAssignment2.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;

public partial class AJAXAssignment2 : System.Web.UI.Page
{
      SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
            connObj.Open();
            ds = new DataSet();
            objCommand = new SqlCommand("Select * from student", connObj);
            objAdapter = new SqlDataAdapter(objCommand);
            objAdapter.Fill(ds);
            connObj.Close();

            ddlStudent.DataSource = ds.Tables[0];
            ddlStudent.DataTextField = "FirstName";
            ddlStudent.DataValueField = "Student_ID";
            ddlStudent.DataBind();
        }
    }
    protected void ddlStudent_SelectedIndexChanged(object sender, EventArgs e)
    {



        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();
        ds = new DataSet();
        objCommand = new SqlCommand("Select * from student where Student_id=" + ddlStudent.SelectedValue, connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();
       
        gvStudent.DataSource = ds.Tables[0];
        gvStudent.DataBind();
    }
}



Below is the DotNetTrainingConnectionString Defined in the web.config



 <connectionStrings>
    <add name="DotNetTrainingConnectionString" connectionString="Data Source=tanvi\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>


Below is my output based on Different Selections



January 28, 2011

AJAX with DATABASE

Use AJAX to Fetch the Data From Database in AJAX Way (Without Post Back)

I have a student table in DB with columns Student_id,FirstName,LastName
On form I have a Student DropdownList and Displaytext is Firstname
On page load I am fetching this data from Database
When There is change in student selection ,It should get the Corresponding Record From DB in
Asynchronous way (AJAX) Below is the code


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

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

<html>
<head>
<script type="text/javascript">
function showStudent(str)
{
alert(str);
var xmlhttp;    
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","EXAJAXSERVER_DB.aspx?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form action="" runat="server"> 

    <asp:DropDownList ID="ddlStudent" runat="server" onChange="showStudent(this.value)">
    </asp:DropDownList>

</form>
<br />
<div id="txtHint">Studnet info will be listed here...</div>
</body>
</html>

EXAJAXDATABASE .aspx.cs
//Contain Code to Fill the Student DropDown List

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;

public partial class EXAJAXDATABASE : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds;
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();
        ds = new DataSet();
        objCommand = new SqlCommand("Select * from student", connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();


      
        ddlStudent.DataSource = ds.Tables[0];
        ddlStudent.DataTextField = "FirstName";
        ddlStudent.DataValueField = "Student_ID";
        ddlStudent.DataBind();


    }
}



//Server Side code to fetch the data based on Student Selection from Dropdown
EXAJAXSERVER_DB .aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;

public partial class EXAJAXSERVER_DB : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds;
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        int id= int.Parse (Request.QueryString["q"].ToString ());
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();
        ds = new DataSet();
        objCommand = new SqlCommand("Select * from student where Student_id=" + id, connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();

       Response .Write ("<table>");
        for(int i=0;i<ds.Tables [0].Columns .Count ;i++)
        {
            
            Response.Write("<tr><td><b>" + ds.Tables[0].Rows[0][i].ToString () +"</b></td>");
             //Response.Write("<td>" & x.value & "</td></tr>");
        }
          Response .Write("</table>");

    }
}



Below is the DotNetTrainingConnectionString Defined in the web.config

 <connectionStrings>
    <add name="DotNetTrainingConnectionString" connectionString="Data Source=tanvi\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>



Below will be the output based on diff Selection




January 23, 2011

Custom Composite Control

I want to create the login control as composite control in asp.net so it can be used between
multiple applications.

Below are the steps to create custom control in ASP.NET

1) Start Visual Studio and Select template a Webcontrol Library or ASP.NET server control project, and give it a name, for example,
CustomLoginControl.

2) Add a source file to the project, for example, LoginServerControl.cs.

3) Include the reference of the System.Web namespace in the references section.

4) Check whether the following namespaces are included in the LoginServerControl.cs file.

System
System.Collections
System.ComponentModel
System.Data
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls

5) Add Properties /Methods /Events

6) Compile the project. It will generate the DLL output(in Project's Debug/bin folder ).

8) Open an existing or create a new ASP.NET Web application project.

9) Add a Web Forms page where the custom control can be used.

10) Add a reference to the class library in the references section of the ASP.NET project.

11) Register the custom control on the Web Forms page.

<% @ Register TagPrefix = "CC" Namespace = CustomLoginControl Assembly = CustomLoginControls" % >



12) To instantiate or use the custom control on the Web Forms page, add the following line of code in the
"FORM" tags.
CC:LoginServerControl id="ctlSimpleControl" runat="server"


13) Run the Web Forms page, and you will see the output from the custom control.


Below is the code

In CustomLogin Web Control Library

WebCustomControl1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomLogin
{
[DefaultEvent ("Click")]
[Category("Appearance")]
public class WebCustomControl1 : System.Web.UI.WebControls.WebControl ,INamingContainer
{
TextBox txtUserName = new TextBox();
RequiredFieldValidator rvUserName = new RequiredFieldValidator();
TextBox txtPassword = new TextBox();
RequiredFieldValidator rvPassword = new RequiredFieldValidator();
Button butLogin= new Button();
Label lblResult = new Label();

//private string text;

//Declare the event.
public event EventHandler Click ;


protected override void CreateChildControls()
{
// Add the sub controls to this composite control.
// Set the TextMode property and add textbox.
txtUserName.TextMode = TextBoxMode.SingleLine;
txtUserName.ID = "UserName";
Controls.Add(txtUserName);

rvUserName.ControlToValidate = txtUserName.ID;
rvUserName.ForeColor = System.Drawing.Color.Red;
rvUserName.SetFocusOnError = true;
rvUserName.ErrorMessage = "* Required";
Controls.Add(rvUserName);


// Start a new line
Controls.Add(new LiteralControl("
"));

txtPassword.TextMode = TextBoxMode.Password;
txtPassword.ID = "Password";
Controls.Add(txtPassword);


rvPassword.ControlToValidate = txtPassword.ID;
rvPassword.ForeColor = System.Drawing.Color.Red;
rvPassword.SetFocusOnError = true;
rvPassword.ErrorMessage = "* Required";
Controls.Add(rvPassword);




// Start a new line
Controls.Add(new LiteralControl("
"));
// Set the Text property and add the Button control.
butLogin.Text = "Login";
Controls.Add(butLogin);
// Add Label and Literals to display result.
Controls.Add(new LiteralControl("&nbsp&nbspResult:&nbsp"));
Controls.Add(lblResult);
Controls.Add(new LiteralControl(""));

// Add event handler.
butLogin.Click += new EventHandler(butLoginClicked);

}


protected virtual void OnClick(EventArgs e)
{
// Raise the event.
Click(this, e);
}

void butLoginClicked(object sender, EventArgs e)
{
// Call the event method.
// System.Web.HttpContext.Current.Response.Write("button was clicked");
AutheticateUser();//Authentication logic of the Application
OnClick(EventArgs.Empty);
}

public void AutheticateUser()//Just a trial Logic
{
if (txtUserName.Text == "Admin" && txtPassword.Text == "Admin")
{
lblResult.Text = "Successful Login";

}
else
{
lblResult.Text = "Username Password Combination doesn't match";

}

}
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}

set
{
ViewState["Text"] = value;
}
}
}
}


Use the above control in WebApp on defaul.aspx
Add the following RegisterDirective

<%@ Register Assembly="CustomLogin" Namespace="CustomLogin" TagPrefix="CC" %>

Place The control in between "form" Tag
CC:WebCustomControl1 runat="server" ID="loginControl" OnClick="loginControl_Click" OnDisposed="loginControl_Disposed"

defaul.aspx.cs

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;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void loginControl_Click(object sender, EventArgs e)
{


Response.Write("Login clicked");
}
protected void loginControl_Disposed(object sender, EventArgs e)
{

}
}

January 17, 2011

Logging in ASP.NET Using Nlogger

Implementing NLog

1.)Download From  
  •  http://nlog-project.org/download.html 
  •  Download the …setup.exe file and execute it, it will also integrate itself into an existing installation of Visual Studio (2005 – 2010 including the free Express Editions!). 


2.) To Log Using  Nlog.NET, just right click on your project, choose “Add New Item”. Select the “Typical NLog Configuration File” from “MyTemplates” . This will write the log entries to a text file.



This will now add a new NLog.config file to your project and at the same time also add a reference to theLNog.dll .
This default config file is enough to write log entries. 



First, make sure that you change the “Copy to Output Directory” to “Copy always” in the File properties of the new config file. Otherwise this file won’t show up when you build your project. 
This will have  sections.
  1.  Targets 
  2.  Rules.

Targets defines where to write and how the log entry should look like (it can be a file, Database, event etc.) and how to write 

The Rules define what level of information to log and what target(s) shall be used. 

Both can be customized and configured. 
We can write multiple targets and multiples rules for different situations etc.

Sample log entry

Include Namspace

using NLog;


Object Creation


NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();



Sample Logging

Sample Logging on PageLoad with Different Error Levels
protected void Page_Load(object sender, EventArgs e)
    {
        logger.Info("Test Logging");
        logger.Warn("Test Logging");
        logger.Fatal("TestLoggin {0}", "In Default");
        logger.Log(LogLevel.Error, "Test Log");
    }



If we now run our project it will write a new log entry into the log.txt in the directory defined by the Target tag which is now "basedir" (Application Root  Folder)



January 14, 2011

JPEG Images not showing in IE

If you are not able to view images in IE which are working in other browsers.
Change the mode of Image from CMYK to RGB Using Adobe Photoshop or Coreldrawl

January 12, 2011

FTP Automated file upload

Code To generate files
1.)ftpcmds.txt ('ll contain the information of username password and File to be uploaded)
2.)FTPScript.cmd('ll Contain the command to upload the file on the specified server)



public void GenerateFiles()
{
// create a writer and open the file
System.IO.StreamWriter file =
new System.IO.StreamWriter(Application .StartupPath+"/ftpcmds.txt");

// write a line of text to the file
file.WriteLine("UserName");
file.WriteLine("Password");
file.WriteLine("type binary");
file.WriteLine("cd Test");
file.WriteLine("put C:\\Test\\Test.doc");
file.WriteLine("bye");


// close the stream
file.Close();


// create a writer and open the file
System.IO.StreamWriter filecmd =
new System.IO.StreamWriter(Application.StartupPath + "/FTPScript.cmd");

// write a line of text to the file
filecmd.WriteLine(@"FTP -s: PathFor ftpcmds.txt file FTPServerIP");


// close the stream
filecmd.Close();

}

The above will generate these two files.
Now below code will run the command from FTPScript.cmd


private void Upload_File(object sender, EventArgs e)
{
try

{
GenerateFiles();
string path = Application.StartupPath + "/FTPScript.cmd";


var procStartInfo = new ProcessStartInfo(path, "")
{

CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};

var proc = new Process { StartInfo = procStartInfo };
proc.Start();
//proc.StandardInput.WriteLine(password);
//proc.WaitForExit(3500);
proc.StandardInput.Flush();

// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();

}

catch (System.ComponentModel.Win32Exception)
{
// logger.Error("Error is occuring at the process start while decrypting the file");
// MessageBox.Show("");
}

catch (System.IO.IOException)
{
// logger.Error("The write operation could not be performed");
// MessageBox.Show("The write operation could not be performed.");

}

January 5, 2011

Required Field Validator on Lost Focus

One of my students asked this question

I have 2 validation controls for the Name field. Required Field Validator and Regular Expression Validator.
If I don't enter any Name and move to the next field , the required field Validator doesn't give the error message.
If I enter wrong values,
Regular Expression Validator gives the error message. Then if I empty the name field and move to the next field , then Required Field Validator gives the error message.

My question is why the
Required Field Validator doesn't give the error message the first time I go to the next field without entering the values ...

Answer
The ASP.NET validation doesn't fire validation when press tab unless a textual change was made. You still get validation when the user clicks the button. It will find all the blank textboxes that are required and will validate them.


So If you want to fire the requiredfieldvalidation for
TextBox1
on onBlur() ,write
below code in pageload event of the webform
TextBox1.Attributes.Add("onblur", "ValidatorOnChange(event);");

It will validate the
TextBox1
on tab out ..