Encrypted querystring in ASP.NET

11 07 2008

Encrypted Querystring

Hello friends When we are passing data between two asp.net pages we will use querystring. But the original value will be displayed there which is not a secure way to do. So we must encrypt that information.

I faced the same situation and searched GOOGLE and come across a nice article by Mr.Tiberius OsBurn of DEVCITY. The original article you can get at: http://www.devcity.net/PrintArticle.aspx?ArticleID=47.

Basically I am C# guy. I made some changes to that program and its working fine now.

First we will write a class file where Encrypt and Decrypt functions will be there.By using them we will execute that.

1) Create a class file in APP_CODE folder and paste this code.

Code Begins

using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Security.Cryptography;

public class Encryption64
{
private byte[] key = { };
private byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };

public string Decrypt(string stringToDecrypt, string sEncryptionKey)
{
byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
try
{

//key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8));
key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.ToCharArray(), 0, 8);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

public string Encrypt(string stringToEncrypt, string SEncryptionKey)
{

try
{
key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey.ToCharArray(), 0, 8);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

}

Code Ends

Take an aspx page and write the code and write the code below.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;

public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
public string encryptQueryString(string strQueryString)
{
//ExtractAndSerialize.Encryption64 oES =
//    new ExtractAndSerialize.Encryption64();
Encryption64 oES = new Encryption64();
return oES.Encrypt(strQueryString, “!#$a54?3″);
}

public string decryptQueryString(string strQueryString)
{

Encryption64 oES = new Encryption64();
return oES.Decrypt(strQueryString, “!#$a54?3″);
}

protected void lnk_btn_Click(object sender, EventArgs e)
{
string strValues = “search”;
string strURL = “http://yoursite.com?search=”
+ encryptQueryString(strValues);

Response.Redirect(strURL);
}
}

In aspx

Take a link button with Id=”lnk_btn”.

when you click it will encrypt an you can decrypt by using the class file.

Bye





Clearing all the textboxes after submitting the data

11 06 2008

Hello friends,

While we are doing some big entry screens after submitting we will erase all the content in textboxes.For that we will do erasing each and every textbox.

It will takes a lot of time . To Reduce the difficulty use the simple code below:

Control myForm = Page.FindControl(”Form1″);

foreach (Control ctl in myForm.Controls)

{

if (ctl.GetType().ToString().Equals(”System.Web.UI.WebControls.TextBox”))

(TextBox)ctl).Text = “”;

}





Displaying total in Footer of Gridview

9 05 2008

If you want to display the Total in the footer of a gridview. Follow the steps:

1) Create a table of employees with salary.

2) Select ename,esalary from emptbl

ename esalary

Bharath 18000

krishna 20000

3) Now in gridview the total of salary must come in footer.

4) .aspx code

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” BackColor=”#DEBA84″
BorderColor=”#DEBA84″ BorderStyle=”None” BorderWidth=”1px” CellPadding=”3″ CellSpacing=”2″
DataSourceID=”SqlDataSource1″ OnRowDataBound=”GridView1_RowDataBound” ShowFooter=”true”>
<FooterStyle BackColor=”#F7DFB5″ ForeColor=”#8C4510″ />
<Columns>
<asp:BoundField DataField=”ename” HeaderText=”ename” SortExpression=”ename” />
<asp:TemplateField HeaderText=”esalary” SortExpression=”esalary”>

<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Bind(”esalary”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>

<asp:Label ID=”Label2″ runat=”server” ></asp:Label>

</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor=”#FFF7E7″ ForeColor=”#8C4510″ />
<SelectedRowStyle BackColor=”#738A9C” Font-Bold=”True” ForeColor=”White” />
<PagerStyle ForeColor=”#8C4510″ HorizontalAlign=”Center” />
<HeaderStyle BackColor=”#A55129″ Font-Bold=”True” ForeColor=”White” />
</asp:GridView>

</div>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:TestConnectionString %>”
SelectCommand=”SELECT [ename], [esalary] FROM [emptbl]“></asp:SqlDataSource>
</form>
</body>
</html>


5) Code behind:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{

private int Total = 0;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

//DataBinder.Eval method Evaluates data-binding expressions at run time.

int Tot=(int)DataBinder.Eval(e.Row.DataItem,”esalary”);
Total = Total + Tot;
}

if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbltotal = e.Row.FindControl(”Label2″) as Label;
lbltotal.Text = Total.ToString();
}
}
}

Any doubts mail me.





Code Snippets in visual studio 2005 - ASP.NET

10 04 2008

Hello friends I want to share something on “Code Snippets” with you.

Code Snippet

Q: What is a “Code Snippet”?

A: A Code Snippet is a reusable block of code. Unlike a static copy-and-paste approach, code snippets allow for dynamic instances of code

by allowing placeholders into mini templates of code. Code snippets are a new feature of Visual Studio 2005.

Q: How do I use a Code Snippet?

A: In the Visual Studio 2005 code editor, you can invoke snippets with [ctrl][k][x] keyboard shortcut. IntelliSense will then display a

context menu displaying the available code snippets to choose. However, most code snippets are available without using the keyboard

shorcut. If you know the shortcut name of the code snippet, simply type the name and press tab to invoke.

Now we will see how we can use snippets here.
I will write a small snippet for disconneceted data access with dataset.

1) Open nottepad.
2) Type the code in it and save it as sample.snippet.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<CodeSnippet Format=”1.0.0″>
<Header>
<Title>Disconnected Data architecture</Title>
<Shortcut>Dataset</Shortcut>
<Description>Code snippet for Disconnected data access</Description>
<Author>Bharath Radhekrishna</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language=”csharp”><![CDATA[dataset
SqlConnection cn = new SqlConnection();
string selquery = $selquery$;
SqlDataAdapter da = new SqlDataAdapter(selquery, cn);
DataSet ds = new DataSet();
da.Fill(ds);
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


3) After saving this. Go to visual studio 2005. Click Tools > CodeSnippets manager or ctrl+K, ctrl+B.
and add this snippet to library.

4) While you are coding right click the mouse. You will see an option of “insert snippet”. when you click it will tell us
to insert the snippet we like. For example if take the above snippet it will be displayed with the name as:
“Disconnected Data architecture”.If we click it will display the code as:

SqlConnection cn = new SqlConnection();
string selquery = ;
SqlDataAdapter da = new SqlDataAdapter(selquery, cn);
DataSet ds = new DataSet();
da.Fill(ds);

So everytime it is not necessary for us to write whole sentence or connections.It will reduce our burden of writing commonly used
code everytime.

For more info on Code snippets you can refer to:

http://gotcodesnippets.com/faq.aspx
http://www.google.com/search?q=how+to+insert+a+code+snippet+in+visual+web+developer+2005&sourceid=navclient-ff&ie=UTF-8&rlz=
1B3GGGL_enIN246IN246.

Screens

Codesnippet while right clicking mouse





javascript with response.redirect

29 03 2008

Q) I had been trying to use javacript to alert some message and after that I do a response.redirect to another page.

But the alert message seems not appearing and it just redirect to another page.

A) use the below code.here we use location.replace

Location.replace

Syntax:
location.replace(URL)

The replace method replaces the current History entry with the specified URL. After calling the replace method, you cannot navigate back to the previous URL using the browser’s Back button.

Usage

string s = “alert(’Your Profile Is Successfully Updated’);location.replace(’Client_home.aspx’);”;
Page.ClientScript.RegisterStartupScript(this.GetType(), “sri”, s, true);

Blogged with Flock





Links for Content Management system in ASP.NET

25 03 2008

Open source

http://www.dotnetnuke.com/
http://www.rainbowportal.net/
http://drupal.org/


http://aspalliance.com/simplecms/default.aspxhttp://www.codeplex.com/SampleCMS

http://www.codeplex.com/umbraco/Release/ProjectReleases.aspx?ReleaseId=6344

http://www.davidpirek.com/CMS/


http://graffiticms.com/
http://www.kentico.com/
http://www.axcms.net/en_axcms_home.AxCMS?ActiveID=1848

Blogged with Flock

Tags:





validate textbox with only numbers using Javascript code

10 03 2008

We can validate textbox with only numbers by writing this Javascript code and calling at onkeypress event of text box

<!–
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //–>

   <asp:TextBox ID=”txt_maxage” Onkeypress=”return isNumberKey(event)” runat=”server”></asp:TextBox>

Blogged with Flock

Tags:





Play music when mouse hovers on a link in ASP.NET

10 03 2008

Javascript code
============

Write this in .aspx page.

<script language=”JavaScript”><!–
// Sound on Mouseover javascript supplied by http://www.hypergurl.com

var aySound = new Array();
// PLACE YOUR SOUND FILES BELOW
aySound[0] = “sound002.wav”;
aySound[1] = “sound003.wav”;
aySound[2] = “sound004.wav”;
aySound[3] = “sound005.wav”;
aySound[4] = “sound006.wav”;
aySound[5] = “sound007.wav”;
aySound[6] = “sound008.wav”;
aySound[7] = “sound009.wav”;
aySound[8] = “sound010.wav”;
// Don’t alter anything below this line

IE = (navigator.appVersion.indexOf(”MSIE”)!=-1 && document.all)? 1:0;
NS = (navigator.appName==”Netscape” && navigator.plugins["LiveAudio"])? 1:0;
ver4 = IE||NS? 1:0;
onload=auPreload;

function auPreload() {
if (!ver4) return;
if (NS) auEmb = new Layer(0,window);
else {
Str = “<DIV ID=’auEmb’ STYLE=’position:absolute;’></DIV>”;
document.body.insertAdjacentHTML(”BeforeEnd”,Str);
}
var Str = ”;
for (i=0;i<aySound.length;i++)
Str += “<EMBED SRC=’”+aySound[i]+”‘ AUTOSTART=’FALSE’  LOOP=’TRUE’ HIDDEN=’TRUE’>”
if (IE) auEmb.innerHTML = Str;
else {
auEmb.document.open();
auEmb.document.write(Str);
auEmb.document.close();
}
auCon = IE? document.all.soundfiles:auEmb;
auCon.control = auCtrl;
}
function auCtrl(whSound,play) {
if (IE) this.src = play? aySound[whSound]:”;
else eval(”this.document.embeds[whSound].” + (play? “play()”:”stop()”))
}
function playSound(whSound) { if (window.auCon) auCon.control(whSound,true); }
function stopSound(whSound) { if (window.auCon) auCon.control(whSound,false); }
//–></script>
<!– –>


=============
Code in ASP.NET
=============

<td width=”51%” valign=”top”  class=”nav”><div><a href=”#” class=”htext2″ onmouseover=”playSound(0)” onmouseout=”stopSound(0)”>&ndash; Command Altitude<br />
          </a>
              <br />
          <a href=”#” class=”htext2″ onmouseover=”playSound(2)” onmouseout=”stopSound(2)”>&ndash;Command Heading</a><br />
              <br />
          </div>
            <div><a href=”#” class=”htext2″ onmouseover=”playSound(3)” onmouseout=”stopSound(3)”>&ndash;Command Speed</a>
                <br />
              <br />
              <a href=”#” class=”htext2″ onmouseover=”playSound(4)” onmouseout=”stopSound(4)”>&ndash;Override</a> </div>
          </td>
          <td width=”51%” valign=”top”  class=”nav”><div><a href=”#” class=”htext2″ onmouseover=”playSound(5)” onmouseout=”stopSound(5)”>&ndash;Permanent   Override<br />
          </a>
              <br />
          </div>
              <div><a href=”#” class=”htext2″ onmouseover=”playSound(6)” onmouseout=”stopSound(6)”>&ndash;Temporary Override</a><br />
                  <br />
              </div>
            <div class=”htext2″>&ndash;<a href=”#” class=”htext2″ onmouseover=”playSound(7)” onmouseout=”stopSound(7)”>Cruise</a><br />
            </div>
            <div>
                <br />
                <a href=”#” class=”htext2″ onmouseover=”playSound(8)” onmouseout=”stopSound(8)”>&ndash;Manual Heading</a></div></td>
        </tr>
      </table>
    </td>

Any doubts mail me:  radhek@gmail.com

Blogged with Flock

Tags: ,





Full screen with javascript in ASP.NET

6 03 2008

 
Here I am givinng javascript code by using which we can make full screen or normal mode.
This code wcan be useful in ASP.NET

<SCRIPT LANGUAGE=”JavaScript”>

function fullScreen(theURL)
{
window.opener=null;
this.close();
window.open(theURL, ”, ‘fullscreen=yes, scrollbars=auto’);

}
function fuScreen(theURL)
 {
 window.opener=null;
 this.close();
window.open(theURL, ”, ‘fullscreen=no, toolbar=yes ,menubar=yes ,status=yes ,scrollbars=yes, location=yes, resizable=yes, maximized=0, height=800, width=1280, left=0,top=0′);
}
function window_onload()
{
window.moveTo(0,0);
top.window.resizeTo(screen.availWidth,screen.availHeight);

}

//  End –>
</script>

Using this in ASP.NET
=================

<td width=300 align=”right” valign=”middle”>
                <a href=”javascript:fullScreen(’Override_attack_Tut3.aspx’);”><img src=”images/fullscreen mode.jpg” border=”0″ /></a><td>
            <td width=300 align=”center” valign=”middle”>
                <a href=”javascript:fuScreen(’Override_attack_Tut3.aspx’);”><img src=”images/normal mode.jpg”border=”0″ /></a><td>

Blogged with Flock

Tags:





Creating of Random numbers within the given range.

1 03 2008

To generate a random number in a given range.
We can use the .NET bult-in Random class.

Random randobj = new Random();
       
        test1.Text = randobj.Next(0, 359).ToString();
        test2.Text = randobj.Next(60, 110).ToString();
        test3.Text = randobj.Next(60, 350).ToString();

In this way we can generate random number with in range in asp.net

Any doubts mail me: radhek@gmail.com

Blogged with Flock