Web Technologist
Posts tagged c#
NOLOCK in LINQ
May 8th
The NOLOCK table hint, also known as READUNCOMITTED, is applicable to SELECT statements only. NOLOCK indicates that no shared locks are issued against the table that would prohibit other transactions from modifying the data in the table.
The most recommended way of implementing NOLOCK is to use a TransactionScope to affect the TransactionOptions associated with the commands of the LINQ context.
Heres a sample code :
using (new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Required,
new System.Transactions.TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
}))
{
// Retreive Data
}
Random Row – Linq to SQL
Apr 4th
You can retrieve a random data record from an SQL database through LINQ using a User Defined Function. We can implement the above in a partial class for the target context.
partial class MyTargetContext {
[Function(Name="NEWID", IsComposable=true)]
public Guid Random()
{
throw new NotImplementedException();
}
}
In the above example which returns a uniqe identifier (GUID), we are mapping the Random method to the NEWID SQL function. The IsComposable boolean property of the Function Attribute, defines if the method is mapped to a function (true) or to a Stored Procedure (false). Also note that since this method is mapped, the C# code is not executed.
We can call the above implementation as …
var posts = (from post in dbContext.Posts
where post.IsActive && post.Category.Equals('Linq')
order by dbContext.Random()
select post).FirstOrDefault();
Although there are better alternative in terms of performance, this approach is much easier and should work fine for small / mid-size tables.
ObjectTrackingEnabled – LINQ
Feb 18th
You may come across a requirement, where you will retrieve data only for reading. LINQ monitors the changes, which as you might have guessed is the not the best solution everywhere, especially in the above scenario.
Here is a quick tip to increase the performance by disabling object tracking in LINQ using the ObjectTrackingEnabled property. This will turn off the unnecessary identity management of the objects.
using (NorthwindDataContext dbContext = new NorthwindDataContext())
{
dbContext.ObjectTrackingEnabled = false;
}
vCalendar – C# Implementation
Nov 18th
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
}
An anonymous type cannot have multiple properties with the same name
Oct 10th
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!!!
Asp.Net Read Reciept Request
Sep 28th
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.
Generic Handler – Session State
Sep 26th
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
Encypting query string in Asp.Net
Jul 8th
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 that’s bad for security.
One solution to this problem is to use encryption using a secret key. So lets use a hard-to-crack 8 byte key like $zm0!qp?
To accomplish this here is 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.
Asp.Net Reset Password
Jul 6th
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 pro-grammatically 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 pro-grammatically Change/Reset the password when required.

