Adnan Rashid

Web Technologist

Follow me on TwitterRSS Feeds

  • Home
  • Projects
    • WebLight
    • Zakat Calculator
  • About Me

SQL Server Reseed Identity Value

May 24th

Posted by Adnan Rashid

No comments

DBCC CHECKIDENT can reset the identity value of the table. The syntax is as follows :

DBCC CHECKIDENT (<table_name>, reseed, <seed_value>)

After executing this statement, the next inserted record will have seed_value + 1 as value. This rule is applicable only if the table previously contained records.

In case of a table with no records, since the current Seed Value is NULL, after execution of the above statement, the SEED VALUE is updated to 0. Thus when the first record is inserted, the SEED VALUE will be 0 not 1.

sql

Javascript – Query String Parameters

Mar 4th

Posted by Adnan Rashid

No comments

Here’s a small JavaScript helper to read URL Query String Parameters.

function GetUrlParams()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?')
					+ 1).split('&');

	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

The above function, will read the URL, get the query string part i.e from (“?”) and split each parameter by the (“=”) character and create a name value pair allowing us to access the param value using the param name.

For example, if we are have a test.htm in http://www.example.com and the URL is : http://www.example.com/test.htm?fname=Adnan&lname=Rashid

To access the param values we can use something like :

var params = GetUrlParams();
alert(params["fname"]);
alert(params["lname"]);
javascript

Multiline TextBox Length Validation

Jan 10th

Posted by Adnan Rashid

No comments

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!

asp.net

Conditional Breakpoints

Dec 23rd

Posted by Adnan Rashid

No comments

Visual Studio is filled with nifty tricks, which if leveraged properly in the right situation can make the developers life easy. Consider if you had a looping statement, and wanted to debug it, but only for a particular value. Rather than hitting the breakpoint every time, you can shorten the hits by using a Conditional Breakpoint.

To set a Conditional Breakpoint, right-click the Breakpoint circle and select the Condition option.

You can then define the condition and additionally select an option to filter the condition for evaluating the condition, or for raising the breakpoint when the value of the expression changes.

visual studio

Attach to Process…

Dec 22nd

Posted by Adnan Rashid

No comments

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

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

visual studio

vCalendar – C# Implementation

Nov 18th

Posted by Adnan Rashid

No comments

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.

using System;
using System.Text;
using System.IO;
using System.Collections;

/// <summary>
/// Summary description for VCalendar
/// </summary>
public class VCalendar
{
	private string _productID;
	/// <summary>
	/// A unique identifier identifying the originating program
	/// </summary>
	public string ProductIdentifier
	{
		get { return _productID; }
		set { _productID = value; }
	}

	private ArrayList _categories;
	/// <summary>
	/// ArrayList of categories
	/// </summary>
	public ArrayList Categories
	{
		get { return _categories; }
		set { _categories = value; }
	}

	private DateTime _createdOn = DateTime.MinValue;
	/// <summary>
	/// DateTime that the vEvent was created.
	/// </summary>
	public DateTime CreatedOn
	{
		get { return _createdOn; }
		set { _createdOn = value; }
	}

	private DateTime _completedOn = DateTime.MinValue;
	/// <summary>
	/// DateTime the vEvent completed on
	/// </summary>
	public DateTime CompletedOn
	{
		get { return _completedOn; }
		set { _completedOn = value; }
	}

	private DateTime _startOn = DateTime.MinValue;
	/// <summary>
	/// DateTime that the vEvent will start
	/// </summary>
	public DateTime StartOn
	{
		get { return _startOn; }
		set { _startOn = value; }
	}

	private DateTime _endOn = DateTime.MinValue;
	/// <summary>
	/// DateTime that the vEvent will end
	/// </summary>
	public DateTime EndOn
	{
		get { return _endOn; }
		set { _endOn = value; }
	}

	private ClassificationType _classification = ClassificationType.PUBLIC;
	/// <summary>
	/// Defines the access classification for the vEvent entity
	/// </summary>
	public ClassificationType Classification
	{
		get { return _classification; }
		set { _classification = value; }
	}

	private int _priority = 0;
	/// <summary>
	/// 0 = undefined, 1 = High, -1 = Low. Defaults to 0
	/// </summary>
	public int Priority
	{
		get { return _priority; }
		set { _priority = value; }
	}

	private string _subject;
	/// <summary>
	/// Subject of the vEvent
	/// </summary>
	public string Subject
	{
		get { return _subject; }
		set { _subject = value; }
	}

	private string _description;
	/// <summary>
	/// Description of the vEvent
	/// </summary>
	public string Description
	{
		get { return _description; }
		set { _description = value; }
	}

	private bool _enableAlarm;
	/// <summary>
	/// Flag to enable the reminder alarm
	/// </summary>
	public bool EnableAlarm
	{
		get { return _enableAlarm; }
		set { _enableAlarm = value; }
	}

	public override string ToString()
	{
		StringBuilder sb = new StringBuilder();
		sb.Append(“BEGIN:VCALENDAR\n”);
		sb.Append(“VERSION:1.0\n”);
		sb.Append(“BEGIN:VEVENT\n”);

		// Product Identifier
		if (!string.IsNullOrEmpty(_productID))
			sb.AppendFormat(“PRODID:{0}\n”, _productID);

		// Categories
		if (_categories != null && _categories.Count != 0)
		{
			sb.Append(“CATEGORIES:”);
			for (int i = 0; i < _categories.Count; i++)
			{
				if (i == 0)
					sb.Append(_categories[0].ToString());
				else
					sb.AppendFormat(“;{0}”, _categories[i].ToString());
			}
			sb.Append(“\n”);
		}

		// Created On
		if (_createdOn != DateTime.MinValue)
			sb.AppendFormat(“DCREATED:{0}\n”, _createdOn.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”));

		// Start Date Time
		if (_startOn != DateTime.MinValue)
		{
			sb.AppendFormat(“DTSTART:{0}\n”, _startOn.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”));

			// Display Reminder
			if (_enableAlarm)
				sb.AppendFormat(“DALARM:{0};PT5M;2;{1}\n”, _startOn.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”), _subject);
		}

		// End Date Time
		if (_endOn != DateTime.MinValue)
			sb.AppendFormat(“DTEND:{0}\n”, _endOn.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”));

		// Completed On
		if (_completedOn != DateTime.MinValue)
			sb.AppendFormat(“COMPLETED:{0}\n”, _completedOn.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”));

		// Priority
		if (_priority != 0)
			sb.AppendFormat(“PRIORITY:{0}\n”, _priority);

		// Description
		if (!string.IsNullOrEmpty(_description))
			sb.AppendFormat(“DESCRIPTION:{0}\n”, _description);

		// Subject
		if (!string.IsNullOrEmpty(_subject))
			sb.AppendFormat(“SUMMARY:{0}\n”, _subject);
		if (_classification != ClassificationType.PUBLIC)
			sb.AppendFormat(“CLASS:{0}\n”, Enum.GetName(typeof(ClassificationType), Classification));
		sb.Append(“END:VEVENT\n”);
		sb.Append(“END:vCalendar”);
		return sb.ToString();
	}

	public void Generate(string filePath, FileMode mode)
	{
		FileStream fs = new FileStream(filePath, mode);
		StreamWriter sw = new StreamWriter(fs);
		using (sw)
		{
			sw.Write(this.ToString());
		}
	}
}

public class Attendee
{
	private StatusType _status;
	public StatusType Status
	{
		get { return _status; }
		set { _status = value; }
	}

	private AttendeeType _role;
	public AttendeeType Role
	{
		get { return _role; }
		set { _role = value; }
	}

	public string _attendeeName;
	public string AttendeeName
	{
		get { return _attendeeName; }
		set { _attendeeName = value; }
	}

	public override string ToString()
	{
		StringBuilder sb = new StringBuilder();
		if (!string.IsNullOrEmpty(_attendeeName))
		{
			sb.Append(“ATTENDEE”);
			if (_role != AttendeeType.ATTENDEE)
				sb.AppendFormat(“;ROLE={0}”, Enum.GetName(typeof(AttendeeType), Role));
			if (_status != StatusType.NEEDS_ACTION)
				sb.AppendFormat(“;STATUS={0}”, Enum.GetName(typeof(StatusType), Status));
			sb.AppendFormat(“:{0}\n”, _attendeeName);
			return sb.ToString();
		}
		else
			return string.Empty;
	}
}
public enum AttendeeType
{
	ATTENDEE,
	ORGANIZER,
	OWNER,
	DELEGATE,
}
public enum StatusType
{
	ACCEPTED,
	NEEDS_ACTION,
	SENT,
	TENTATIVE,
	CONFIRMED,
	DECLINED,
	COMPLETED,
	DELEGATED
}
public enum RSVPType
{
	YES,
	NO
}
public enum ExpectType
{
	FYI,
	REQUIRE,
	REQUEST,
	IMMEDIATE
}
public enum CategoryType
{
	APPOINTMENT,
	BUSINESS,
	EDUCATION,
	HOLIDAY,
	MEETING,
	MISCELLANEOUS,
	PERSONAL,
	TRAVEL,
	VACATION
}
public enum ClassificationType
{
	PUBLIC,
	PRIVATE,
	CONFIDENTIAL
}
c#

An anonymous type cannot have multiple properties with the same name

Oct 10th

Posted by Adnan Rashid

No comments

If you are using LINQ and have a query that looks something like this :

var myUser = (from user in dbContext.Users
				join comp in dbContext.Companies on user.CompanyID equals comp.CompanyID
				where user.UserID == "12345"
				select new {user.UserID, user.Name, comp.Name}).SingleOrDefault();

string _userID = myUser.UserID;
string _userName = myUser.Name;
string _companyName = myUser.Name;

In the above code, example we are using a syntactic sugar feature of C# 3.0 by building anonymous types. When you try to compile the above code, you will get an “An anonymous type cannot have multiple properties with the same name” error. This is because the compiler can’t differentiate if the Name property belongs to the Users table or the Companies table. So to solve this problem, we need to assign something like an alias to the conflicting properties.

var myUser = (from user in dbContext.Users
				join comp in dbContext.Companies on user.CompanyID equals comp.CompanyID
				where user.UserID == "12345"
				select new {user.UserID, UserName = user.Name, CompanyName = comp.Name}).SingleOrDefault();

string _userID = myUser.UserID;
string _userName = myUser.UserName;
string _companyName = myUser.CompanyName;

Happy coding!!!

c#, linq

Asp.Net Read Reciept Request

Sep 28th

Posted by Adnan Rashid

No comments

Here’s 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.

asp.net, c#

Generic Handler – Session State

Sep 26th

Posted by Adnan Rashid

No comments

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

asp.net, c#

Remove project from Recent Projects in Visual Studio

Sep 15th

Posted by Adnan Rashid

No comments

Recently, I felt the need for removing a project from the Visual Studio Start Page, so I Googled and would like to share the solution. Don’t forget to close visual studio before trying this out. This trick requires modification to registry, so if you are skeptical do make a backup of the registry before proceeding.

Start the registry :

Start > Run > regedit > HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList

Then delete the key that has the project you want to remove.

Note:

  • The Project Keys are consecutive. So if you have 5 projects listed, and you delete the key for the 4th project ie File4, the 5th project (File5) will also not be shown. You will need to remain one of the keys so that the list remains consecutive.
  • The same procedure can be repeated for the FileList and Find sections of the registry
visual studio
«1234»
  • Tags

    asp.net c# css freebie google javascript jQuery linq mysql open source php sql tools visual studio wordpress

    WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.

  • My Tweeets

    Loading tweets...
    Follow me on Twitter!
  • User Login






    • Lost your password?
  • Certifications

    • Brainbench : Asp.Net :: Master
    • Brainbench : C#
    • Brainbench : Web Design Concepts :: Master
  • Accounts

    • LinkedIn Profile
    • Naymz Profile
Powered by WordPress
RSS Feeds XHTML 1.1 Top