Blog ( Of Ryan Olshan)

News

About Ryan Olshan

LinkedIn Profile

Follow Ryan via twitter

Join StrongTypes - Free Generics Help By Email
Join StrongTypes

Community Credit Winner

View my MVP profile

The posts on this weblog are provided "as is" with no warranties and confer no rights. The opinions expressed herin are my own personal opinions and do not represent my employer's view in any way.

Subscribe to Rolog via My AOL
Subscribe to Rolog via Bloglines


Subscribe to Rolog via Feedburner

Furl Rolog




Subscribe to Rolog via Newsburst


Subscribe to Rolog via Pluck

Add Rolog to Technorati Favorites




Thycotic Secret Server

Receive Email Updates


.NET Websites

  • => StrongTypes.com <=
  • Community Credit
  • DotNetCharity.com
  • DotNetSlackers
  • EasyListBox
  • LearnAsp.com
  • SystemNetMail.com
  • SystemWebMail.com

Blogroll

  • Alex Campbell
  • Carlos Magalhaes
  • Charles Carroll
  • Chris Taylor
  • Darren Neimke
  • David Betz
  • Eric Smith
  • Rob Caron
  • Rob Howard
  • Sam Gentile
  • Scott Guthrie
  • Scott Mitchell
  • Tess
  • Wesner Moise
  • Jason Alexander
  • Bill Ryan
  • Steve Smith
  • Sahil Malik
  • David Silverlight

Other Websites

  • 911 Pigeon Alert
  • Pacific Wildlife Project

Strong Coder Bloggers

  • Dean Fiala
  • Doug Nelson
  • Kevin Jones

Yahoo! Groups

  • => StrongTypes <=
  • AspNet2
  • AspNet20GridView
  • PayPalDevDotNet
  • RubyOnRails
  • VSTS

C#

Implicit and Explicit Operators in C#

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?

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: May 24 2007, 03:37 PM by Ryan Olshan | with no comments
Filed under:

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: | | | | |
Posted: by Ryan Olshan | with
Filed under: , ,

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: | | | | |
Posted: by Ryan Olshan | with
Filed under: ,
Replacing all instances of UTC time in a string

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);

   }

}

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Feb 26 2006, 03:38 PM by Ryan Olshan | with no comments
Filed under:
Creating a List of a custom class

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;
}

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Jan 11 2006, 10:05 AM by Ryan Olshan | with no comments
Filed under: , ,
Nullable Types

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);
   }
}
   

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Jan 01 2006, 07:47 PM by Ryan Olshan | with 2 comment(s)
Filed under: ,
HttpContext Helper

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
Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 25 2005, 03:44 PM by Ryan Olshan | with no comments
Filed under: , ,
Common DropDownList Issue

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

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 17 2005, 07:20 PM by Ryan Olshan | with 1 comment(s)
Filed under: , ,
Why is it a bad idea to use C# pointers?
I just answered a post on one of the lists I am a member of that asked how to use pointers in C#. Using pointers in C# is a very bad idea. Pointers reference a location in memory. If the garbage collector is called, the location of an object in memory could be moved and the end result is obvious. As such, pointers are categorized as unsafe.

On a side note, any unsafe code in C#, such as pointers, must use the unsafe modifier keyword:

unsafe int * ptr;

R
Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 07 2005, 11:53 AM by Ryan Olshan | with no comments
Filed under:
Using Statement Article
Here is my latest article in which I discuss the use of the using statement in C# and VB.NET.

Using Statement Article

R
Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 07 2005, 10:17 AM by Ryan Olshan | with no comments
Filed under: ,
Starwars Meet Yoda

Earlier I posted about C# Version 3.0 . I found this blog entry on C# 4.0 (codenamed Yoda) - http://blogs.msdn.com/mattwar/archive/2005/10/09/479008.aspx .

R

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 07 2005, 01:41 AM by Ryan Olshan | with no comments
Filed under:
What's wrong with Eval()?
The .NET Framwork 2.0 introduces Eval() . Eval() is a shortcut for Container.DataItem() . Since Eval() uses Reflection, it causes overhead. From a optimization standpoint, it is better to use Container.DataItem() .

VB.NET

Container.DataItem()

C#
DataReader: ((System.Data.Common.DbDataRecord)Container.DataItem)[]
DataSet: ((System.Data.DataRowView)Container.DataItem)[]

R
Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 06 2005, 03:45 PM by Ryan Olshan | with 1 comment(s)
Filed under: , , ,
C# Version 3.0 Specifications
Have you ever wondered what the next version of C# (3.0) has to offer? Microsoft has published the specifications and they can be downloaded at http://tinyurl.com/baoh8 .

R

Share this post: | bookmark it! | digg it! | reddit! | kick it! | live it!
Posted: Dec 06 2005, 11:40 AM by Ryan Olshan | with 2 comment(s)
Filed under:
More Posts