Sharing knowledge in Project, Program, Portfolio Innovation Management (PPIM) and various Technology.
Thursday, February 21, 2008
Javascript Debugger Enabling
function someFunct()
{
Javascript:debugger;alert(window.name)
alert("Mahesh");
}
Tuesday, February 19, 2008
What's new in C# 3.0
Local variables can be declared as type var, whose actual type of the variable is determined by the compiler based on the data schema (see Listing 1). It's mainly used to store anonymous types in LINQ.
// This is an integer
var nId = 1234567;
//This is a string
var strFullname = "John Charles Olamendy Turruellas";
Sunday, February 17, 2008
XML
Well, that's quite a question, xml is a platform and language independent, which means it doent matter that computer may be using(Solaris, unix, linux), XML is potential fit for exchange format. The following are just few example.
1)Reducing Server load.
2)Web site Content.
3)RPC(Remote procedure call).
4)E-Commerce.
2) Illegal PCDATA Character
They are some reserverd character that you cant include in your PCDATA(Parsed Character Data) because they are used in xml syntax. The below characters are reserved word in xml.
1) &
2) <
3) >
4) '
5) ""
They are two ways you can get around this,
1) Escaping characters.
2)Enclosing tag with CDATA Sections.
1)Escaping Characters.
& -- amp;
<--lt;
2)Enclosing tag with CDATA Sections.
if you have lot of "<" and ">" that you need to cdata.
<test><![cdata[<is<7&7>7]]></test>
Output
<is<7&7>7
Stylee Sheet Using XML
Coming soon....
Wednesday, February 13, 2008
How to use DbProviderFactory and DbConnection
Refer this
http://www.developer.com/net/net/print.php/11087_3530396_2
Example
DbProviderFactory Factory = DbProviderFactories.GetFactory("DDTek.Oracle");DbConnection Conn1 = Factory.CreateConnection();
Conn1.ConnectionString ="Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";
Conn1.Open();// Pool A is created and filled with connections to the //
minimum pool size
DbConnection Conn2 = Factory.CreateConnection();
Conn2.ConnectionString = "Host=Accounting;Port=1521;User ID=Jack;Password=quake; " + "Service Name=ORCL;Min Pool Size=100";
Conn2.Open();// Pool B is created because the connections strings differDbConnection Conn3 = Factory.CreateConnection();
Conn3.ConnectionString = "Host=Accounting;Port=1521;User ID=scott;Password=tiger; " + "Service Name=ORCL;Min Pool Size=50";Conn3.Open();//
Conn3 is assigned an existing connection that was created in // Pool A when the pool was created for Conn1
Friday, February 8, 2008
Statemanagement Using C#.Net
State Management is a process of maintaining the state of the control or variable after page postback from server or between pages. In Asp.Net we are having many ways to maintain the state management. Basically it is dividied into server side and client side state management. Depends on the resource that we have to plan. They are as follows....
1. Session state
2. Hidden Variables
3. Query String
4. Cookies
5. ViewState
6. Caching
Out of which session state and caching are server side state management. others are client side state management.
1. Session StateSession State is responsible for maintaining the state of a variable between pages and page postback. There are two types of session state. They are
a. Application state
b. Session state
An object that is instant in application state will be available to the entire application. The lifetime of that instance will be available as long as application exists. Synatax for it is
Application.lock();
Application["Name"] = "Senthil";
Application.unlock();
string strName = Application["Name"].ToString();
and an instance created in session state will be available for that session (i.e browser).
Session["RoleID"] = "ADMIN";
string strRole = Session["RoleID"].ToString();
Session state can stored in three places
a. InProc - same system
b. StateServer - storing values in other server. Use " net start aspnet_state" for configuring the state server.
c. SQLServer - In database - use "aspnet_regsql" for configuring the sql server.
This can be set in web.config
<configuration> <system.web> <sessionstate mode="InProc" stateserver="129.23.33.53" sqlserver="" cookieless="true" /> </system.web></configuration>
To get more info about state management, set the trace to on
<configuration> <system.web> <trace enable="true" pageoutput="true" />
</system.web>
If pageoutput is set to false, then we find the contents in trace.axd file which is available in the root folder.
2. Hidden variables
Hidden controls are for storing few informations and retrieving it when page gets submits. We cannot get one hidden value in another page. The syntax for hidden variables are as follows.
<input type="hidden" name="hid" value="">
<%=Request.Form("hid")%>
3. QueryString
Easiest way to transfer data between pages is the querystring. But we cannot transfer a bulk of data through it. Basically querystring has two keywords ? and &.
Example
document.frm.action="login.aspx?Name=" & strName & "?Role=ADMIN"
<%= Request.QueryString["Name"] %>
4. Cookies
Cookies are client side and it is used to store few values in the client machine. We cannot create cookies in server side. Many browsers restrict using cookies in the websites. The class that supports cookies in dotnet are HttpCookies.
5. ViewState
ViewState are used to maintain the state of the control. It can be set page wise or control wise. To set it by page wise
<% @ Page EnableviewState="True" %>
For setting viewstate control wise set the viewstate property to true.
The value of the control would be retained once the pages get postback.
6. Caching
Caching too places a part in state management. Its similar to session state but the only difference is we have to set the duration for it.
Caching can be done by page levels or application levels.
Syntax for page level caching[CODE]
<% outputcache duration="10" valuebyParam="none" />[CODE]
Thursday, February 7, 2008
Working with XML and DataSets
1) Getxml Method
The getxml method lets you to convert the dataset to xml.
Example
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("id");
DataColumn dc2 = new DataColumn("firstname");
DataColumn dc3 = new DataColumn("lastname");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
for (int i = 0; i < 3; i++)
{
DataRow dr=dt.NewRow();
dr[0] = i.ToString();
dr[1] = "sdf";
dr[2] = "test";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
string getxmldata = ds.GetXml();
How to access XPathNavigator using XML DOM
access the node or set of nodes in an xml document. xpath treats xml document as a tree
structure.
xpath implementation recognize the several node types in the xml document, such as root, node, element, attribute, comment, white space, significant whitespace, namespace,
Xpath class defined in the system.xml.path, Xpath navigator can access any of the datasource , such as Dataset, database, xml document.
The below code describe , how to acces the xpathnavigator class.
XPathDocument Doc = new XPathDocument("emp.xml");
XPathNavigator navigator = Doc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/employees/employee");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
Console.WriteLine(iterator.Current.Value);
}
Inserting some values in XML DOM
The DOM class lets you read, write , manipulate the xmldocument.
The below examlple for reading and writing xml in file using xmldocument objects.
string getvalueexisting = string.Empty;
string getvaluetag = string.Empty;
string s = string.Empty;
string firstname = txtfirstname.Text;
string lastname = txtlastname.Text;
string address = txtaddress.Text;
string path = Server.MapPath("XMLDATA");
XmlDocument copyexisting = new XmlDocument();
copyexisting.Load(path + "\\test.xml");
XmlTextReader XTR = new XmlTextReader(path + "\\test.xml");
while (XTR.Read())
{
if (XTR.Name != "student")
{
if (XTR.NodeType == XmlNodeType.Element)
{
getvalueexisting += "<" + XTR.Name + ">";
}
if (XTR.NodeType == XmlNodeType.Text)
{
getvalueexisting += XTR.Value;
}
if (XTR.NodeType == XmlNodeType.EndElement)
{
getvalueexisting += "</" + XTR.Name + ">";
}
}
}
XTR.Close();
s = "<student>" + getvalueexisting + "<abc><firstname>" + firstname + "</firstname><lastname>" + lastname + "</lastname><address>" + address + "</address></abc></student>";
xmldoc.LoadXml(s);
xmldoc.Save(path + "\\test.xml");
Displaying images in URL
Create a image which you want to display on the url.
Go to favicon.comThere you have a browse option.Select the image from your local machine
using the browse optionClick submitIt will create a small icon and it will display on the page.
Right click and save as "favicon.ico"
Give the exact file name as favicon.ico.Normally it opens in paint.
Now paste that image in your website root directory and on your masterpagewithin <head></head> tags copy and paste the below given link tag:
<link rel="shortcut icon" href="favicon.ico" />
Thats it! You can view it on the url!
Wednesday, February 6, 2008
Using Keyword advantage in framework 2.0
using (SqlConnection myconn = new SqlConnection(connstring))
{
using (SqlCommand mycomm = new SqlCommand("select * from employee", myconn))
{
mycomm.CommandType = CommandType.StoredProcedure;
myconn.Open(); /////Here u opened the connection but no close
SqlDataReader myread;
myread = mycomm.ExecuteReader();
dt.Load(myread);
}
}
Note
This above code work only in C#
Accesing Parent Window through Childwindow using Javascript
alert(window.opener.document.getElementById("HidString").value)
///////////////////////End Accessing Id///////////////////////////
///////////////////////Accessing Function///////////////////////////
child.aspx
window.opener.LoadEmp(obj)
parent.aspx
function LoadEmp(ob)
{
alert(ob);
}
///////////////////////End Accessing Function///////////////////////////
///////////////////////Refershing Parent Page from Child page////////////
Response.Write("<script language='javascript'>
window.opener.location.href=opener.location.href;</script>");
Using Javascript creating control without postback
////Note dont delete the id of table (i am using that in javascript)////////
<table cellspacing="0" cellpadding="0" width="100%" border="0" id="Tellafriend1">
<tr>
<td colspan="3" align="right"><input type="button" value="Addmore" onclick="fnAddRow()" /> <input type="button" value="DeleteRow" onclick="fnDelRow()" /></td>
</tr>
<tr>
<td colSpan="3"><br /></TD>
</tr>
<tr>
<td>
Friend Name</td>
<td>
Email Id</td>
<td>
Delete</td>
</tr>
<tr>
<td>
<input type="text" id="txtfriendname1" name="txtfriendname1" /></td>
<td>
<input type="text" id="txtfriendemail1" name="txtfriendemail1" /></td>
<td>
<input type="checkbox" disabled="true" id="chkdelete" name="chkdelete" />
</td>
</tr>
</table>
/////////////////////////////////Javascript///////////////////////////
///////////////////This is for adding row/////////////////////////////
var rowcount=1;
var checkcount=1;
function fnAddRow()
{
rowcount++;
// var check=validate(); //this is for my page validation
if(check!=false)
{
var objTbl = document.getElementById("Tellafriend1");
var objTbody = objTbl.getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
//txtfriendname///
var friendnameval=document.createElement("td");
var friendnameDel = document.createElement("INPUT")
friendnameDel.setAttribute("type","text");
friendnameDel.setAttribute("name","txtfriendname"+rowcount);
friendnameDel.setAttribute("id","txtfriendname"+rowcount);
friendnameval.appendChild(friendnameDel)
row.appendChild(friendnameval);
//txtfriendname///
//txtfriendemail///
var friendemailval=document.createElement("td");
var friendemailDel = document.createElement("INPUT")
friendemailDel.setAttribute("type","text");
friendemailDel.setAttribute("name","txtfriendemail"+rowcount);
friendemailDel.setAttribute("id","txtfriendemail"+rowcount);
friendemailval.appendChild(friendemailDel)
row.appendChild(friendemailval);
//txtfriendemail///
//checkbox///
var checkval=document.createElement("td");
var ChkDel = document.createElement("INPUT")
ChkDel.setAttribute("type","checkbox");
ChkDel.setAttribute("name","chkDelete"+rowcount);
ChkDel.setAttribute("id","chkDelete"+rowcount);
checkval.appendChild(ChkDel)
row.appendChild(checkval);
//End check box checkbox///
objTbody.appendChild(row);
}
else
{
return false;
}
}
///////////////////End adding row/////////////////////////////
Note:For deleting i am using checkbox...................
///////////////Deleting Row//////////////////////////////////
function fnDelRow()
{
var ChkOption = ""
for(var i=2;i<=rowcount;i++)
{
var ChkCtrl = document.getElementById("chkDelete"+i)
if(ChkCtrl == '[object]')
{
if(ChkCtrl.checked)
{
ChkOption = "1"
delRow(ChkCtrl)
checkcount++;
}
}
}
if(ChkOption == "" && rowcount!=1)
{
alert("Select any one option to delete")
return false;
}
}
function delRow(button)
{
var row = button.parentNode.parentNode;
var tbody = document.getElementById('Tellafriend1').getElementsByTagName('tbody')[0];
tbody.removeChild(row);
}
/////////////////////////////End Deleting row////////////////////////////////
Reading and removing Listbox using Javascript
var listEmp=document.getElementById("PMEmpname");
for(j=0;j<listEmp.options.length;j++)
{
listEmp.options[j].value //Value field
listEmp.options[j].text //Text Field
}
///////////Deleting///////////////////////////////////
for(j=0;j<listEmp.options.length;j++)
{
listEmp.remove(j);
}
Friday, January 18, 2008
SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005
SqlCacheDependency using Asp.net 2.0 and sqlserver 2005 is a beautiful thing :) Although getting SqlCacheDependency to work with SQL Server 2000 have to add some additional step.
Now we will go with Asp.net 2.0 with sqlserver 2005
Enable Service Broker
Before SqlCacheDependency will work with SQL Server 2005, you first have to enable Service Broker, which is reponsible for the notification services that let the web cache know a change has been made to the underlying database and that the item in the cache must be removed.
ALTER DATABASE Store SET ENABLE_BROKER;
GO
--SqlCacheDependency.Start() in Global.asax
In ASP.NET, you need to run SqlCacheDependency.Start(connectionString) in the Global.asax:
Example:
void Application_Start(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
SqlDependency.Start(connectionString);
}
SqlCacheDependency in ASP.NET 2.0 Example
Now you can just create your SqlCacheDependency as normal in your ASP.NET 2.0 page. Here is a simple example:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable categories = (DataTable)Cache.Get("Categories");
if (categories == null)
{
categories = GetCategories();
Label1.Text = System.DateTime.Now.ToString();
}
GridView1.DataSource = categories.DefaultView;
GridView1.DataBind();
}
private DataTable GetCategories()
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
DataTable categories = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID,Code,Title
FROM dbo.Categories", connection);
SqlCacheDependency dependency =
new SqlCacheDependency(command);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
categories = dataset.Tables[0];
Cache.Insert("Categories", categories, dependency);
}
return categories;
}
}
Wednesday, January 16, 2008
Scrapping using C#.Net
using System.io;
WebRequest request = WebRequest.Create("http://localhost:4733/strings.aspx");
WebResponse response = request.GetResponse();
Stream s=response.GetResponseStream();
StreamReader sr = new StreamReader(s);
string line = sr.ReadLine();
while ((line=sr.ReadLine()) !=null)
{
Response.Write(line);
}
Datatable Load option in Dotnet Framework 2.0
Definition
Using datatable.load you can load the sqldatareader value directly
Example
DataTable dt = new DataTable();
string connectionstring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection myconn = new SqlConnection(connectionstring);
SqlCommand mycomm = new SqlCommand("select * from FA_contactdetails", myconn);
myconn.Open();
SqlDataReader sqldataread = mycomm.ExecuteReader();
dt.Load(sqldataread);////
myconn.Close();
dggrid.DataSource = dt;
dggrid.DataBind();
Thursday, January 10, 2008
.NET BEST PRACTICES
# Use Master Pages for common content across pages.
# Use the “@” prefix for string literals instead of using escaped strings.
# Avoid Empty Catch-blocks# In the .NET framework 2.0: use the New AppendDataBoundItems property in ListControls.
# Close DataReaders and Connections as soon as possible.
# All important graphics should have tool tip and alternate text.
# Use Typed Datasets wherever possible and required.
# Use Validators / Validator Groups for validation.
# Include exception handling in the Application_Error event of global.asax file for unhandled exceptions – implement a Global.asax error handler.
# Choose the most appropriate data type. It is advisable to stop using the “image” data type in SQL Server for any fresh development. Microsoft is planning to phase it out in future versions of SQL Server. You should use the “varbinary(max)” data type instead.
.NET Security Tips
# Keep “Persist Security Info” as false in the connection string.
# Remove the authentication cookie in Session_End event or application specific logout event.
# Security decisions should not rely only on client-side validations – they should be verified on the server side too!
# Hashed password format should be specified in provider configuration.
# The website should be partitioned into public access areas and restricted areas that require authentication access. Navigation between these areas should not flow sensitive credentials information.
# Protect your website against Cross-Site Scripting or XSS attacks
# Dynamic queries that accept user input should be used only if stored procedures cannot be used. Even these queries should use parameters.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.
# Set mode attribute in customErrors to On to prevent displaying detailed error messages to the caller.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.
Performance Boosting .NET coding tips
# Instantiate Objects only if really needed { will NOT use up memory unnecessarily }
# Prefer using String.Empty instead of "" for string initialisation
# Prefer using StringBuilder for dynamic creation of Strings.
# Avoid String datatype while using Switch Case programming-construct
# Use Server.Transfer() instead of Response.Redirect() method.
# Avoid use of Page.DataBind() method
# Define the four most frequently used local variables as the first four variables.
# Even inside vb.net OR c# code, Avoid using the “select * from table” syntax.
# Use proper column case in queries.dr[“ProductName”] vs dr[“PRODUCTNAME”]
# Use Page.IsPostBack to minimize redundant processing in page load.
# Avoid server round trips (by using client scripts, validator controls, html controls, caching techniques (for pages, user controls and objects)).
# Disable view state on a control-level / page-level if you do not need it.DataGrid with ViewState disabled is 66% faster than DataGrid with ViewState enabled.
# Minimize the number of objects you store in view state.
# Use a DataReader for fast and efficient data binding.
# Prefer to Use try/finally on disposable resources.
# Minimize calls to DataBinder.Eval
Moving Listitem from left Listbox to right Listbox
{
ArrayList arrfirst = new ArrayList();
foreach (ListItem lstfirstitem in lstfirst.Items)
{
if (lstfirstitem.Selected == true)
{
arrfirst.Add(lstfirstitem);
}
}
for (int i = 0; i < arrfirst.Count; i++)
{
ListItem tst = (ListItem)arrfirst[i];
if (lstsecond.Items.Contains(tst) == false)
{ lstsecond.Items.Add(tst);
lstfirst.Items.Remove(tst);
}
}
}
protected void btnmoveleft_Click(object sender, EventArgs e)
{
lstfirst.SelectionMode = ListSelectionMode.Multiple;
lstfirst.Attributes.Add("SelectionMode", "Multiple");
ArrayList arrsecond= new ArrayList();
foreach (ListItem lstseconditem in lstsecond.Items)
{ if (lstseconditem.Selected == true)
{ arrsecond.Add(lstseconditem); }
} for (int i = 0; i < arrsecond.Count; i++)
{ ListItem tst = (ListItem)arrsecond[i];
if (lstfirst.Items.Contains(tst) == false)
{ lstfirst.Items.Add(tst);
lstsecond.Items.Remove(tst);
}
}
lstfirst.SelectedItem.Selected = false;
lstfirst.SelectionMode = ListSelectionMode.Single;
}