Sunday, January 30, 2011

Edit code when your ASP.NET Development Server is running

 

Lot of people trying to edit the code when ASP.NET Development Server is running but they can't. In order to edit code you have to stop debugger/ ASP.NET  Development server then you can edit it.

If you want to continue code edit while your are running ASP.NET Development Server try this:

http://localhost:3499/Default.aspx

You do have the option to control which port is used when using the built-in development server.  The steps to specify the port to be used are slightly different depending on whether you are using a website project or a web application project.

ASP.NET Development Server - Web Application project

  1. Right click the Project in the Solution Explorer, and then select “Properties”

  2. Click “Web” tab.

  3. Go to Server section (Make sure Visual Studio Development server is selected)

  4. Check Enable Edit and Continue is turned on

Tuesday, January 25, 2011

Encrypting and Decrypting web.config Information

The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. In this situation to maintain the security to encrypt and decrypt the web.config file.

We can encrypt the configuration sections by using two built-in providers: DPAPI (Windows Data Protection API) Provider or the RSA provider. The RSA provider (default) uses an RSA key which holds public and private keys, where as the DPAPI provider uses built-in machine-specific key. Let us explore the steps required to encrypt the sections using RSA.

There is two method for encryption and decryption of web.config file.One through asp.net command line and second through programmatically.

Method # 1:

 

Encryption

  ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.  

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings>
<add name="MembershipConnectionString" connectionString="connectionString"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
<authentication mode="Forms" />
</system.web>
</configuration>



 

In this method for encrypting and decryption of web.config does not involve any code, instead is based on the command line tool aspnet_regiis.

This command line tool can be found within the %windows%\Microsoft.NET\Framework\versionNumber folder, or can be run directly from the Visual Studio command prompt.

aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication



-pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.

If you are using IIS base web site the command will be,

 aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”



-pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.   

   If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”

Open your web.config file and you can see that connection string is encrypted and its look like this.

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed...GicAlQ==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

<system.web>
<compilation debug="true"/>
<authentication mode="Forms" />
</system.web>
</configuration>



Decryption:


Now to decrypt the configuration section in web.config file use following command,

For File System Application,

aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication



For IIS based Application

aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication”




    If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,

aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication



Method # 2:


Step 1: Open Visual Studio > File > WebSite > Select the language (C# or Visual Basic) and location to create a new ASP.NET website.

Step 2: Now add a web.config file to the project. Right click the project > Add New Item > Web Configuration File

Open the web.config and add the following sample entries in the file between the <configuration> tag as shown below:

<configuration>
<appSettings>
<add key="var1" value="SomeValue"/>
</appSettings>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;" />
</connectionStrings>

<system.web>...

</configuration>



Step 3: Now add two buttons to the page, called btnEncrypt and btnDecrypt. We will use these buttons to encrypt and decrypt the sections of the web.config file. Add the following code in the button click event of the two buttons:

 


C#

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";

protected void btnEncrypt_Click(object sender, EventArgs e)
{
try
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null)
{
confStrSect.SectionInformation.ProtectSection(provider);
confg.Save();
}
// the encrypted section is automatically decrypted!!
Response.Write("Configuration Section " + "<b>" +
WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString + "</b>" + " is automatically decrypted");
}
catch (Exception ex)
{

}
}

protected void btnDecrypt_Click(object sender, EventArgs e)
{
try
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
{
confStrSect.SectionInformation.UnprotectSection();
confg.Save();
}

}
catch (Exception ex)
{

}
}

VB.NET

Private provider As String = "RSAProtectedConfigurationProvider"
Private section As String = "connectionStrings"

Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confStrSect As ConfigurationSection = confg.GetSection(section)
If Not confStrSect Is Nothing Then
confStrSect.SectionInformation.ProtectSection(provider)
confg.Save()
End If
' the encrypted section is automatically decrypted!!
Response.Write("Configuration Section " & "<b>" & WebConfigurationManager.ConnectionStrings("MyConnString").ConnectionString & "</b>" & " is automatically decrypted")
Catch ex As Exception

End Try
End Sub

Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confStrSect As ConfigurationSection = confg.GetSection(section)
If Not confStrSect Is Nothing AndAlso confStrSect.SectionInformation.IsProtected Then
confStrSect.SectionInformation.UnprotectSection()
confg.Save()
End If

Catch ex As Exception

End Try
End Sub

In the code above, we open the web.config file as a System.Configuration.Configuration object using the specified virtual path. We then call the GetSection() to retrieve the specified ConfigurationSection object, in our case connectionStrings. The ConfigurationSection.SectionInformation property gets us the SectionInformation object, and then we finally call the ProtectSection() method on the SectionInformation object to mark the section for protection.

Similarly while decrypting the section, we call the UnprotectSection() method of the SectionInformation object.

Step 4: Now run the application and click on the Encrypt button. Now close the application > Open the web.config file. You will observe that the <connectionString> has been encrypted in the following manner:

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>ZehN7B+VXBdJTe1X3NFz9Uz3NqxvjSMmbytLeHGNlZa4
JkkpRkXzphm5sedHeMTk5KZCHxoYrJ4ssJ0OcZnzLxNUrAB9Ie3y8xJVWJ2s0RQ
dmaGk5bSJADE1xKJBuOtDIOi/Ron7qJDWXwllC3v
vmNwgabmJ9RU+RN35TOQpznc=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>q2amqNwjeyEbMxF5pZ3XqfboNUJKSml773mPkISGi6uWCWCDPs
0ICClmH1eQYcsI9FlxFvEfyRyRRugqOU2xe+gd3aRZEZ5irpGFB45Fn6M+te7kg
OeTK1gjGEsbeaNjBNwgpcXMh9RiA9xVOvWlLAyJ3u8DsDQ+4JmM/zTUtxer/8Dl
UI7+u8D+9V4b5tWxShp4BToMFdTcefhMb19pGdn+jocGet
WBJirO5CJsLXI=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>



Note: If you are running this application from the file system, when you close the application, Visual Studio will display a dialog with the message of "The file has been modified outside the editor. Do you want to reload it?" Click yes and then view the web.config.

Step 5: Run the application again and now click on the Decrypt button. You will observe that the <connectionStrings> section is no longer encrypted and can be read as plain text.

Note: Take a note that 'section groups' like <system.net>, <mailSettings> etc. cannot be encrypted through programmatically .

You can encrypt all the sections of web.config file except following using the method I displayed in this article,

<processModel>
<runtime>
<mscorlib>
<startup>
<system.runtime.remoting>
<configProtectedData>
<satelliteassemblies>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>



   To encrypt these section you needed to use Aspnet_setreg.exe tool.

Monday, January 24, 2011

Clear Session On Browser Close

 

How to capture logoff time when user closes browser?

Or

How to end user session when browser closed?

Or

How to end user session when user redirect to another sites.

These are some of the frequently asked questions normally this is the requirement of any application.There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP.I am explain one of them which is very effective and tested.

 

1. First create a page LogOut.aspx and in Page_Load event write this code:-

protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
}




 


2. Then add following JavaScript code in your page or Master Page:-

<script type="text/javascript"> 
    var clicked = false;
function CheckBrowser()
{
if (clicked == false)
{
//Browser closed
}
else
{
//redirected
clicked = false;
}
}

function bodyUnload()
{
if (clicked == false)//browser is closed
{
var request = GetRequest();

request.open ("GET", "AutoLogOut.aspx", true);
request.send();
}
}

function GetRequest()
{
var request = null;
if (window.XMLHttpRequest)
{
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else
{
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}






3.  Add the following code in the body tag of master page.

<body onunload="bodyUnload();" Onclick="clicked=true;">








Finally the code in Master page like this:-


<script language="javascript" type="text/javascript">
//<![CDATA[

var clicked = false;
function CheckBrowser() {
if (clicked == false) {
//Browser closed
}
else {
//redirected
clicked = false;
}
}

function bodyUnload() {
if (clicked == false)//browser is closed
{
//var request = GetRequest();

//location.href = 'LogOut.aspx';
var request = GetRequest();

request.open("GET", "LogOut.aspx", true);
request.send();
}
}
function GetRequest() {
var request = null;
if (window.XMLHttpRequest) {
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else {
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}



//]]>
</script>

<body onunload="bodyUnload();" onclick="clicked=true;">
<form id="form1" runat="server">






Sunday, January 2, 2011

Textual description of firstImageUrl

Search ListBox items using JavaScript

Technorati Tags: ,,,,
This example shows how to select ListItems in the ListBox based from the TextBox values using JavaScript.
Its only select the first letter in list box control .If you want to filtering check this Filtering Listbox control using Javascript.

Here’s the code block below.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Demo</title>
</head>
<script type="text/javascript" language="javascript">
function SearchList()
{
var l = document.getElementById('<%= ListBox1.ClientID %>');
var tb = document.getElementById('<%= TextBox1.ClientID %>');
if(tb.value == "")
{
ClearSelection(l);
}
else{
for (var i=0; i < l.options.length; i++)
{
if (l.options[i].text.toLowerCase().match(tb.value.toLowerCase()))
{
l.options[i].selected = true;
return false;
}
else
{
ClearSelection(l);
}
}
}
}
function ClearSelection(lb)
{
lb.selectedIndex = -1;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return SearchList();"/><br />
<asp:ListBox ID="ListBox1" runat="server" Height="150px" Width="250px">
<asp:ListItem>Vincent</asp:ListItem>
<asp:ListItem>Jennifer</asp:ListItem>
<asp:ListItem>Shynne</asp:ListItem>
<asp:ListItem>Christian</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Vladi</asp:ListItem>
<asp:ListItem>Bee</asp:ListItem>
<asp:ListItem>Jerome</asp:ListItem>
<asp:ListItem>Vinz</asp:ListItem>
<asp:ListItem>Churchill</asp:ListItem>
<asp:ListItem>Rod</asp:ListItem>
<asp:ListItem>Mark</asp:ListItem>
</asp:ListBox>
</form>
</body>
</html>
The JavaScript function basically searches the ListBox items and find the items based from the value of the TextBox that was entered. If a keyword exist from the list then it will automatically select the ListItems in the ListBox, but if the keyword does not exist then it will clear the ListBox selection.
See the output below when you run it on the page

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...