</div>
Sharing knowledge in Project, Program, Portfolio Innovation Management (PPIM) and various Technology.
Monday, June 22, 2009
Drag & Drop In Infragistics New Framework
</div>
Tuesday, May 19, 2009
ResizableControlExtender in Ajax
Step 1:
Create Ajax enabled website.
Step 2:
Now go to the solution explorer and add the Ajaxcontroltoolkit.dll in the root directory.
Step 3:
Also add the Ajaxcontroltoolkit.dll in the toolbox to get the control.
Step 4:
Create CSS for HandleCssClass and ResizableCssClass for the control attribute.
<style type="text/css">
.handle
{
width:10px;
height:10px;
background-color:#aaccee;
}
.resizing
{
padding:0px;
border-style:solid;
border-width:1px;
border-color:#aaccee;
cursor:se-resize;
}
</style>
Step 4:
Create one panel with the some paragraph document.
<asp:Panel ID="Panel1" runat="server" Style="width: 300px; height: 200px;">
<asp:Label ID="image1" runat="server" Text="ASP.NET AJAX offers you Resizable Extender Control. ResizableControl is an extender that attaches to any element on a web page and allows the user to resize that control with a handle that attaches to lower-right corner of the control. The resize handle lets the user resize the element as if it were a window.">
</asp:Label>
</asp:Panel>
Step 5:
Create the ResizableControlExtender and link the panel.
<cc1:resizablecontrolextender ID="ResizableControlExtender1"
runat="server" TargetControlID="Panel1" HandleCssClass="handle" ResizableCssClass="resizing" MaximumHeight="400" MaximumWidth="500"
MinimumHeight="100" MinimumWidth="100" HandleOffsetX="5" HandleOffsetY="5" />
Monday, May 18, 2009
calling WCF Service method from javascript
Before starting the code please select the template called Ajax enabled wcf service.
then call the method in the javascript.
ASPX with javascript.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function getValue()
{
AjaxWCF.DoWork(onSucess,onFailure)
}
function onSucess(result)
{
alert(result);
}
function onFailure(result)
{
alert(result);
}
</script>
</head>
<body onload="getValue();">
<form id="form1" runat="server">
<asp:ScriptManager ID="script" runat="server">
<Services>
<asp:ServiceReference Path="~/AjaxWCF.svc" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>
AjaxWCF.svc File
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace Xmlhttp
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AjaxWCF
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public string DoWork()
{
// Add your operation implementation here
return "Hi bala";
}
// Add more operations here and mark them with [OperationContract]
}
}
Access a control on the Content Page from a MasterPage using JavaScript
on the content page. create a text box has given below.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
<asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
</asp:Panel>
</asp:Content>
Now access and control the page text box "txtContent" from the master pages.
<head runat="server">
<title></title>
<script type="text/javascript">
function accessControlContentPage() {
var txtCont = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtContent").ClientID %>');
txtCont.value = "I got populated using Master Page";
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
Thursday, May 14, 2009
Calling Webservice through Ajax with javascript
Aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function OnLookup()
{
var stb = document.getElementById("txt1");
Xmlhttp.call.HelloWorld1(stb.value, OnLookupComplete);
}
function OnLookupComplete(result)
{
var res = document.getElementById("txtHint");
res.innerHTML = "<b>" + result + "</b>";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="script" runat="server">
<Services>
<asp:ServiceReference Path="~/call.asmx" />
</Services>
</asp:ScriptManager>
First Name:<input type="text" id="txt1" onkeyup="OnLookup();">
<span id="txtHint"></span>
</div>
</form>
</body>
</html>
webservice
namespace Xmlhttp
{
///
/// Summary description for call
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class call : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
string value = "1";// HttpContext.Current.Request.QueryString["value"];
Dictionary
if (HttpRuntime.Cache["out"] != null)
{
objDictionary = (Dictionary
if (!objDictionary.ContainsKey(value))
{
objDictionary.Add(value, value + "out");
}
}
else
{
objDictionary.Add(value, value + "out");
}
HttpRuntime.Cache["out"] = objDictionary;
return objDictionary[value];
}
[WebMethod]
public string HelloWorld1(string value)
{
return value;
}
}
}
Accessing webservice from javascript using XML HTTp Activex
XML http is a active X object to enable the browser to sending the request and receiving the response asynchronously.
Example:
Aspx Section
<html>
<head>
<script type="text/javascript">
var xmlHttp=null;
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
try
{// Firefox, Opera 8.0+, Safari, IE7
xmlHttp=new XMLHttpRequest();
}
catch(e)
{// Old IE
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
}
var url = "http://localhost:2735/call.asmx?op=HelloWorld";
//var getValue = document.getElementById("txt1");
//url = url + "&value='" + getValue.value + "'";
xmlHttp.onreadystatechange = output;
xmlHttp.open("GET",url,true);
xmlHttp.send();
function output() {
if (xmlHttp.readyState == 4)
{
xmlHttp.open("POST", "http://localhost:2735/call.asmx/HelloWorld", false);
xmlHttp.send();
document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form><p>Suggestions: <span id="txtHint"></span></p> </body>
</html>
Webservice Section
namespace Xmlhttp
{
///
/// Summary description for call
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class call : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
string value = "1";// HttpContext.Current.Request.QueryString["value"];
Dictionary
if (HttpRuntime.Cache["out"] != null)
{
objDictionary = (Dictionary
if (!objDictionary.ContainsKey(value))
{
objDictionary.Add(value, value + "out");
}
}
else
{
objDictionary.Add(value, value + "out");
}
HttpRuntime.Cache["out"] = objDictionary;
return objDictionary[value];
}
[WebMethod]
public string HelloWorld1(string value)
{
return value;
}
}
}
Wednesday, April 15, 2009
Calling javscript method in different frames.
Create one html page with following frames with frameset.
<frameset cols="30%,70%">
<frame src="testFrame.aspx" name="foody"/>
<frame src="Frame1.aspx" name="goody"/>
</frameset>
step 2:
Create one javascript method in testFrame.aspx, which it has been included in frame 1.
Javascript method.
function getValueFrame1()
{
alert("hi");
}
step 3:
call that javacript method in the second frame of page.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
<script language="javascript">
parent.foody.getValue();
</script>
</body>
</html>
Note:foody is frame name
Monday, April 13, 2009
Showing Intelligence for JavaScript methods in different Files.
Tuesday, March 24, 2009
Generating javascript Id through C# (Instead of using control.clientID)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),string.Empty,string.Format("{0}"), string.Format("var gridUniqueID = '{0}'; ", uwgDailyView.UniqueID))
}
fromdate always less than todate validation using javascript
{
objfromDt="12/01/2008";
objtoDt="11/01/2008";
var arrFrom=objfromDt.value.split('/');
var arrTo=objtoDt.value.split('/');
var strFromMonth=arrFrom[0];
var strFromDate=arrFrom[1];
var strToMonth=arrTo[0];
var strToDt=arrTo[1];
if(parseInt(arrFrom[0])<10)
{
strFromMonth=arrFrom[0].replace('0','');
}
if(parseInt(arrFrom[1])<10)
{
strFromDate=arrFrom[1].replace('0','');
}
if(parseInt(arrTo[0])<10)
{
strToMonth=arrTo[0].replace('0','');
}
if(parseInt(arrTo[1])<10)
{
strToDt=arrTo[1].replace('0','');
}
var mon1 = parseInt(strFromMonth);
var dt1 = parseInt(strFromDate);
var yr1 = parseInt(arrFrom[2]);
var mon2 = parseInt(strToMonth);
var dt2 = parseInt(strToDt);
var yr2 = parseInt(arrTo[2]);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("From date always less than to date");
return false;
}
}
Getting Start week date for the given date
{
var strdate=objDate.split("/");
var yer=strdate[2];
var da=strdate[0];
var mon=strdate[1];
var cdat=new Date(yer,mon,da);
var countDay=cdat.getDay();
if(countDay!="0")
{
cdat.setDate(cdat.getDate()-countDay);
}
return cdat;
}
Finding Eventtop and EventLeft position Using javascript
var y =evnt.clientY + document.body.scrollTop + document.body.parentNode.scrollTop;
var x =evnt.clientX + document.body.scrollLeft + document.body.parentNode.scrollLeft;
You have to apply this top and left position value to style attribute of the control.
Wednesday, March 18, 2009
Dependency Caching Using Oracle 11g
It is nothing but a one of the caching mechanism for interacting with the Database.
If any data changes happen in the database,
it will find out and full out the data only on that time. It wont go every time to
the database. In this am going to explain how to do dependency caching using Oracle
11g.Also this option not avilable earlier version of oracle 11g.
Example:
In oracle11 g, there is a method called OracleDependency using this have to achieve the Oracle dependency caching.
public DataSet GetTechnicianDrpdwnval()
{
try
{
DataSet DSTechSumDrp = new DataSet();
ltdConn = new OracleConnection();
ltdConn.ConnectionString = ltdConnString;
ltdCommand = new OracleCommand("USP_GetTechSumDropdown", ltdConn);
ltdCommand.CommandType = CommandType.StoredProcedure;
ltdCommand.Parameters.Add(new OracleParameter("Drp_Primaryduty", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
ltdCommand.Parameters.Add(new OracleParameter("Drp_TypeOfWork", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
ltdCommand.Parameters.Add(new OracleParameter("Drp_DispatchCenter", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
///////////////////////////////Oracle Dependency Caching////////////////////////////////
objOracleDependency = new OracleDependency(ltdCommand);
ltdCommand.Notification.IsNotifiedOnce = false;
objOracleDependency.OnChange += new OnChangeEventHandler(ObjTechDrpDwnval);
///////////////////////////////End/////////////////////////////////////////////////////
ltdDataAdapter = new OracleDataAdapter(ltdCommand);
ltdDataAdapter.Fill(DSTechSumDrp);
return DSTechSumDrp;
}
catch (Exception)
{
throw;
}
public static void OnDatabaseNotificationForGetTechnicianDrpdwnval(object src, OracleNotificationEventArgs args)
{
// Here we have invalidate our cache object if result set changed in database.
InvalidateCache("WireCenter");
}
public static void InvalidateCache(String CacheName)
{
if (HttpRuntime.Cache[CacheName] != null)
{
HttpRuntime.Cache.Remove(CacheName);
}
}
Thursday, January 8, 2009
Typed Dataset Using Asp.net 3.5
Before starting we will remember in Dotnet frame work 2.0. In this it will create only xsd and class file for that. But it will not create Adapters for retrieving dataset. We should use Sqldataadapter for getting the data. But in Asp.net 3.5 frame work it will create data adapter for that xsd. So we can get the typed dataset via adapter instead of getting from Sqldataadapter. See the step by step explanations with examples.
Step 1:
Create one employee database with table name called “contact” which has created for you. Open that database in server explorer of visual studio 2008. See picture A
Picture A
Step 2:
Create Contact.xsd file through add file option in project file. See picture B
Picture B
Step 3:
Drag and drop contact table in to the contact.xsd screen. After waiting few seconds it will create Contact.xsd file automatically. Now you can see in picture C
Picture C
Step 4
Writing few lines of code assigning this typed data values in gridview. See picture as well as the code to retrieve the typed dataset. Create one aspx page with gridview control. I am going to write the code in page load event for that page.
Example:
protected void Page_Load(object sender, EventArgs e)
{
ContactTableAdapters.ContactTableAdapter Dataadapt = new Dotnetspider.ContactTableAdapters.ContactTableAdapter();
grdlist.DataSource = Dataadapt.GetData();
grdlist.DataBind();
}
Note: ContactTableAdapter class will create automatically. This is the one main difference between frame work 2.0 and framework 3.5. But in 2.0 frame work will not create.
Happy Coding
By
Bala
Note:Images will update soon. Sorry for the inconvenience.
Monday, January 5, 2009
Using Filter Expressions with an SQL Data Source in ASP.NET VB 2008
If you use sqldatasource in your project. we can filter the dataset in c# coding itself.
Example1
If (Session("FiltExp") <> Nothing) Then
SqlDataSource1.FilterExpression = Session("FiltExp").ToString()
End If
Example2
SqlDataSource1.FilterExpression = "city='" & DropDownList1.SelectedValue & "'"
Example3
SqlDataSource1.FilterExpression = "BirthDate > #" + dt + "#"
Session("FiltExp") = "BirthDate > #" + dt + "#"
Hidden Features in C#
var @object = new object();
var @string = "";
var @if = IpsoFacto();
2) Aliased Generics.
using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;
Allows you to ASimpleName,instead of
Dictionary<string, Dictionary<string, List<string>>>;
Use it when you would use the same generic big long complex thing in a lot of places.
Thursday, January 1, 2009
Accessing server side event using Ajax 3.5 with Visual Studio 2008
Accessing server side event using Ajax 3.5 in visual studio 2008.
when we compare with earlier method,This may easy to write the code for developer.
step1 :
Include in your application system.web.extensions 3.5
Step 2:
In the script manager tag EnablePageMethods attribute make it true. it will help you to create method in the pagemethod class. Then only you can access the server event in the client side.
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
Step 3:
We should include the namespace over the server side method.[System.Web.Services.WebMethod].
Earlier we have used [Ajax.Ajaxmethod].
Example
[System.Web.Services.WebMethod]
public static string Message(string one,string two)
{
return one + two;
}
Client side. while calling the server side method. it will create two default methods. if it is succeed it will call OnGetMessageSuccess, and fails it will call OnGetMessageFailure.
Example
function GetCall()
{
PageMethods.Message("122","122",OnGetMessageSuccess, OnGetMessageFailure);
}
function OnGetMessageSuccess(result,userContext,methodName)
{
alert(result);
alert(userContext);
}
function OnGetMessageFailure(error,userContext,methodName)
{
alert(error.get_message());
}
Customizing "Start Page" in Visual Studio 2010
Thursday, October 30, 2008
Windows Workflow Foundation
Workflow is nothing but a Business Process also start with a need end with a fulfilled need.
now lets talk about Business Process.
Business Process.
Business process is a collection of activities.it will describe the start to end activity. The Business process is categrozied in to three types. The types are
1)Management Business process(Ex:Governence and Strategic Management)
2)Operation Business process(Ex:Manufactoring,Supply chain).
3)supporting Business Process(Ex:Accounting Recuriting).
Tuesday, October 14, 2008
Visual studio 2008 has a new style builder dialog
Tuesday, September 23, 2008
Monday, August 11, 2008
Reading and writing file in Table using binary
step 1:
Create table with the folowing column, The columns are content type, filename and filedata. if you want also create some additional columns.
for "filedata" column choose datatype called "image" in the datatype list.
Note:if you choose binary datatype instead of image. unable to insert large data in to the table.
writing file in to the table
step 2:
just convert your data file to binary format, After that do insert in to table.
step 3:
how to run exe file through javascript
<head>
<script language="javascript" type="text/javascript">
function runApp()
{s
var shell = new ActiveXObject("WScript.shell");
shell.run("notepad.exe ", 1, true);
}
</script>
</head>
<body>
<input type="button" name="button1" value="Run Notepad" onClick="runApp()" />
</body>
</html>
Monday, July 7, 2008
Dropdown validation using Javascript
Step 1:
function getcheckdrp()
{
var drp=document.getElementById("drpcheck");
if(drp=='[object]')
{
if(drp.selectedIndex==0)
{
alert("please select state");
return false;
}
}
}
step 2:
<asp:ListItem>----Select State----</asp:ListItem>
<asp:ListItem>Karnataka</asp:ListItem>
<asp:ListItem>Bangalore</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btncheckdrp" runat="server" />
step 3:
protected void Page_Load(object sender, EventArgs e)
{
btncheckdrp.Attributes.Add("onclick", "javascript:return getcheckdrp()");
}
Tuesday, June 24, 2008
How to Register User Controls and Custom Controls in Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="bala" src="~/Controls/Header.ascx" tagName="header"/>
<add tagPrefix="bala" src="~/Controls/Footer.ascx" tagName="footer"/>
<add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
</controls>
</pages>
</system.web>
</configuration>
<strong>Output:</strong>
<html>
<body>
<form id="form1" runat="server">
<bala:header ID="MyHeader" runat="server" />
</form>
</body>
</html>
Monday, June 9, 2008
Accordin Control using Dotnet
</asp:ScriptManager>
<asp:UpdatePanel ID="updatepanel1" runat="Server">
<ContentTemplate>
<table>
<tr>
<td>dsfsd</td>
</tr>
<tr>
<td>
<cc1:Accordion ID="accordin1" runat="server" RequireOpenedPane="false">
<Panes>
<cc1:AccordionPane id="accordinpane1" runat="server">
<Header>
<asp:Label ID="lbltext" runat="server" Text="bala"></asp:Label>
</Header>
<Content>
<asp:Label ID="Label1" runat="server" Text="bala1"></asp:Label>
<cc1:Accordion ID="accordin2" runat="server" RequireOpenedPane="false">
<Panes>
<cc1:AccordionPane ID="test" runat="server">
<header>
<asp:Label ID="lbltest1" runat="server" Text="testsdfsd"></asp:Label>
</header>
<Content>
<asp:Label ID="lbltest" runat="server" Text="test"></asp:Label>
</Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>
</Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
How to select all checkbox when i select header checkbox in datagrid.
function checkall(obj)
{
var check=obj.checked;
var len=document.form1.elements.length;
for(i=0;i<len;i++)
{
if(document.form1.elements.item(i).type=="checkbox")
{
document.form1.elements.item(i).checked=check;
}
}
}
</script>
In .Aspx grid control..
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<input type="checkbox" id="head" onclick="checkall(this)"/>
</HeaderTemplate>
</asp:TemplateColumn>
</Columns>
<Columns>
number validatuion in textbox using Javascript
{
var check=false;
var val=obj.value;
var s=new Array("0","1","2","3","4","5","6","7","8","9");
var len=val.length;
for(i=0;i<len;i++)
{
for(j=0;j<s.length;j++)
{
if(obj.value.charAt(i)==s[j])
{
check=false
break;
}
else
{
check=true
}
}
}
if(check==true)
{
obj.value="";
obj.focus();
alert("Please type valid number");
return false;
}
}
Note:Call using onkey up event in html..
<asp:TextBox ID="txtbox" runat="server" onkeyup="javascript:return typecheck(this)" ></asp:TextBox>
how to search textbox value in dropdownlist Using Javascript
<asp:DropDownList ID="drpt" runat="server">
<asp:ListItem Text="text">ss</asp:ListItem>
<asp:ListItem Text="text">ss1</asp:ListItem>
<asp:ListItem Text="text">ss2</asp:ListItem>
<asp:ListItem Text="text">ss3</asp:ListItem>
<script language="javascript">
function getValue(obj)
{
var d=obj.value;
var dro=document.getElementById("drpt");
var drplen=document.getElementById("drpt").options.length
var i;
for(i=0;i<drplen;i++)
{
if(document.getElementById("drpt").options[i].value==d)
{
document.getElementById("drpt").selectedIndex=i;
}
}
}
</asp:DropDownList>
</script>
Sunday, June 8, 2008
Adding rows in DataGrid
DataRow dr = dtg.NewRow();
dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.65";
dtg.Rows.Add(dr);
DataGrid1.DataSource = dtg;
It will work for windows.
If you use DataGrid in ASP then you will have to keep DataTable in Session:
DataTable dtg = new DataTable();
if (Session["SampleDataTable"]==null)
{
DataColumn dc;
dc = new DataColumn("Item_ID",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Name",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Desc",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Amount",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
}
else {dtg = (DataTable) Session["SampleDataTable"];}
DataRow dr = dtg.NewRow();
dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.35;
dtg.Rows.Add(dr);
DataGrid1.DataSource=dtg;
DataGrid1.PageSize+=1;
DataGrid1.DataBind();
Session["SampleDataTable"]=dtg;
Tuesday, June 3, 2008
Windows Communication Foundation (WCF) features
• Facilitates interoperability through WS-* standards
• WS-Trust. Uses the secure messaging mechanisms of WS-Security
• WS-SecureConversation
• WS-Federation
• WS-SecurityPolicy
• Confidentiality – keeping messages private
• Authentication – verifying claimed identity
• Uses transport-level protocol (like HTTPS); only point-to-point secure
• Uses WS-Security; less efficient but secure from end to end
• SOAP Message Security (OASIS)
Reliable Messaging
• Provides for SOAP messages what TCP provides for IP packets
• Ensures messages are exactly once
• Handles lost messages and duplicates
• End-to-end reliability (vs. transport reliability of TCP)
Queues
• Leverages Microsoft Message Queuing (MSMQ) as a transport
• Enables loosely coupled applications and disconnected operations
Transactions
• Takes advantage of System.Transactions in .NET 2.0
• Supports WS-AtomicTransaction
Compatibility
COM+
• Extend COM+ components as Web services
• Service derived from COM+ interface
COM
• Moniker support (GetObject) for usage of WCF services from COM-based applications
Debugging the wcf Service in client side
step1:
<compilation debug=true>
step2:
<servicedebug includeExceptionDetailInfaults="true"/>
Thursday, May 29, 2008
Syndication on WCF
Restart Http Service using Command prompt
step2: type "net start http"
step3: end
Monday, April 21, 2008
Disable Copy and Paste for greater website security
Removing Xml element in two ways
<?xml version="1.0" encoding="utf-8" ?><bookstore> <books> <book genre="reference"> <title>World Atlas</title> </book> <book genre="reference"> <title>World Atlas</title> </book> </books></bookstore>
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("test.xml"));
XmlElement root = xmldoc.DocumentElement;
root.RemoveChild(root.SelectNodes("books/book"));
root.RemoveChild(root.RemoveChild(root.FirstChild));
Replacing xml attribute in two ways
<?xml version="1.0" encoding="utf-8" ?><bookstore> <books> <book genre="reference"> <title>World Atlas</title> </book> <book genre="reference"> <title>World Atlas</title> </book> </books></bookstore>
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("test.xml"));
XmlElement root = xmldoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("books/book");
////////////////////////////////Replaceing Attribute value using xml///////////////////////////////
foreach (XmlNode xn in nodes)
{
xn.Attributes[0].Value = "NA";
}
////////////////////////////////Replaceing Attribute value using xml///////////////////////////////
foreach (XmlNode xn1 in nodes)
{
XmlNode dd = xn1.SelectSingleNode("@genre");
}
How to get the path for "My Documents" and other system folders?
Sunday, April 20, 2008
JSON
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
1) A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
2) An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Installation for Dotnet
http://sourceforge.net/project/showfiles.php?group_id=205597
An easy way to build connection string.
1) Open a New notepad and save it with "udl" extension, suppose "New.udl".
2) Now you will see that it's icon is changed.
3) Open it, you will find Data Link properties dialog box.
4) For SQl Server connection string select Microsoft OLE DB Provider For SQL Server in Provider Tab.
5) Click button "Next" or select Connection Tab
6) Here you can select all connection details and press button
Test Connection. If it is successful close this dialog box.
7) Now open this file using "Notepad", you will find the connection string. Though it is built for OLE DB
type of connection, you can use for SQL Server connection by removing Provider attribute.
NOTE: If you are using SQL Authentication with password, then check the checkbox Allow Saving Password.
This is necessary so that password appears in connection string.
Thursday, April 17, 2008
Paging In Sqlserver 2005
FROM (SELECT ROW_NUMBER() OVER(ORDER BY person) AS
rownum, person, income FROM Salaries) AS Salaries1
WHERE rownum >= 5 AND rownum <= 9
ORDER BY income
Wednesday, April 16, 2008
How to show Modal and Modeless dialog windows in Javascript
When you show a modal dialog the window remains on top of other windows until the user explicitly closes it.
window.showModalDialog("Test.html","dialogWidth:400px; dialogHeight:225px; status:no; center:yes");
When you show a modeless dialog the window remains on top of other windows, but you can still access the other windows.
window.showModalessDialog("Test.html","dialogWidth:400px; dialogHeight:225px; status:no; center:yes");
How do we get ipaddress or hostaddress using c#
HttpContext.Current.Server.MachineName
HttpContext.Current.Request.ServerVariables["local_addr"]
Changing Connection string dynamically using Application_BeginRequest
"Production" and another server name is "Testing". The below code connection string will change dynamically based on server host information.
Example:
<appsettings>
<add key="production" value="http://www.production.com">
<add key="ProductionconnectionString" value="server=localhost;...." >
<add key="testconnectionString" value="server=localhost;...." >
</appsettings>
Public Application_BeginRequest()
{
bool production=false;
if(Request.URL.Host==ConfiqurationManager.Appsettings("production"))
{
Production=true;
}
}
if(Production==true)
{
context.items.add("connectionStrings",ConfiqurationManager.Appsettings("production"))
}
else
{
context.items.add("connectionStrings",ConfiqurationManager.Appsettings("test"))
}
}
Support Multiple Browser Image control
Example:
<asp:image id="cklogo" runat="server" ImageUrl="Images/ck_logo.jpg" PIE4.0:imageurl="Images/small/ck_logo.jpg">
Thursday, April 10, 2008
Cross Joins Using sqlserver
A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. This is an example of a Transact-SQL cross join:
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors CROSS JOIN publishers
ORDER BY au_lname DESC
The result set contains 184 rows (authors has 23 rows and publishers has 8; 23 multiplied by 8 equals 184).
However, if a WHERE clause is added, the cross join behaves as an inner join. For example, these Transact-SQL queries produce the same result set:
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors CROSS JOIN publishers
WHERE authors.city = publishers.city
ORDER BY au_lname DESC
-- Or
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors INNER JOIN publishers
ON authors.city = publishers.city
ORDER BY au_lname DESC
Accessing server event using Ajax
Install system.web.extension and ajax tools
Install ajax.dll in your system all add in reference of the project.
step:2
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
step:3
Write javascript
<script language="javascript" type="text/javascript">
function Getconfirm()
{
var con=confirm("Are sure want to delete this");
var test;
if(con==false)
{
alert(Bala.Getvalue().value);
}
else
{
alert(Bala.Getvalue1().value);
}
}
</script>
step 4:
in c# page
public partial class Bala : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Bala));
//btnsubmit.Attributes.Add("onclick", "Getconfirm();");
}
[Ajax.AjaxMethod()]
public string Getvalue()
{
return "bala";
}
[Ajax.AjaxMethod()]
public string Getvalue1()
{
return "bala1";
}
}
Monday, April 7, 2008
Check if a date is a valid date in Sql Server 2005
Use the ISDATE() function
The ISDATE() function determines whether the variable or the expression contains a valid date. It returns 1(true) if the input expression is a valid date;
otherwise, it returns 0 (false).
For eg:
DECLARE @dt varchar(10)
SET @dt = '02/21/08'
SELECT ISDATE(@dt)-- Returns 1
DECLARE @dt varchar(10)
SET @dt = '13/21/08'
SELECT ISDATE(@dt)-- Returns 0 as 13 is not a valid month
Reset all control values in .NET Web pages.
private void ResetFields()
{
foreach (Control ctrl in this.Controls)
{if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
if (tb != null)
{ tb.Text = string.Empty;
}
} else
if (ctrl is DropDownList)
{ DropDownList dd = (DropDownList)ctrl;
if (dd != null)
{
dd.SelectedIndex = 0;
}
}
}
How to Show Binary Files in the Browser using ASP.NET and VB.NET
1)Create an asp.net web project. Name the project as ShowBinary
2) Add a file of type (.gif,.jpg,.doc,.xls) to the project
3) Specify a Start page for the application4) Use following code snippet in the form load event handler
Private Sub Page_Load(sender as object, e as System.EventArgs)
Response.ContentType = “Application/pdf” ‘ Specify Content Type
Dim fpath as string = Mappath(“Mypdf.pdf”) ‘ Specify Physical Path of the file
Response.writefile(fpath)
End Sub
ASP.NET 2.0 MultiView Control
<asp:MultiView ID="MultiView1" runat="server" >
<asp:View ID="View1" runat="server">This is one section where you can have a set of controls / contents<asp:View>
<asp:View ID="View2" runat="server">This is another section where you can have a different set of controls / contents<asp:View>
</asp:MultiView>
Now, to show the different tabs based on different events, we just need to set the following code:-
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
}
"goto" Using Dotnet framework 2.0
{
Response.Write("Testing Goto");
goto Testing;
Testing:
Response.Write("Testing Goto in for loop");
}
output
Testing GotoTesting Goto in for loop
COALESCE using Sqlserver
now in new pl/sql version having the COALESCE function,
The magic of function is, it will automatically add "," seprator of employeelist.
///////////////////////////Before COALESCE ///
DECLARE @Emp_UniqueID int,
@EmployeeList varchar(100)
SET @EmployeeList = ''
DECLARE crs_Employees CURSOR
FOR SELECT Emp_UniqueID
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
OPEN crs_Employees
FETCH NEXT FROM crs_Employees INTO @Emp_UniqueID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @EmployeeList = @EmployeeList+CAST(@Emp_UniqueID AS varchar(5))+ ', '
FETCH NEXT FROM crs_Employees INTO @Emp_UniqueID
END
SET @EmployeeList = SUBSTRING(@EmployeeList,1,DATALENGTH(@EmployeeList)-2)
CLOSE crs_Employees
DEALLOCATE crs_Employees
SELECT @EmployeeLis
Output:
1, 2, 4
///////////////////////////After COALESCE/////////////
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList
Output:1,2,4
/////////////////////////////////////////////////////////////////////////////
Anonymous delegate using Dotnet framework 2.0
{
System.Console.Write("hi");
});
Th.Start();
Breaking out a loop in two ways
1) firstway is using "break" keyword
2) Second way is using variable declaration.
//First way
for (int i = 0; i < 5; i++)
{
Response.Write("bala");
break;
}
//Second Way
bool br = false;
for (int j = 0; j < 2&& br == false; j++)
{
Response.Write("testingbala");
br = true;
}
Nullable DataType in Dotnet Framework 2.0
If you dont have the value for nullable datatype, it will return automatically null as a value.
Example 1:
int? var1 = null;
int var2 = 5;
var1 = var2;
if (var1.HasValue == true) //Using HasValue properties will will findout "var1" variable having value or null.
{
Response.Write("bala");
}
else
{
Response.Write("bala1");
}
Output:
bala
Example 2:
float? a = 436;
float? b = null;
if (a.HasValue) Response.Write("testing");
if (b.HasValue) Response.Write("testi"); else Response.Write("test");
Output:
testingtest
Tuesday, March 25, 2008
Calling Javascript in Dotnet based on Button id
<script language="javascript" type="text/javascript">
{
var con=confirm("Are sure want to delete this");
var test;
if(con==false)
{
alert("test");
}
else
{
alert("test1");
}
}
</script>
<asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" />
In C# Page
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(btnsubmit, typeof(string), "bala", "Getconfirm();", true);
}
Note:btnsubmit is control id.
Monday, March 17, 2008
Windows Communication Foundation

WCF is nothing but a Distributed system. Combination of Object Oriented Architechtre and Service Oriented Architecture.
NET 3.0 comes with three main technologies in core: Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation.
Windows Communication Foundation (WCF), codenamed Indigo in Microsoft, is the last generation of service oriented technologies for development. It provides all the latest means to help developers build service oriented applications. The result of service oriented design is a distributed system which runs between services and clients. Windows Communication Foundation is Microsoft infrastructure for Service Oriented architecture
Advantages
Windows Communication Foundation has some important enhancements in comparison with preceding technologies·
. It merges all older separate technologies in one place and allows you to do things easier.
· It has rich communication capabilities.
· It comes with many powerful and ready to use enterprise features.
· It can be integrated with other technologies and has great interoperability.
Windows Communication Foundation consists of three main concepts.
· Services: Programs that respond to clients. They can send or receive messages.
· Clients: Programs that ask for a service. They can send or receive messages.
· Intermediaries: Programs that sit between services and clients (Figure 2). They can work as a firewall or can rout messages. In all cases neither services nor clients need to be aware of intermediaries.
Architecture of Windows Communication Foundation consists of five layers. These layers from top to down are:
· Application: In this level application is located.
· Contracts: In the second layer service, data and message contracts as well as bindings and policies are present. In this level services describe themselves to clients.
· Runtime: Behaviors are located in this layer. Runtime layer loads all services.
· Messaging: Different types of channels as well as encoders are here. This layer enables communications for services.
· Hosting: This layer is where host services in different manners, but there are two common ways to host a service. You can host a service in Internet Information Services (IIS) which is easier than the second approach and starts and stops your services automatically. The second approach is to create executable files (.EXE) for services and start and stop them manually by writing more codes.
Windows Communication Foundation has simple and easy to write/understand codes. It has many APIs, but beside this only a small amount of these API's is common.
There are three programming approaches in Windows Communication Foundation:
· Imperative: You use programming codes in different languages to accomplish a task.
· Configuration Based: You use configuration files to do things.
· Declarative: You use attributes to declare something.
On the other hand, you can use typed services and untyped services. In typed services you pass normal objects and data types and/or get normal objects and data types, but in untyped services you pass and get messages to work directly with messages at a lower level..
Installation
Installation of Windows Communication Foundation and its development tool is easy and consists of these steps:
· Download and install .NET Framework 3.0 RTM. I also strongly recommend you to download and install WinFX SDK as well. After this step you have all necessary API's to run Windows Communication Foundation.
· Download and install Visual Studio 2005xtensions for .NET Framework 3.0 WCF and WPF). After installing this package, you will have new project templates in your Visual Studio to start developing for Windows Communication Foundation
Sunday, March 16, 2008
verbatim literal
Another useful feature of C# strings is the verbatim literal
which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".
Cracking .NET Assemblies
This is nice articale for cracking the .net assemblies
http://www.grimes.demon.co.uk/workshops/fusionWSCrackThree.htm#Cracking_Whidbey_Assemblies
Monday, February 25, 2008
Encrypt and Decrypt configuration files using Code
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.protectsection("Dataprotectionconfigurationprovider");
config.save();
}
How to decrypt connection string in asp.net stored in web.config.
Using System.web.configuration;
Protected void button_click(object sender,eventargs e)
{
string webconfigpath="~";
configuration config=webconfigurationmanager.openwebconfiguration(webconfigpath);
configurationsection configsection=config.Getsection("connectionstrings");
configsection.sectionInformation.Unprotectsection();
config.save();
}
Encryption connectionstring .NET Framework 2.0 using Tool
Configuration File Encryption
In the .NET Framework 2.0, developers will be able to encrypt sensitive parts of the web.config file (if containing password or keys, for instance) using the aspnet_regiis utility. The decryption is done transparently.
The DPAPI protected configuration provider supports machine-level and user-level stores for key storage. The choice of store depends largely on whether or not the application shares state with other applications and whether or not sensitive data must be kept private for each application.
If the application is deployed in the Web farm scenario, developers should use RSAProtectedConfigurationProvider to leverage the ease with which RSA keys can be exported on multiple systems. It uses RSA public key cryptography to provide data confidentiality.
The following example encrypts the connection string section using the tool aspnet_regiis:
try out this...
aspnet_regiis.exe -pef "connectionStrings" C:\VirtualDirectory\Path
URL Mapping in asp.net 2.0
URL Mapping is a mechanism by which you can change the displayed url in address bar.
Example
Step1: Add Mapping URL in web.config file.<system.web>
<urlMappings enabled="true">
<add url="~/Department.aspx" mappedUrl=" oldforms/frmDept.aspx"/>
<add url="~/Employee.aspx" mappedUrl=" oldforms/frmEmployee.aspx"/>
<add url="~/Product.aspx" mappedUrl="& gt;
</urlMappings></system.web>
Step2: Change the URL in .aspx file
<a href="Department.aspx">Department</a><br />
<a href="Product.aspx">Product</a><br />
<a href="Employee.aspx">Employee</a>
Thursday, February 21, 2008
Tips & Tricks for Dotnet
1. Press Ctrl+I.
2. Start typing the text you are searching for. Note: you'll see the cursor jump to the first match, highlighting the current search string.
3. Press Ctrl+I again to jump to the next occurrence of the search string.
4. To stop search, press Esc. Advanced tip: Press Ctrl+Shift+I to search backwards.
2) Make Window Fit any Resolution
Create function definition
<script language="Javascript">
function resolution()
{
UserWidth = window.screen.availWidth
UserHeight = window.screen.availheight
window.resizeTo(UserWidth, UserHeight)
window.moveTo(0,0)
}
</script>
</head>
2) Call the function on load event of body.
<body OnLoad=”resolution();”>
3) Adding a Print Button with Javascript
Add this line to the Page_Load event
btnPrint.Attributes("onClick") ="javascript:window.print();"
*Add a button to the page called 'btnPrint' Technically, that's it, but, let's say you want to do something a little fancier, using DotNet.
Then, add a subroutine (let's call it 'DoPrint'):
Sub doPrint(Source as Object, E as EventArgs)
lblResults.visible="True"
lblResults.text="Page has successfully been sent to the printer!"
End Sub
Then, add a direction to this sub, in the button's tag: onServerclick="doPrint"
4) *To print certain areas of a page
Create a style sheet for printing purpose, normally by removing/hiding background colors, images.... After that include it with media="print",
so that this style sheet will be applied while printing.
<LINK media="print" href="styles/printStyle.css" type="text/css" rel="stylesheet">
5) Fade Effect on Page Exit
<meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(duration=.9)">
6)Disabling a Button Until Processing is Complete
Here's the scenario - let's say you have an Insert subroutine,
called 'doInsert'.
You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times. For this,
use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:
<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert">
Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True"
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);
}





