Search This Blog

Tuesday, November 8, 2011

About Global.asax in ASP.NET


  • Global.asax is a file in asp.net
  • Global.asax file contains all the application level methods.like
  •       1.Application_Start 2.Application_End 3.Session_Start 4.Session_End etc..
  • Note: When you compile your code for the first time your ASP.NET runtime creates a class corresponding to Global.asax file with the Class name global_asax. This class inherits from HTTP Application class.
  • You can see the automatically created class in the C:\Documents and Settings\User\My Documents\Visual Studio 2008\WebSites\ApplicationName\global.asax file.

Friday, October 28, 2011

Adding new Nodes to XML File in C#

1.Create a Dummy xml file with the name Patients.xml in your solution explorer.
    Ex:
 <Patients>
  <Patient type="IP">
    <VistorNum>134</VistorNum>
    <FName>Maha</FName>
    <LName>Veer</LName>
    <Age>89</Age>
    <Sex>Male</Sex>
  </Patient>
</Patients>
 
2.Create the UI to accept data from users.(Write the below code in .aspx page)
   VisitorNum:<asp:TextBox ID="tbVstrNum" runat="server" ></asp:TextBox><br />
    FName:<asp:TextBox ID="tbFName" runat="server" ></asp:TextBox><br />
    LName:<asp:TextBox ID="tbLName" runat="server" ></asp:TextBox><br />
    Age:<asp:TextBox ID="tbAge" runat="server" ></asp:TextBox><br />
    Sex:<asp:TextBox ID="tbSex" runat="server" ></asp:TextBox><br />
    <asp:Button ID="btnInsertPat" Text="AddPatient" runat="server" 
            onclick="btnInsertPat_Click" />
3.Write the below code in code behind's button click method.
    protected void btnInsertPat_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("Patients.xml"));
        //Create a New patient node.
        XmlNode nPatient=doc.CreateNode(XmlNodeType.Element,"Patient",null);
        //Create visitornUm,FName,LName,Age,Sex nodes and add 
        //it to Patient Node
        XmlElement eVistNum= doc.CreateElement("VistorNum");
        eVistNum.InnerText = tbVstrNum.Text;
        XmlElement eFName = doc.CreateElement("FName");
        eFName.InnerText = tbFName.Text;
        XmlElement eLName = doc.CreateElement("LName");
        eLName.InnerText = tbLName.Text;
        XmlElement eAge = doc.CreateElement("Age");
        eAge.InnerText = tbAge.Text;
        XmlElement eSex = doc.CreateElement("Sex");
        eSex.InnerText = tbSex.Text;
        nPatient.AppendChild(eVistNum);
        nPatient.AppendChild(eFName);
        nPatient.AppendChild(eLName);
        nPatient.AppendChild(eAge);
        nPatient.AppendChild(eSex);
        //Get the Root Patients Node ref.
        XmlNode root=doc.SelectSingleNode("Patients");
        //Add New patient node to root patient node.
        root.AppendChild(nPatient);
        string sPath = Server.MapPath("Patients.xml");
        doc.Save(sPath);
        //elem.AppendChild(
    }
Sign Up for dot net training course 

Friday, September 9, 2011

Opening My Computer Using ASP.NET

Please use the HTML Input File Control for opening all the available Drives. Just Drag and drop the control
on to the .aspx page and check the result by clicking on the Browse Button.

India's #1 .NET Training

Sunday, August 28, 2011

How to Encrypt Connection String

For security reasons we need to encrypt the connection strings.
Encrypting and decrypting the connection string is very easy. Follow the Below steps to encrypt the Connection strings.
Encrypt Connection Strings:
  • Open visual studio command prompt.
  • type the given command  aspnet_regiis -pef  "connectionStrings"  "YourApplicationFullPath where your web.config file is present"  and then press Enter.


Decrypting Connection String:
  • aspnet_regiis -pdf  "connectionStrings" "YourApplicationFullPath where your web.config file is present"  and then press Enter.


Note : You need to use pef or pdf only if your website is created as a file system. If Your website is created as a IIS website then use pe or pd for encrypting or decrypting.

Thursday, August 18, 2011

is and as operators in C#

is Operator:
  • is operator Checks if an object is compatible with a given type 
  • An is expression evaluates to true if the provided expression is non-null, and the provided object     can  be cast to the provided type without causing  an exception to be thrown.
as Operator:
  • The as operator is used to perform conversions between compatible reference types      
  • The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception
Ex:

public class Exam
{
    public string GetSubjectName()
    {
        return "C#";
    }
}
public class UnitTest
{
    public int GetTestNumber()
    {
        return 1;
    }
}

public partial class CSHARPSAMPLES_Keywords : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Exam e1 = new Exam();
    }
    public void Test(object o)
    {
        if (o is UnitTest)
        {
            UnitTest u = o as UnitTest;
            u.GetTestNumber();
        }
        else if (o is Exam)
        {
            Exam e = o as Exam;
            e.GetSubjectName();
        }
    }
}

Ternary Operators in C#

Ternary operators can be use full when we have only one simple if else condition.
Ternary Operator Syntax:

condition ? first_expression : second_expression;
Ex:
public class TernaryEx
{
    public int GetBigNum(int a, int b)
    {
        return a > b ? a : b;
        //in the above syntax if a is greater than b
        //the above expression returns a else it returns b.
    }
}
Note: SignUp for JobGuaranteed Training

Sunday, July 17, 2011

How to show XML Data in the Grid View

  • Create a Page with the Name XMLSample.aspx
  • Write the Below controls in the .aspx source Page.
  • Create an xml file on the desktop with Name Students ( See example xml at the End)
<asp:GridView ID="gvList" runat="server">
        </asp:GridView>
        Path:
        <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
  • Write the Below code in the Code behind file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;


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

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        HttpPostedFile hpf=FileUpload1.PostedFile;
        string fName=FileUpload1.PostedFile.FileName;
        System.Data.DataSet ds = new System.Data.DataSet();
        ds.ReadXml(fName);
        gvList.DataSource = ds.Tables[0];
        gvList.DataBind();
        
        
    }
}

Note : Example Xml file.


<Students>
  <Student>
    <id>1312</id>
    <name>123</name>
    <age>123123</age>
  </Student>
  <Student>
    <id>6</id>
    <name>Ashoke</name>
    <age>23</age>
  </Student>
</Students>

Friday, July 15, 2011

Encrpt and Decrypt Connection String

For Security reasons we need to encrypt the connection strings.

How to Encrypt a connection string:
  • Open visual studio command prompt.
  • Change your command prompt location and should point to your application physical drive
  • Assume your application Name is DataSet and  is present in c:\Documents and Settings\Administrator\My Documents
  • type the below statements and then press enter to encrypt the connection
  • aspnet_regiis -pe "connectionStrings" -app "/DataSet"
How to Decrypt Connection:
  • Type the below command and press enter
  • aspnet_regiis -pd "connectionStrings" -app "/DataSet"
Note : See the below attached screen shot.

Saturday, July 9, 2011

Sealed class

Sealed class

  1. It is complete class
  2. It is allow creating an object
  3. It is also called instance class
  4. Inheritance is not possible for Sealed Class. Means No one can be able to inherit from a Sealed Class but sealed class can inherit from any other class (The Parent Class should not be Sealed Class).
  5. Sealed class can never acts as a Parent Class
  6. Static class is by default sealed class only.

Example for Sealed Class:

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

­­­­public sealed class ToyCalc

{

}

public class AdvancedToyCalc : ToyCalc

{

}

Note 1: The above Code is wrong since a sealed class can never act as a Base or Parent Class.

Note 2: But ToyCalc class can inherit from other classes ex.

Ex: ­­­­public sealed class ToyCalc: Toy

The Toy Class should not be a Static Class or SealedClass.

Abstract Class

Abstract Class:
  • When a class is not providing full functionality it recommended to declare that class as an Abstract class.
  • Method with out body is called an abstract method.
  • Ex: public abstract void GetArea ();
  • When class contain at least one abstract method then that class must be declared as abstract class.
  • All the abstract method must be overridden in the derived class.
  • We cant create object for Abstract class.
Ex :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class AbstractClassSammple : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

Circle c = new Circle ();

c.print();

Response.Write(c.findarea()+" ");

Response.Write("
"
+c.print());

}

}

public abstract class Shape

{

private int x = 10;

private int y = 20;

public int print()

{

return (x + y);

}

public abstract double findarea();

}

public class Circle : Shape

{

private int r = 10;

public override double findarea()

{

double a = 3.14 * r * r;

return (a);

}

}

Wednesday, June 8, 2011

Important JavaScript Methods

The  below JavaScript methods are very much useful while writing JavaScript Code.
Note: Below Questions are Frequently asked in .NET Interviews
1.document.getElementById("ControlID");
2.document.getElementByName("Control Name");

Dom Properties:

the below properties are the freequently used properties while writing JavaScript Code.


z.innerHTML - the text value of z
z.nodeName - the name of z
z.nodeValue - the value of z
z.parentNode - the parent node of z
z.childNodes - the child nodes of z
z.attributes - the attributes nodes of z


Note: z Represents HTMLElement ( ex. Text Box or Radio Button )



Wednesday, May 18, 2011

Why .NET is better than Java

There are couple things we need to understand before comparing Java and .NET.

1.Usually softwares are developed to automate any business and to reduce human intervention.
2.Let us Say Palle Technologies wanted to develop a software for XYZ hospital. Since XYZ hospital wanted to automate the Registration,Admission,Scheduling etc process and they decided to develop a software which makes their daily work faster and increases Revenue.
3.They gave contract of developing an application to PalleTechnologiies and asked to come with feasible choice of softwares and they gave us 6 months time for development for what ever the technology they choose.
4.We analysed the requirement and estimated development and maintainence effort for Both Java and .NET
5. We saw significant notable differences between JAVA and .NET
Note: Assumed Application Life time = 15 years.
 Look at the Estimated Costs Required for creating the application for XYZ company.
Estimation for Java Application :
  Java Total Resources Required for Development (6 months)= 6 resources
  Cost of Each Resource= 6* 20000 INR/Month
 Total Resources Cost During Development=720000 INR
Note: We assumed XYZ company is going to use this software for 15 years
Cost of Maintaining the Application for 1 year =3*20000 INR/Person/Month*12 Months=720000
Cost of Maintaining the Application for 15 years=10800000 INR.
Cost of Softwares and Servers = 60000 INR.
Total Cost=11580000 INR.
Estimation for .NET Application :

 .NET Total Resources Required for Development (6 months)= 5 resources 
  Cost of Each Resource= 5* 20000 INR/Month
 Total Resources Cost During Development=700000 INR
Note: We assumed XYZ company is going to use this software for 15 years
Cost of Maintaining the Application for 1 year with 2 Resources=2*20000 INR/Person/Month*12 Months=480000
Cost of Maintaining the Application for 15 years=7200000 INR. 
Cost of Softwares and Servers = 100000 INR.
Total Cost=8000000 INR.

We found significant difference of almost 30 lakhs of rupees savings to XYZ company if They Choose .NET.

Wednesday, April 6, 2011

AutoEventWireUp

AutoEventWireUp attribute in asp.net is used to call the Page_Load and Page_InIt methods automatically
by setting AutoEventWireUp=true;
By default AutoEventWireup set to true in machine.config and hence at the page level it is set to false
If you set AutoEventWireUp=true at page level then Page_Load and Page_InIt will be executed twice.

Sign up for .Net Training Bangalore

User Control assignment ( Change Button color from User Control Text Box Value)

1.Create User Control with name Enquiry . Drag and drop Text box control on the Enquiry.ascx
    set text box id="tbColorName".
2.Create a property in the Enquiry.ascx.cs as shown below.
   protected void Page_Load(object sender, EventArgs e)
    {

    }
    private string _color;

    public string Color
    {
        get { return _color; }
        set { _color = value; }
    }
3.Create a Page with Name UserControlSample.aspx and do below given activities

  • Drag and drop a button on the aspx page and set id="btnSubmit" Text="Submit"
  • Drag and drop the User Control on to the surface of the aspx page. Set UserControl id="Enquiry1".
4.Write the below code in the UserControlSample.aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        foreach (var c in Enquiry1.Controls)
        {
            Type t=c.GetType();
            if (t.Name=="TextBox")
            {
                Enquiry1.Color = ((TextBox)c).Text;
            }
        }
        btnSubmit.BackColor = System.Drawing.Color.FromName(Enquiry1.Color);
    }
5.Execute the application by pressing F5.

Thursday, March 31, 2011

JavaScript Validations

Default.aspx Page Start
<%@ 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">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Form</title>
<script language="javascript" type="text/javascript">
function fnValidate()
{
//FName Validation.
fnValidateFirstName();
//LName Validation
fnValidateLastName();
//Mobile validation
fnValidateMobileNumber();
//PEmail validation
fnValidatePrimaryEmail();
//SEmail Validation
fnValidateSecondaryEmail();
//Counttry Validation
fnValidateCountries();
}
function fnValidateSecondaryEmail()
{
var semail=document.getElementById("txtsemail").value;
var semailregex=/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
if(!semail.match(semailregex))
{
alert("enter valid emailid");
}
}
function fnValidatePrimaryEmail()
{
var pemailno=document.getElementById("txtPemail").value;
if(pemailno=="")
{
alert("email id is mandatory");
}
var pemailregex=/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
if(!pemailno.match(pemailregex))
{
alert("enter valid emailid");
}
}
function fnValidateMobileNumber()
{
var mobile=document.getElementById("txtMobile").value;
if(mobile=="")
{
alert("Mobile number is mandatory");
}
var mno= /^((\+)?(\d{2}[-]))?(\d{10}){1}?$/;
if(!mobile.match(mno))
{
alert("1.Mobile Number should Have Only Digits .\n2.Mobile Number should contain 10 digits");
return false;
}
else
{
return true;
}
}
function fnValidateLastName()
{
var lname=document.getElementById("txtlname").value;
var alphaExp= /^[a-zA-Z]+$/;
if(!lname.match(alphaExp))
{
alert("Last name should have only alphabets");
return false;
}
else
{
return true;
}
}
function fnValidateFirstName()
{
var fname=document.getElementById("txtfname").value;
if(fname=="")
{
alert("First Name Cannot be Blank.");
return false;
}
else
{
var alphaExp = /^[a-zA-Z]+$/;

if(!fname.match(alphaExp))
{
alert("First Name should contain Only Alphabets.");
return false;
}
return true;
}
}
function fnValidateCountries()
{
var index=document.getElementById("ddlCountry").selectedIndex;
alert(index);
if(index==0)
{
alert("Please Select a Country.");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td width="15%"></td>
<td width="70%">
<table>
<tr>
<td align="right">FirstName:</td>
<td><asp:TextBox ID="txtfname" runat="server" /></td>
<td align="right">Mobile:</td>
<td><asp:TextBox ID="txtMobile" runat="server" /></td>
</tr>
<tr>
<td align="right">LastName:</td>
<td><asp:TextBox ID="txtlname" runat="server" /></td>
<td align="right">Phone:</td>
<td><asp:TextBox Width="10%" ID="tbCountryCode" runat="server" />

<asp:TextBox Width="10%" ID="tbCityCode" runat="server" />

<asp:TextBox Width="29%" ID="tbPhone" runat="server" />
</td>
</tr>
<tr>
<td align="right">PrimaryMail: </td>
<td>
<asp:TextBox ID="txtPemail" runat="server" />
</td>
<td align="right">SecondaryMail:</td>
<td>
<asp:TextBox ID="txtsemail" runat="server" />
</td>
</tr>
<tr>
<td align="right">Address1:</td>
<td>
<asp:TextBox ID="txtaddress1" runat="server" TextMode="MultiLine" rows="5"/>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Country:</td>
<td><asp:DropDownList ID="ddlCountry" runat="server"
width="80%"></asp:DropDownList></td>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClientClick="return fnValidate()" /></td>
</tr>
</table>
</td>
<td width="15%"></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Default.aspx Page End


Default.aspx.cs Page Start

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillCountries();
        }
    }

    private void FillCountries()
    {
        ArrayList alCountries = new ArrayList();
        alCountries.Add("India");
        alCountries.Add("Pakistan");
        alCountries.Add("Srilanka");
        alCountries.Add("Australia");
        ddlCountry.DataSource = alCountries;
        ddlCountry.DataBind();
        ddlCountry.Items.Insert(0, "--Select--");
    }
}


Default.aspx.cs Page End

Thursday, March 17, 2011

What is JavaScript


  • JavaScript is a Scripting language , The JavaScript(js) code will be executed by the JavaScript engine which comes with the Browser ( I.E,Opera,Mozilla etc..)
  • JavaScript is a loosely typed language and is called client side scripting language. Because the js code you have written in the .aspx  pages will be sent back to client browser by the web server (IIS) and the JavaScript code will be executed by Browser hence we call this as Client side Script.
  • The Html and js code sent by IIS to browser will be executed by HTML parser and JavaScript engine which are present in the Browser software ( Browser like IE,Opera, Chrome all are softwares which contains code written in c-language etc..)
  • Note: For .net training institutes in Bangalore you can always visit http://techpalle.com/net-training-in-bangalore.html