Wednesday, March 10, 2010

Getting IP Address of PC in ASP.NET

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Below is the method which will return the IP address of the system as a string.
" strHostName " is a variable as you can see below which contains the Host name (PC name) that also you can get.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public string GetNetInfo()
{
try
{
string retVal = string.Empty;
string strHostName = System.Net.Dns.GetHostName();
string strIp = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
return strIp;
}
catch (Exception ex)
{
throw ex;
}
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Enjoy......

Tuesday, February 23, 2010

Reading Contents of a File into a String Variable

We have a file (txt,doc,xml,xslt etc tested) and we wanted to read the content of that file into a string variable.

To do this I have following code section:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
using System.IO;

public string GetContentsOfFile(string URL)
{
if(string.Equals(URL,string.Empty))
throw new ArgumentNullException("URL not given");
StreamReader sr = new StreamReader(URL);
string retStr = string.Empty;
retStr = sr.ReadToEnd();
return retStr;
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=
This method will take URL of file as parameter and return a string with the contents of that file.

Enjoy...

Adding New Node to an Existing XML file

We have an XML file named: TestXML.xml

Structure is as follow:




We wanted to add a new node.

This code block will do the same

public void AddXMLNode(string XMLFilePath,string TitleToAdd, string ArtistToAdd)
{
XmlDocument doc = new XmlDocument();
doc.Load(XMLFilePath);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "CD", null);
XmlNode TitleNode = doc.CreateElement("title");
TitleNode.InnerText = TitleToAdd;
XmlNode ArtistNode = doc.CreateElement("artist");
ArtistNode.InnerText = ArtistToAdd;
node.AppendChild(TitleNode);
node.AppendChild(ArtistNode);
XmlNodeList list = doc.GetElementsByTagName("Catalog");
list[0].AppendChild(node);
doc.Save(XMLFilePath);
}

Now Test This Code:

AddXMLNode(TestXML.xml,”Deewana”,”Sonu Nigam”);

Now the Structure Will Look Like:



Enjoy...

Friday, February 19, 2010

Understanding WITH TIES Option in SQL Server

Table Structure:
=-=-=-=-=-=-=-=-
Book_ID Book_Name Book_Price
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
B001 ABC $10.50
B002 AAA $12.50
B003 BBC $10.50
B004 KCC $16.50
B005 MCC $10.50
B006 DCC $17.50
B007 BBA $13.50
B008 MMC $10.50
B009 BOOK $07.10
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

if you use TOP clause with the SELECT statement it will only gives you the N rows even if there is any record of same value available.

Consider this example:

select top 5 Book_Name,Book_Price from Book order by Book_Price desc

Resule of this query is will be:

Book_Name Book_Price
=-=-=-=-=-=-=-=-=-=-=-=-=-
DCC $17.50
KCC $16.50
BBA $13.50
AAA $12.50
MCC $10.50
=================
But there is also some books with the same price ($10.50). So those records will be ignored by TOP Clause.

But If we think as book seller's mind they also wanted to list the name of those books which comes in that top 5 price range because they have to sell those boks also because those are also coming in TOP 5 price range.

So, to solve this issue we will use WITH TIES Clause.

Consider this Example:

select top 5 with ties Book_Name,Book_Price from Book order by Book_Price desc

Result of this query will be:

Book_Name Book_Price
=-=-=-=-=-=-=-=-=-=-=-=-=-
DCC $17.50
KCC $16.50
BBA $13.50
AAA $12.50
BBC $10.50
MCC $10.50
MMC $10.50
ABC $10.50
=======================

Now we are getting the expected output; here we can see all the book name of top 5 price range.

===============================
Enjoy...   

Wednesday, February 10, 2010

Calling Controller Page Methods using JavaScript in MVC

First Check whether the Browser supports the Ajax or Not.
================

function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
====
Then Write The following Code.
=============
function ConfirmMsg() {
if (confirm("put the confirmation message, clicking cancel of this will not cause a post back")) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "/Folder or ControllerName/MethodName";
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4){
document.getElementById('objDiv').value = xmlHttp.responseText;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return false;
}
}
=====
Enjoy...

Wednesday, February 3, 2010

Creating Hit Counter in ASP.NET WebSite

Create a Website (website1)
Add a Class file and edit like:
==================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

///
/// Summary description for Global
///

public class Global:HttpApplication
{
public static int Users = 0;
public Global()
{
//
// TODO: Add constructor logic here
//
}
}
====================
Add a Global Application Class (Global.asax) file and edit like:
in session_start Event Increment the number of users, means on every session the number of users will be incremented.
====================
void Session_Start(object sender, EventArgs e)
{
Global.Users++;
}
=============================
Then goto your Default.aspx.cs page source and edit like:
=======================
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("No Of Users:"+Global.Users);
}
}

================
Execute this Application First time you will see No of Users: 1
break this application execute next time you will see No of users: 2
and the same will be keep going for next Consecutive page requests.
========
Enjoy...

Monday, January 25, 2010

Exporting GridView Data into Excel in Asp.Net

Add the Folllowing namespace:

using System.IO;

Write the following lines on the click of the Export button.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.Charset = "";
Page.EnableViewState = false;
Response.AddHeader("Content-Disposition", "inline;filename=report.xls");
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
//Here grid1 is the name of the GridView Control.
grid1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}

Enjoy Exporting data from GridView to Excel.

Calling Stored Procedure of Oracle in Asp.Net

Add Reference
System.Data.OracleClient;

After That Add the Following Code.

public void AddEmployee(int EmpId,string EmpName)
{
string strConn = "Data Source=Data Source;User ID=system;Password=pwd;";
OracleConnection con = new OracleConnection();
con.ConnectionString = strConn;
con.Open();
OracleCommand cmd = new OracleCommand();
//CommandText=Procedure Name.
cmd.CommandText = "InsertData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
//ID is the name of Parameter in SP.
cmd.Parameters.Add("ID", OracleType.Number).Value = EmpId;
//NAME is the name of parameter in SP
cmd.Parameters.Add("NAME", OracleType.VarChar).Value = EmpName;
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
throw ex;
}
}


Enjoy....

Using Oracle Connection To List data in Asp.Net

Add the Reference of System.Data.OracleClient.
and then ...
using System.Data.OracleClient;
using System.Data;

public void LoadData()
{
string strConn = "Data Source=Data Source Name;User ID=userId;Password=password;";
using (OracleConnection objConnection = new OracleConnection())
{
objConnection.ConnectionString = strConn;
try
{
objConnection.Open();
OracleCommand objCommand = new OracleCommand();
objCommand.Connection = objConnection;
objCommand.CommandText = "select ID,NAME from Employee";
objCommand.CommandType = System.Data.CommandType.Text;
OracleDataAdapter objAdapter = new OracleDataAdapter(objCommand);
DataTable objTable = new DataTable();
objAdapter.Fill(objTable);
grid1.DataSource = objTable;
grid1.DataBind();
objConnection.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objConnection.Close();
}
}
}

Enjoy....

Wednesday, January 13, 2010

Checking Whether you browser supports XMLHTTP or Not.

function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function CheckBrowser() {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
}

Thursday, January 7, 2010

Validating Date Using JavaScript.

Date Should not be Character.
-------------------------------

function IsChar(sText) {
var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. ";
var IsNumber = true;
var Char;


for (i = 0; i < sText.length && IsNumber == true; i++) { Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1) { IsNumber = false; } } return IsNumber; } Date Should Not Contains Special Characters. ---------------------------------------- function checkSpecialchar(objName) { var checkOK = "!@#$%^&*()_-+|\<>?.";
var checkStr = objName;

var allValid = true;
var allNum = "";
var ch;

for (i = 0; i < checkStr.length; i++) { ch = checkStr.charAt(i); for (j = 0; j < checkOK.length; j++) if (ch == checkOK.charAt(j)) break; if (j == checkOK.length) { allValid = false; break; } //if (ch != ",") //allNum += ch; } if (!allValid) { return (false); } else { return (true); } } Now we Start validating date. Here is the code for that. ------------------------------------------------ var startDate = document.forms[0].txtStartDate.value; var validDate = startDate.indexOf('/'); var fIndex = startDate.charAt(2); var lIndex = startDate.charAt(5); if (fIndex != '/') { alert("Please Use (Slash) /to Enter Date"); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } if (lIndex != '/') { alert("Please Use (Slash) /to Enter Date"); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } if (validDate == -1) { alert("Please Use (Slash) /to Enter Date"); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } else if (CheckSpecialChar(startDate)) { alert("Special Characters are not allowed."); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } else if (IsChar(startDate)) { alert("Date Should be Numeric."); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } else { var txtDate = startDate.split('/'); var day = txtDate[0]; var month = txtDate[1]; var year = txtDate[2]; var dt = new Date(); var curYear = dt.getFullYear(); var curMonth = dt.getMonth() + 1; if (year < curYear) { alert("Year Should be Greater Than or Equal to Current Year."); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } if (year == curYear) { if (month < curMonth) { alert("Month Should be greater than current month."); document.forms[0].txtStartDate.focus(); document.forms[0].txtStartDate.select(); return false; } } if (month > 12) {
alert("Please Enter date in DD/MM/YYYY Format.");
document.forms[0].txtStartDate.focus();
document.forms[0].txtStartDate.select();
return false;
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day > 31) {
alert("Day Should be less than or equal to 31 for the given month.");
document.forms[0].txtStartDate.focus();
document.forms[0].txtStartDate.select();
return false;
}
}
if (month == 2 && (year % 4 == 0 || year % 400 == 0)) {
if (day > 29) {
alert("Leap Year February day should be less than or equal to 29");
document.forms[0].txtStartDate.focus();
document.forms[0].txtStartDate.select();
return false;
}
}
if (month == 2 && (year % 4 != 0 || year % 400 != 0)) {
if (day > 28) {
alert("Not a Leap Year February day should be less than or equal to 28");
document.forms[0].txtStartDate.focus();
document.forms[0].txtStartDate.select();
return false;
}
}

=============================================================
Enjoy....

Validating Email Using JavaScript

=============================================
function isEmail(emailStr) {
var emailPat = /^(.+)@(.+)$/
var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars = "\[^\\s" + specialChars + "\]"
var quotedUser = "(\"[^\"]*\")"
var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom = validChars + '+'
var word = "(" + atom + "|" + quotedUser + ")"
var userPat = new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$")

var matchArray = emailStr.match(emailPat)

if (matchArray == null) {
return false
}

var user = matchArray[1]
var domain = matchArray[2]


if (user.match(userPat) == null) {
return false
}

var IPArray = domain.match(ipDomainPat)

if (IPArray != null) {
for (var i = 1; i <= 4; i++) { if (IPArray[i] > 255) {
return false
}
}
return true
}

var domainArray = domain.match(domainPat)

if (domainArray == null) {
return false
}

var atomPat = new RegExp(atom, "g")
var domArr = domain.match(atomPat)
var len = domArr.length

if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 3) {
return false
}

if (len < 2) {
var errStr = "Email ID is missing a Host Name!"
return false
}

return true;
}
=============================================

Setting Maxlength Of Textarea Using JavaScript

==================================

function SetMaxLength(Object, MaxLen) {
return (Object.value.length < MaxLen);
}
==================================
Here Object is the Id of Textarea and MaxLen is the maximum no of characters allowed.