For a side project I'm working on, explicit operators have come in handy in the data layer. With explicit operators, you can convert from one class to another using a user-defined conversion operator. For example:
public
class
MyClass
{
private
int
_id;
private
string
_description;
public
int
ID
{
get
{
return
_id; }
set
{ _id =
value
; }
}
public
string
Description
{
get
{
return
_description; }
set
{ _description =
value
; }
}
public
static
MyClass
GetMyClass(
int
id)
{
return
(
MyClass
)
AnotherClass
.GetRows(id);
}
public
static
explicit
operator
MyClass
(
DataTable
dataTable)
{
MyClass
myClass =
new
MyClass
();
myClass.ID =
Convert
.ToInt32(dataTable.Rows[0][
"ID"
]);
myClass.Description =
Convert
.ToString(dataTable.Rows[0][
"Description"
]);
return
myClass;
}
}
public
class
AnotherClass
{
public
static
DataTable
GetRows(
int
id)
{
DataTable
dataTable =
new
DataTable
();
//...
return
dataTable;
}
}
With implicit operators, you can implicitly convert from one class to another using a user-defined operator without casting. For example:
public
class
MyClass
{
private
int
_value;
public
int
Value
{
get
{
return
_value; }
set
{ _value =
value
; }
}
public
MyClass()
{
}
public
MyClass(
int
value)
{
_value = value;
}
public
static
void
SomeMethod()
{
MyClass
myClass =
new
MyClass
(2);
int
id = myClass;
}
public
static
implicit
operator
int
(
MyClass
myClass)
{
return
myClass.Value;
}
}
Pretty cool, huh?
Some people may not know that .NET 2.0 provides APIs for accessing everything in a configuration file. The most common question I see relates to accessing the mail settings in the system.net node programmatically.
C#
using
System.Configuration;
using
System.Web.Configuration;
using
System.Net.Configuration;
Configuration
configurationFile =
WebConfigurationManager
.OpenWebConfiguration(
"PathToConfigFile"
);
MailSettingsSectionGroup
mailSettings = configurationFile.GetSectionGroup(
"system.net/mailSettings"
)
as
MailSettingsSectionGroup
;
if
(mailSettings !=
null
)
{
int
port = mailSettings.Smtp.Network.Port;
string
host = mailSettings.Smtp.Network.Host;
string
password = mailSettings.Smtp.Network.Password;
string
username = mailSettings.Smtp.Network.UserName;
}
VB.NET
Imports
System.Configuration
Imports
System.Web.Configuration
Imports
System.Net.Configuration
Dim
configurationFile
As
Configuration = WebConfigurationManager.OpenWebConfiguration(
"PathToConfigFile"
)
Dim
mailSettings
As
MailSettingsSectionGroup = configurationFile.GetSectionGroup(
"system.net/mailSettings"
)
If
Not
mailSettings
Is
Nothing
Then
Dim
port
As
Integer
= mailSettings.Smtp.Network.Port
Dim
host
As
String
= mailSettings.Smtp.Network.Host
Dim
password
As
String
= mailSettings.Smtp.Network.Password
Dim
username
As
String
= mailSettings.Smtp.Network.UserName
End
If
Share this post:
|
|
|
|
|
Below is a C# and VB.NET class that demonstrates using System.Net.Mail to send an email.
Download C# System.Net.Mail Helper
Download VB.NET System.Net.Mail Helper
Calling the function from code
MailHelper
.SendMailMessage(
""
,
""
,
""
,
""
,
"Sample Subject"
,
"Sample body of text for mail message"
)
MailHelper.cs
using
System.Net.Mail;
public
class
MailHelper
{
///
///
Sends an mail message
///
///
Sender address
///
Recepient address
///
Bcc recepient
///
Cc recepient
///
Subject of mail message
///
Body of mail message
public
static
void
SendMailMessage(
string
from,
string
to,
string
bcc,
string
cc,
string
subject,
string
body)
{
// Instantiate a new instance of MailMessage
MailMessage
mailMessage =
new
MailMessage
();
// Set the sender address of the mail message
mailMessage.From =
new
MailAddress
(from);
// Set the recepient address of the mail message
mailMessage.To.Add(
new
MailAddress
(to));
// Check if the bcc value is null or an empty string
if
(!
string
.IsNullOrEmpty(bcc))
{
// Set the Bcc address of the mail message
mailMessage.Bcc.Add(
new
MailAddress
(bcc));
}
// Check if the cc value is null or an empty value
if
(!
string
.IsNullOrEmpty(cc))
{
// Set the CC address of the mail message
mailMessage.CC.Add(
new
MailAddress
(cc));
}
// Set the subject of the mail message
mailMessage.Subject = subject;
// Set the body of the mail message
mailMessage.Body = body;
// Set the format of the mail message body as HTML
mailMessage.IsBodyHtml =
true
;
// Set the priority of the mail message to normal
mailMessage.Priority =
MailPriority
.Normal;
// Instantiate a new instance of SmtpClient
SmtpClient
smtpClient =
new
SmtpClient
();
// Send the mail message
smtpClient.Send(mailMessage);
}
}
MailHelper.vb
Imports
System.Net.Mail
Public
Class
MailHelper
'''
''' Sends an mail message
'''
''' Sender address
''' Recepient address
''' Bcc recepient
''' Cc recepient
''' Subject of mail message
''' Body of mail message
Public
Shared
Sub
SendMailMessage(
ByVal
from
As
String
,
ByVal
recepient
As
String
,
ByVal
bcc
As
String
,
ByVal
cc
As
String
,
ByVal
subject
As
String
,
ByVal
body
As
String
)
' Instantiate a new instance of MailMessage
Dim
mailMessage
As
New
MailMessage()
' Set the sender address of the mail message
mailMessage.From =
New
MailAddress(from)
' Set the recepient address of the mail message
mailMessage.To.Add(
New
MailAddress(recepient))
' Check if the bcc value is nothing or an empty string
If
Not
String
.IsNullOrEmpty(bcc)
Then
' Set the Bcc address of the mail message
mailMessage.Bcc.Add(
New
MailAddress(bcc))
End
If
' Check if the cc value is nothing or an empty value
If
Not
String
.IsNullOrEmpty(cc)
Then
' Set the CC address of the mail message
mailMessage.CC.Add(
New
MailAddress(cc))
End
If
' Set the subject of the mail message
mailMessage.Subject = subject
' Set the body of the mail message
mailMessage.Body = body
' Set the format of the mail message body as HTML
mailMessage.IsBodyHtml =
True
' Set the priority of the mail message to normal
mailMessage.Priority = MailPriority.Normal
' Instantiate a new instance of SmtpClient
Dim
smtpClient
As
New
SmtpClient()
' Send the mail message
smtpClient.Send(mailMessage)
End
Sub
End
Class
Web.config
xml
version
=
"
1.0
"
?>
<
configuration
>
<
system.net
>
<
mailSettings
>
<
smtp
from
=
"
"
>
<
network
host
=
"
smtp.yourdomain.com
"
port
=
"
25
"
userName
=
"
yourUserName
"
password
=
"
yourPassword
"
/>
smtp
>
mailSettings
>
system.net
>
configuration
>
Share this post:
|
|
|
|
|
I'm in the progress of upgrading a web application from .NET 1.1 to 2.0 and came across this function that I created which replaces all instances of date/time in a string. In the application users add notes and when it gets saved to the database it appends Added By [User] on [Date/Time] to the end of the notes. The date/time is added as UTC format, so I had to come up with a way to replace each instance of date/time to the users local time when the notes are viewed. Here's how I did it:
using
System;
using
System.Text.RegularExpressions;
public
class
TimeZoneConversionHelper
{
public
static
string
RegexReplaceTime(
string
input,
double
timeZone)
{
string
convertedText =
String
.Empty;
if
((input !=
String
.Empty) && (input !=
null
))
{
string
pattern =
@"\?*(((((0[13578])|([13578])|(1[02]))[\-\/\s]?\b((0[1-9])|([1-9])|([1-2][0-
9])|(3[01])))|((([469])|(11))[\-\/\s]?\b((0[1-9])|([1-9])|([1-2][0-9])|(30)))|((02|2)[\-\/\s]?\b((0[1-
9])|([1-9])|([1-2][0-9]))))[\-\/\s]?\b\d{4})(\s(((0[1-9])|([1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5]
[0-9])\s))([AM|PM|am|pm]{2,2})))?"
;
MatchCollection
matchCollection =
Regex
.Matches(input, pattern);
foreach
(
Match
match
in
matchCollection)
{
DateTime
conversionDateTime = TimeZoneConversion(
Convert
.ToDateTime(match.Value), timeZone);
convertedText = input.Replace(match.ToString(), conversionDateTime.ToString());
}
}
return
convertedText;
}
public
static
DateTime
TimeZoneConversion(
DateTime
utcTime,
double
timeZone)
{
return
utcTime.AddHours(timeZone);
}
}
Let's say for instance, you want to create a List of your own class, say Employee, where Employee represents an employee. First, we'll start by creating an employee class.
[
Serializable
]
public class
Employee
{
private bool
m_IsSalaried;
private int
m_Age;
private string
m_Email;
private string
m_Name;
public
Employee(
bool
isSalaried,
int
age,
string
email,
string
name)
{
m_Age = age;
m_Email = email;
m_IsSalaried = isSalaried;
m_Name = name;
}
public int
Age
{
get
{
return
m_Age; }
set
{ m_Age =
value
; }
}
public string
Email
{
get
{
return
m_Email; }
set
{ m_Email =
value
; }
}
public bool
IsSalaried
{
get
{
return
m_IsSalaried; }
set
{ m_IsSalaried =
value
; }
}
public string
Name
{
get
{
return
m_Name; }
set
{ m_Name =
value
; }
}
}
You can then add an employee to a List collection as follows:
using
System.Collections.Generic;
...
List
<
Employee
> m_EmployeeList =
new
List
<
Employee
>();
m_EmployeeList.Add(
new
Employee
(
true
, 30,
,
"Jane Doe"
));
You can get values for Employees in the List collection by enumerating through the Employees.
foreach
(
Employee
employee
in
m_EmployeeList)
{
SomeBool = employee.IsRetired;
SomeInt = employee.Age;
SomeString1 = employee.Email;
SomeString2 = employee.Name;
}
One of the weirder features in C# 2.0 is nullable types. My thinking is as follows: Why complicate things with Nullable, or its shorter version of DataType? (i.e. int?), instead of allowing null values to be assigned to those data types that don't have any way of handling null? Maybe it was a matter of not breaking the framework or introducing changes gradually. Also, code such as that below will cause the compiler to error as nullable types and their non-nullable type equivelent are treated as 2 different types.
int
? m_Value1;
// The shorter version of Nullable m_Value1
m_Value1 =
int
.Parse(Request.QueryString[
"SomeNumberParam"
]);
int
m_Value2;
if
(m_Value1 !=
null
)
// Nullable types can be checked for null
{
m_Value2 = m_Value1;
// Won't compile
m_Value2 = (
int
)m_Value1;
// Will compile
}
Hopefully, in the next version of C#, nullable types will be replaced with the ability for their non-nullable versions to handle null, like below:
int
m_Value1, m_Value2;
m_Value1 =
int
.Parse(Request.QueryString[
"SomeNumberParam"
]);
if
(m_Value1 !=
null
)
{
m_Value2 = m_Value1;
}
Do you dare ask what this non-sense looks like in code form? In case you are wondering, I'm using the non-nullable form of the word form. Sorry if I've confused you by including the ? after form in order to form a question. I now present you with non-sense:
using
System;
using
System.Runtime.CompilerServices;
using
System.Runtime.InteropServices;
[
Serializable
,
StructLayout
(
LayoutKind
.Sequential),
TypeDependency
(
"System.Collections.Generic.NullableComparer`1"
),
TypeDependency
(
"System.Collections.Generic.NullableEqualityComparer`1"
)]
public
struct
Nullable
where
T :
struct
{
private
bool
hasValue;
internal
T value;
public
Nullable(T value)
{
this
.value = value;
this
.hasValue =
true
;
}
public
bool
HasValue
{
get
{
return
this
.hasValue;
}
}
public
T Value
{
get
{
if
(!
this
.HasValue)
{
ThrowHelper
.ThrowInvalidOperationException(
ExceptionResource
.InvalidOperation_NoValue);
}
return
this
.value;
}
}
public
T GetValueOrDefault()
{
return
this
.value;
}
public
T GetValueOrDefault(T defaultValue)
{
if
(!
this
.HasValue)
{
return
defaultValue;
}
return
this
.value;
}
public
override
bool
Equals(
object
other)
{
if
(!
this
.HasValue)
{
return
(other ==
null
);
}
if
(other ==
null
)
{
return
false
;
}
return
this
.value.Equals(other);
}
public
override
int
GetHashCode()
{
if
(!
this
.HasValue)
{
return
0;
}
return
this
.value.GetHashCode();
}
public
override
string
ToString()
{
if
(!
this
.HasValue)
{
return
""
;
}
return
this
.value.ToString();
}
public
static
explicit
operator
T(
Nullable
value)
{
return
value.get_Value();
}
public
static
implicit
operator
Nullable
(T value)
{
return
new
Nullable
(value);
}
}
Need to access an HttpContext object in a class, but can't because the class doesn't inherit System.Web.UI.Page? Here is a simple helper class that will allow you to access some of the most common HttpContext objects.
C#
using
System;
using
System.Web;
using
System.Web.Caching;
using
System.Web.SessionState;
///
///
Encapsulates all HTTP-specific information about an individual HTTP request.
///
public
class
HttpContextHelper
{
///
///
Gets the System.Web.HttpApplicationState object for the current HTTP request.
///
public
static
HttpApplicationState
CurrentApplication
{
get
{
return
HttpContext
.Current.Application; }
}
///
///
Gets the System.Web.Caching.Cache object for the current HTTP request.
///
public
static
Cache
CurrentCache
{
get
{
return
HttpContext
.Current.Cache; }
}
///
///
Gets the System.Web.HttpRequest object for the current HTTP request.
///
public
static
HttpRequest
CurrentRequest
{
get
{
return
HttpContext
.Current.Request; }
}
///
///
Gets the System.Web.HttpResponse object for the current HTTP response.
///
public
static
HttpResponse
CurrentResponse
{
get
{
return
HttpContext
.Current.Response; }
}
///
///
Gets the System.Web.HttpServerUtility object that provides methods used in
///
processing Web requests.
///
public
static
HttpServerUtility
CurrentServer
{
get
{
return
HttpContext
.Current.Server; }
}
///
///
Gets the System.Web.SessionState.HttpSessionState object for the current
///
HTTP request.
///
public
static
HttpSessionState
CurrentSession
{
get
{
return
HttpContext
.Current.Session; }
}
}
VB.NET
Imports
System
Imports
System.Web
Imports
System.Web.Caching
Imports
System.Web.SessionState
'''
''' Encapsulates all HTTP-specific information about an individual HTTP request.
'''
Public
Class
HttpContextHelper
'''
''' Gets the System.Web.HttpApplicationState object for the current HTTP request.
'''
Public
Shared
ReadOnly
Property
CurrentApplication()
As
HttpApplicationState
Get
Return
HttpContext.Current.Application
End
Get
End
Property
'''
''' Gets the System.Web.Caching.Cache object for the current HTTP request.
'''
Public
Shared
ReadOnly
Property
CurrentCache()
As
Cache
Get
Return
HttpContext.Current.Cache
End
Get
End
Property
'''
''' Gets the System.Web.HttpRequest object for the current HTTP request.
'''
Public
Shared
ReadOnly
Property
CurrentRequest()
As
HttpRequest
Get
Return
HttpContext.Current.Request
End
Get
End
Property
'''
''' Gets the System.Web.HttpResponse object for the current HTTP response.
'''
Public
Shared
ReadOnly
Property
CurrentResponse()
As
HttpResponse
Get
Return
HttpContext.Current.Response
End
Get
End
Property
'''
''' Gets the System.Web.HttpServerUtility object that provides methods used in
'''
processing Web requests.
'''
Public
Shared
ReadOnly
Property
CurrentServer()
As
HttpServerUtility
Get
Return
HttpContext.Current.Server
End
Get
End
Property
'''
''' Gets the System.Web.SessionState.HttpSessionState object for the current
'''
HTTP request.
'''
Public
Shared
ReadOnly
Property
CurrentSession()
As
HttpSessionState
Get
Return
HttpContext.Current.Session
End
Get
End
Property
End
Class
A common DropDownList issue I've seen on many forums and lists is about a DropDownList populating items 2x or not being able to get the selected value on postback when binding to a data source. This is due to the DropDownList having data bound to it again on postback before the form is processed. To prevent this, you will need to ensure that the DropDownList is only bound to data on the initial load of the page.
VB.NET
Private Sub
Page_Load(
ByVal
sender
As Object
,
ByVal
e
As
EventArgs)
If Not
IsPostBack
Then
' Code here to bind data to DropDownList
End If
End Sub
C#
private void
Page_Load(
object
sender,
EventArgs
e)
{
if
(!IsPostBack)
{
// Code here to bind data to DropDownList
}
}
R