Sharing knowledge in Project, Program, Portfolio Innovation Management (PPIM) and various Technology.
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);
}