RSS

Category Archives: Dot Net

Enum With String Values In C#

I am currently making a Virtual Earth asp.net ajax server control and came to the point where I had to replicate the enums in my classes, but the issue with them is that the enums do not use integer values but string ones. In C# you cannot have an enum that has string values :(. So the solution I came up with (I am sure it has been done before) was just to make a new custom attribute called StringValueAttribute and use this to give values in my enum a string based value.

Note: All code here was written using .NET 3.5 and I am using 3.5 specific features like automatic properties and exension methods, this could be rewritten to suit 2.0 quite easily.

First I created the new custom attribute class, the source is below:

    /// <summary>
    /// This attribute is used to represent a string value
    /// for a value in an enum.
    /// </summary>
    public class StringValueAttribute : Attribute {

        #region Properties

        /// <summary>
        /// Holds the stringvalue for a value in an enum.
        /// </summary>
        public string StringValue { get; protected set; }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor used to init a StringValue Attribute
        /// </summary>
        /// <param name=”value”></param>
        public StringValueAttribute(string value) {
            this.StringValue = value;
        }

        #endregion

    }

 
Then I created a new Extension Method which I will use to get the string value for an enums value:

        /// <summary>
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        /// </summary>
        /// <param name=”value”></param>
        /// <returns></returns>
        public static string GetStringValue(this Enum value) {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString());

            // Get the stringvalue attributes
            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                typeof(StringValueAttribute), false) as StringValueAttribute[];

            // Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].StringValue : null;
        }
 

So now create your enum and add the StringValue attributes to your values:

 public enum Test : int {
        [StringValue(“a”)]
        Foo = 1,
        [StringValue(“b”)]
        Something = 2       
 }

Now you are ready to go, to get the string value for a value in the enum you can do so like this now:

Test t = Test.Foo;
string val = t.GetStringValue();

– or even –

string val = Test.Foo.GetStringValue();

All this is very easy to implement and I like the ease of use you get from the extension method [I really like them :)] and it gave me the power I needed to do what I needed. I haven’t tested the performance hit that the reflection may give and might do so sometime soon.

 
Leave a comment

Posted by on June 8, 2010 in Dot Net

 

Tags: , ,

Generate random 5 digit number using asp.net

public string GetRandomString(int seed)
    {
        //use the following string to control your set of alphabetic characters to choose from
        //for example, you could include uppercase too
        const string alphabet = "abcdefghijklmnopqrstuvwxyz";

        // Random is not truly random,
        // so we try to encourage better randomness by always changing the seed value
        Random rnd = new Random((seed + DateTime.Now.Millisecond));

        // basic 5 digit random number
        string result = rnd.Next(10000, 99999).ToString();

        // single random character in ascii range a-z
        string alphaChar = alphabet.Substring(rnd.Next(0, alphabet.Length-1),1);

        // random position to put the alpha character
        int replacementIndex = rnd.Next(0, (result.Length - 1));
        result = result.Remove(replacementIndex, 1).Insert(replacementIndex, alphaChar);

        return result;
    }
 
Leave a comment

Posted by on October 26, 2009 in Dot Net

 

Tags: , , ,

Extend session using javascript in c#

protected void Page_Load(object sender, EventArgs e)
{

int SessionTimeout = Session.Timeout;

StringBuilder d = new StringBuilder();
d.Append(“<script>\n”);
d.Append(“function BeforeTimeout()\n{\n”);
d.Append(“setTimeout(‘CheckSession()’,60000*” + Convert.ToString(SessionTimeout – 1) + “)\n}\n”);
d.Append(“\n”);
d.Append(“function CheckSession()\n{\n”);
d.Append(“var flag=confirm(‘Your session is about to expire. Do you want to extent it?’)\n”);
d.Append(“if (flag)\n{\n”);
d.Append(“window.location.href='” + Page.Request.Url + “‘\n}\n}\n”);
d.Append(“window.onload=BeforeTimeout \n”);
d.Append(“</script>\n”);

Header.InnerHtml = d.ToString();
//}
}

 
Leave a comment

Posted by on October 26, 2009 in Dot Net

 

Tags: , ,

Import Excel Data Into An ASP.NET GridView using OLEDB

using System.Data.OleDb;
using System.Data;

public partial class UploadD : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cnstr = “Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;”
+ “Extended Properties=Excel 8.0”;
OleDbConnection oledbConn = new OleDbConnection(cnstr);
string strSQL = “SELECT * FROM [Sheet$]”;

OleDbCommand cmd = new OleDbCommand(strSQL, oledbConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}

 
Leave a comment

Posted by on October 26, 2009 in Dot Net

 

Tags: , , ,

Generate thumbnail using dotnet

using System.Drawing;
using System.Drawing.Design;

Use the following code to create High Quality Thumbnail/Resize the image.

string originalFilePath = "C:\\originalimage.jpg"; //Replace with your image path
string thumbnailFilePath = string.Empty;
 
Size newSize = new Size(120,90); // Thumbnail size (width = 120) (height = 90)
 
using (Bitmap bmp = new Bitmap(originalFilePath))
{
    thumbnailFilePath = "C:\\thumbnail.jpg"; //Change the thumbnail path if you want
 
    using (Bitmap thumb = new Bitmap((System.Drawing.Image)bmp, newSize))
    {
        using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
        {
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
 
            //Set Image codec of JPEG type, the index of JPEG codec is "1"
            System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
 
            //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
            System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
            eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
 
            //Now draw the image on the instance of thumbnail Bitmap object
            g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
 
            thumb.Save(thumbnailFilePath, codec, eParams);
        }
    }
}
 
Leave a comment

Posted by on October 26, 2009 in Dot Net

 

Tags: , , , ,