Tuesday, March 25, 2008

Calling Javascript in Dotnet based on Button id

In aspx Page

<script language="javascript" type="text/javascript">

function Getconfirm()
{
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-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.

Fundamental Concepts

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
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.

Programming Model

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

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

How to encrypt 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.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) Incremental search in Visual Studio.
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

Step 1. Disable Script Debugger - Make this option unchecked in the IE.
function someFunct()
{
Javascript:debugger;alert(window.name)
alert("Mahesh");
}

Tuesday, February 19, 2008

What's new in C# 3.0

1)Implicit typed local variables
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

1) Where is xml used, and where can it be used?

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 State

Session 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

The below method you can convert the dataset in to xmlformat.

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

After create an xmldoument, you might need to access the particular node, xpath enables you

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

XML Document object model(DOM) class is a representation of the xml document in memory,

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

The below code getting the employee details, but connection and command object declared in through using Keyword.one of the advantage of using keyword you no need to close the connection


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

///////////////////////Accessing Id///////////////////////////
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

This one i done for tell a friend, when i click add it should create dynamically one row with all the controls.

////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////////////////////////////////