Adnan’s Blog

Posts Tagged ‘asp.net

Unlike the normal TextBox, the MaxLength property doesnt work for MultiLine TextBox. Heres a small trick to solve the problem:


<asp:TextBox ID="txtExample" runat="server" TextMode="MultiLine" />
<asp:RegularExpressionValidator ID="revExample" runat="server" 
ControlToValidate="txtExample" ValidationExpression="[\s\S]{1,200}" 
Display="Dynamic" ErrorMessage="Length cannot be greater than 200 characters" />

The above markup validates the revExample TextBox / textarea and limits the max characters to 200. By modifying the regular expressions, we can validate fields for any scenario. If you are looking for some Regular Expressions to get started out, just point your browser to http://regexlib.com/

Cheers!


The average programmer uses the general Debug mode by using the “Start Debugging” option from the Debug menu, or the F5 shortcut key. But what if you want to debug an application that is already running? If you faced this problem, then this tip should lighten up your day.

Choose Debug | Attach to Process….

Select the aspnet_wp.exe from the list of Available Processes and click on Attach

Attach To Process...

Attach To Process...

Alternatively you can also use ALT + D , P to select the option.

I needed to integrate support for vCalendar in my current project. So i went through the vCalendar spec 1.0 at http://www.imc.org/pdi/vcal-10.txt and wrote this class. Although I have not implemented all the specification features, but this should prove sufficient for the usual requirements. If you have any comments / suggestions , let me know.

Read the rest of this entry »

Tags: ,

Heres a quick tip. If you need to include a request for read receipt like Microsoft Outlook while sending mails through Asp.net, just add the Disposition-Notification-To Header to the MailMessage.

The MailMessage class does not have a corresponding attribute and thus it has to be set through the Header.

MailMessage mm = new MailMessage(fromAddress, toAddress);
mm.Subject = subject;
mm.Headers.Add("Disposition-Notification-To", sendReadReceiptToAddress);

Please keep in mind that this is only a request, and can be rejected/ignored by the Mail Client/User configuration.

In my current project I needed to access the Session state in a Generic Handler. To my dismay, i realized that the Session StateBag was null. The StateBag class is sealed and manages the Viewstate of the Asp.net server controls and pages.

Upon discussion with my colleague, Mr. Hamed, we found the solution to my problem. Using the IRequiresSessionState interface in System.Web.SessionState, we got access to Session state.

According to Microsoft “Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

Another option was to use the IReadOnlySessionState interface (Specifies that the target HTTP handler requires only read access to session-state values. This is a marker interface and has no methods.)

Needless to say, there is a performance increase in the latter case and if your requirement is only to read Session state, then that would be the right choice

When you pass information from one page to another, you are passing information that anybody can sniff. For example consider a scenario, in which you pass the customer id as a query string:

http://www.yourapplication.com?customer_id=15

Now if somebody replaced 15 with say 10 or any other number, they can pull up other customer information. And thats a bad for security.

One solution to this problem is to use ecryption using a secret key. So lets use a hard-to-crack 8 byte key like $zm0!qp?

To accomplish this heres a code snippet


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(sEncryptionKey, 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, 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;
}
}
}

The end user will get to see a random text in the query string, something like

http://www.yourapplication.com/Receive.aspx?key=a2f5ckj?h79#8dd3

Remember stay secure stay safe.

If you are using Membership Provider in your ASP.net application, you might come across a scenario in which you need to have both Security Question and Answer feature and would also like to programmatically reset the password for an account.

So if you run the code

string username = “user”;
string password = “password”;
MembershipUser mu = Membership.GetUser(username);
mu.ChangePassword(mu.ResetPassword(), password);

You will get an error when you try to reset the password. A solution is to add another Membership provider having all the same settings as the default provider with only one exception:

<add name="NewMembershipProvider" requiresQuestionAndAnswer=”false” ....../>

For all Membership functions, you the default Membership provider will be used, but when you need to reset the password, you must reference the new Provider. Here’s a code excerpt to help you out:

string username = “user”;
string password = “password”;
MembershipUser mu = Membership.Providers["NewMembershipProvider"].GetUser(username, false);
mu.ChangePassword(mu.ResetPassword(), password);

So now your application can use both the Security feature to recover password and programmatically Change/Reset the password when required.