Joseph Michael Pesch
VP Programming

C# Convert Enum Array Into Typed Array Used in LINQ to SQL IN Query

by 30. March 2009 17:22

http://stackoverflow.com/questions/472384/convert-an-array-of-enum-to-an-array-of-int

http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/

The example below take an enum array input variable, converts to an integer array variable for use in a LINQ to SQL IN clause type query:

    public enum FlagTypeCode
    {
      NotAssigned = 0,
      SendToServicerBlocked = 100,
      SelectedForQCReview = 200
    }
    public static IQueryable<ModFlagDate> LoadModFlagDate(FlagTypeCode[] FlagTypeCodeList, ref string ErrorMessage)
    {
      int[] FlagTypeList = Array.ConvertAll(FlagTypeCodeList, value => (int) value);
      ModCalcDataContext db = new ModCalcDataContext();
      var rows = (from row in db.ModFlagDates
                        where FlagTypeList.Contains(row.FlagTypeCode)
                        select row);
      return rows;
    }

Tags: ,

C# | LINQ to SQL

C# System.Drawing.Color from HTML Color String

by 23. March 2009 20:20

System.Drawing.Color OrangeColor = System.Drawing.ColorTranslator.FromHtml("#CE56CC");

You can also translate colors without the ColorTranslator class (which may be useful if you are using the Compact Framework).

System.Drawing.Color only supports creating custom colors using it's FromArgb method, which requires base-10 inputs. Therefore, two conversion functions are needed - a conversion from decimal to hexadecimal, and a conversion from a 6 character string to three numeric parts (one each for red, green, and blue).

Source CodeThe first function handles the safe conversion of a hexadecimal (base-16) number to decimal (base-10).

1protected int HexStringToBase10Int(string hex)
2...{
3    int base10value = 0;
4
5    try   ...{ base10value = System.Convert.ToInt32(hex, 16); }
6    catch ...{ base10value = 0; }
7
8    return base10value;
9}

The next function breaks the hexadecimal string into parts, removes a leading # (so you can pass it #FF00FF or FF00FF with the same result), and then converts the hexadecimal parts into decimal, and creates a color using the red, green, and blue value integers.

 1protected System.Drawing.Color HexStringToColor(string hex)
 2...{
 3    hex = hex.Replace("#", "");
 4
 5    if (hex.Length != 6)
 6        throw new Exception(hex +
 7            " is not a valid 6-place hexadecimal color code.");
 8
 9    string r, g, b;
10
11    r = hex.Substring(0, 2);
12    g = hex.Substring(2, 2);
13    b = hex.Substring(4, 2);
14
15    return System.Drawing.Color.FromArgb(HexStringToBase10Int(r),
16                                         HexStringToBase10Int(g),
17                                         HexStringToBase10Int(b));
18}

from: http://www.akxl.net/labs/articles/converting-a-hexadecimal-color-to-a-system.drawing.color-object/

Tags: ,

C#

Declarative Security Checks for User Name and/or Role Permission

by 6. January 2009 18:46

[PrincipalPermissionAttribute(SecurityAction.Demand, Name =  "UserName", Role = "UserRole")]
publicstaticvoid SecurityTestEntryPoint(bool flag)
{
  if (flag)
  {
    // This is more secure code...

    SecurityTest(flag, "");
  }
  else

  {
    // This is less secure code...

    SecurityTest(flag);
  }
}
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "ManagerRole")]
publicstaticvoid SecurityTest(bool flag, string MoreSecure)
{
  // This is more secure code...

}
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "ManagerRole")]
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "UserRole")]
publicstaticvoid SecurityTest(bool flag)
{
  // This is less secure code...

}

NOTE: You can stack multiple attributes for an OR condition, however, you cannot create an AND condition. As in the example above the less secure method will let both "ManagerRole" users and "UserRole" users access itself.

Topic Links:

http://msdn.microsoft.com/en-us/library/dswfd229(VS.71).aspx

http://bytes.com/groups/net-c/267605-cas-multiple-permissions

 

Tags: ,

C# | Security

Get System Font List in C# Using Shell32.dll

by 31. December 2008 16:06

Creates a key/value dictionary of FontName/FontFile from the system fonts.  Also, contains a method to that accepts an output path which will be filled with image files (.png format) of sample text of each of the fonts. 

Original source of API code: http://blog.debreuil.com/archive/2007/05/31/5108.aspx

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
 
// Call the FontUtil.FontTool.BuildSampleFontImages() to generate sample image files of the fonts.
 
/*
 // Sample usage:
   FontUtil.FontList fnt = FontUtil.FontList.GetInstance();
   IEnumerator en = fnt.FontMap.GetEnumerator();
   while (en.MoveNext())
   {
     string FontName = ((System.Collections.Generic.KeyValuePair<string, string>)en.Current).Key;
     string FontFile = ((System.Collections.Generic.KeyValuePair<string, string>)en.Current).Value;
   }
 */
 
namespace FontUtil
{
   public static class FontTool
   {
     public static void BuildSampleFontImages(string OutputPath)
     {
      
       // The output path will be filled with image files (.png format) of sample text
       // of each of the fonts in the system that don't contain the words " bold" or " italic"
       // Also, checks after setting the since some of the fonts don't seem to register (see "Font Error" section).
       // NOTE: It will delete any existing image file with the same name before creating the new image.
 
       Font font = new Font("Times", 20);
       string FilePath = OutputPath;
 
       FontUtil.FontList fnt = FontUtil.FontList.GetInstance();
       IEnumerator en = fnt.FontMap.GetEnumerator();
       while (en.MoveNext())
       {
         string text = ((System.Collections.Generic.KeyValuePair<string, string>)en.Current).Key;
         try
         {
           // Skip bold and/or italic versions of the fonts.
           if (text.ToLower().Contains(" bold") || text.ToLower().Contains(" italic"))
             continue;
           font = new Font(text, 12);
           if (font.FontFamily.Name.ToLower() != text.ToLower())
           {
             System.Diagnostics.Debug.WriteLine("Font Error: " + text);
             continue;
           }
           FilePath = System.Web.HttpContext.Current.Server.MapPath("") + @"\images\fonts\" + text.Replace(" ", "_") + ".png";
           text += (char)10 + "1234567890";
           text += (char)10 + "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.";
           text += (char)10 + "The quick brown fox jumps over the lazy dog.";
           CreateTextImage(text, font, FilePath);
         }
         catch (Exception ex)
         {
           System.Diagnostics.Debug.WriteLine(ex.Message);
         }
       }
 
     }
     private static void CreateTextImage(string text, Font font, string FilePath)
     {
       Graphics g = Graphics.FromImage(new Bitmap(10, 10));
       SizeF sf = g.MeasureString(text, font);
       Bitmap bmp = new Bitmap(Convert.ToInt16(sf.Width), Convert.ToInt16(sf.Height));
 
       g = Graphics.FromImage(bmp);
       StringFormat strFormat = new StringFormat();
       strFormat.Alignment = StringAlignment.Center;
       strFormat.LineAlignment = StringAlignment.Center;
       // Color bgColor = Color.FromArgb(50, Color.Black); // 50% transparent black
       Color bgColor = Color.Transparent;
       g.FillRectangle(new SolidBrush(bgColor), 0, 0, Convert.ToInt16(sf.Width), Convert.ToInt16(sf.Height));
       g.DrawString(text, font, Brushes.Black,
        new RectangleF(0, 0, sf.Width, sf.Height), strFormat);
       g.Save();
 
       File.Delete(FilePath);
       bmp.Save(FilePath, ImageFormat.Png);
 
     }
 
   }
 
   public class FontList
   {
     public Dictionary<string, string> FontMap = new Dictionary<string, string>();
 
     private static FontList inst;
     private FontList()
     {
     }
 
     public static FontList GetInstance()
     {
       if (inst == null)
       {
         inst = new FontList();
         inst.GetAllFonts();
       }
       return inst;
     }
 
     private void GetAllFonts()
     {
       //string fp = Environment.GetFolderPath((Environment.SpecialFolder) 0x14);//CSIDL_FONTS = 0x0014
 
       StringBuilder sb = new StringBuilder();
       SHGetFolderPath(IntPtr.Zero, 0x0014, IntPtr.Zero, 0x0000, sb);//CSIDL_FONTS = 0x0014
       string fontDir = sb.ToString();
 
       if (!Directory.Exists(fontDir))
       {
         return;
       }
       string[] fonts = Directory.GetFiles(fontDir);
       for (int i = 0; i < fonts.Length; i++)
       {
         string name = GetFontName(fonts[i]);
         if (name != "")
         {
           FontMap.Add(name, fonts[i]);
         }
       }
     }
 
 
     private TT_OFFSET_TABLE ttResult;
     private TT_TABLE_DIRECTORY tbName;
     private TT_NAME_TABLE_HEADER ttNTResult;
     private TT_NAME_RECORD ttNMResult;
 
     private string GetFontName(string fontPath)
     {
       string result = "";
 
       FileStream fs = new FileStream(fontPath, FileMode.Open, FileAccess.Read);
       BinaryReader r = new BinaryReader(fs, Encoding.UTF8);
       byte[] buff = r.ReadBytes(Marshal.SizeOf(ttResult));
       buff = BigEndian(buff);
       IntPtr ptr = Marshal.AllocHGlobal(buff.Length);
       Marshal.Copy(buff, 0x0, ptr, buff.Length);
       ttResult = (TT_OFFSET_TABLE)Marshal.PtrToStructure(ptr, typeof(TT_OFFSET_TABLE));
       Marshal.FreeHGlobal(ptr);
 
       //Must be maj =1 minor = 0
       if (ttResult.uMajorVersion != 1 || ttResult.uMinorVersion != 0)
         return "";
 
       bool bFound = false;
       tbName = new TT_TABLE_DIRECTORY();
       for (int i = 0; i < ttResult.uNumOfTables; i++)
       {
         byte[] bNameTable = r.ReadBytes(Marshal.SizeOf(tbName));
         IntPtr ptrName = Marshal.AllocHGlobal(bNameTable.Length);
         Marshal.Copy(bNameTable, 0x0, ptrName, bNameTable.Length);
         tbName = (TT_TABLE_DIRECTORY)Marshal.PtrToStructure(ptrName, typeof(TT_TABLE_DIRECTORY));
         Marshal.FreeHGlobal(ptrName);
         string szName =
           tbName.szTag1.ToString() +
           tbName.szTag2.ToString() +
           tbName.szTag3.ToString() +
           tbName.szTag4.ToString();
         if (szName != null)
         {
           if (szName.ToString() == "name")
           {
             bFound = true;
             byte[] btLength = BitConverter.GetBytes(tbName.uLength);
             byte[] btOffset = BitConverter.GetBytes(tbName.uOffset);
             Array.Reverse(btLength);
             Array.Reverse(btOffset);
             tbName.uLength = BitConverter.ToUInt32(btLength, 0);
             tbName.uOffset = BitConverter.ToUInt32(btOffset, 0);
             break;
           }
         }
       }
       if (bFound)
       {
         fs.Position = tbName.uOffset;
         byte[] btNTHeader = r.ReadBytes(Marshal.SizeOf(ttNTResult));
         btNTHeader = BigEndian(btNTHeader);
         IntPtr ptrNTHeader = Marshal.AllocHGlobal(btNTHeader.Length);
         Marshal.Copy(btNTHeader, 0x0, ptrNTHeader, btNTHeader.Length);
         ttNTResult = (TT_NAME_TABLE_HEADER)Marshal.PtrToStructure(ptrNTHeader, typeof(TT_NAME_TABLE_HEADER));
         Marshal.FreeHGlobal(ptrNTHeader);
         bFound = false;
         for (int i = 0; i < ttNTResult.uNRCount; i++)
         {
           byte[] btNMRecord = r.ReadBytes(Marshal.SizeOf(ttNMResult));
           btNMRecord = BigEndian(btNMRecord);
           IntPtr ptrNMRecord = Marshal.AllocHGlobal(btNMRecord.Length);
           Marshal.Copy(btNMRecord, 0x0, ptrNMRecord, btNMRecord.Length);
           ttNMResult = (TT_NAME_RECORD)Marshal.PtrToStructure(ptrNMRecord, typeof(TT_NAME_RECORD));
           Marshal.FreeHGlobal(ptrNMRecord);
 
           // this is where the font name is recovered
           // to get the font family name (not incl 'bold' etc) use ttNMResult.uNameID == 1
           // see http://www.microsoft.com/OpenType/OTSpec/name.htm
           if (ttNMResult.uNameID == 4)
           {
             long fPos = fs.Position;
             fs.Position = tbName.uOffset + ttNMResult.uStringOffset + ttNTResult.uStorageOffset;
             char[] szResult = r.ReadChars(ttNMResult.uStringLength);
             if (szResult.Length != 0)
             {
               // some fonts are \0 A \0 r \0 i \0 a \0 l.... UTf8 encoding doesn't help
               if (szResult[0] == '\0')
               {
                 int count = 0;
                 char[] temp = new char[szResult.Length / 2];
                 for (int j = 1; j < szResult.Length; j += 2)
                 {
                   temp[count++] = szResult[j];
                 }
                 szResult = temp;
               }
               result = new String(szResult);
               break;
             }
           }
         }
       }
       return result;
     }
     private byte[] BigEndian(byte[] bLittle)
     {
       byte[] bBig = new byte[bLittle.Length];
       for (int y = 0; y < (bLittle.Length - 1); y += 2)
       {
         byte b1, b2;
         b1 = bLittle[y];
         b2 = bLittle[y + 1];
         bBig[y] = b2;
         bBig[y + 1] = b1;
       }
       return bBig;
     }
 
     [DllImport("shell32.dll")]
     static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken,
      uint dwFlags, [Out] StringBuilder pszPath);
 
     [StructLayout(LayoutKind.Sequential, Pack = 0x1)]
     struct TT_OFFSET_TABLE
     {
       public ushort uMajorVersion;
       public ushort uMinorVersion;
       public ushort uNumOfTables;
       public ushort uSearchRange;
       public ushort uEntrySelector;
       public ushort uRangeShift;
 
     }
     [StructLayout(LayoutKind.Sequential, Pack = 0x1)]
     struct TT_TABLE_DIRECTORY
     {
       public char szTag1;
       public char szTag2;
       public char szTag3;
       public char szTag4;
       public uint uCheckSum; //Check sum
       public uint uOffset; //Offset from beginning of file
       public uint uLength; //length of the table in bytes
     }
     [StructLayout(LayoutKind.Sequential, Pack = 0x1)]
     struct TT_NAME_TABLE_HEADER
     {
       public ushort uFSelector;
       public ushort uNRCount;
       public ushort uStorageOffset;
     }
     [StructLayout(LayoutKind.Sequential, Pack = 0x1)]
     struct TT_NAME_RECORD
     {
       public ushort uPlatformID;
       public ushort uEncodingID;
       public ushort uLanguageID;
       public ushort uNameID;
       public ushort uStringLength;
       public ushort uStringOffset;
     }
 
   }
 

}

Tags: ,

C# | Windows

C# Gridview History Highlight Example

by 16. December 2008 14:52

This sample loads a GridView and performs the two functions shown below.  The first function is simply to make the column labels more user friendly by adding spaces.  The second function is relevant to the historical aspect of the data being viewed.  It was intended as a method to load a grid of audit trail type changes to a single record.  The comparison will then highlight changed values so they stand out visually against the unchanged values.

  1. Performs a string replacement on the column names, putting spaces at every captial letter. For example: "ThisColumnName" would be converted to "This Column Name".
  2. Performs a column-by-column record comparison of the current row in the GridView (using a RegEx function) against the next row in the DataTable, and if the values don't match the GridView column is highlighted yellow. Note: It is best presented with newest records on top.

GridViewHistoryHighlight.zip (5.57 kb)

Tags:

ASP.Net | C#

C# Regular Expression (RegEx) Samples

by 11. December 2008 18:57
using System;
using System.Text.RegularExpressions;

namespace RegExSamples
{
  class Program
  {
    static void Main(string[] args)
    {
      string result;
      // Replace each new word with uppercase.
      result = Regex.Replace("four score and seven years ago", @"\w+", new MatchEvaluator(CapText));
      Console.WriteLine(result);
      // Add a space before every capital letter.
      result = Regex.Replace("ThisIsAnotherTest", @"[A-Z]", new MatchEvaluator(PrefixSpace));
      Console.WriteLine(result);
      Console.Read();
    }
    static string CapText(Match m)
    {
      // Get the matched string.
      string x = m.ToString();
      // If the first char is lower case...
      if (char.IsLower(x[0]))
      {
        // Capitalize it.
        return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
      }
      return x;
    }
    static string PrefixSpace(Match m)
    {
      string x = m.ToString();
      return " " + x;
    }
  }
}

Tags:

C#

C# Create a String of Repeating Charcters

by 9. December 2008 17:56

newstring('x', 50);

 

Tags:

C#

C# Get Virtual Root Path of File System Web Site

by 8. December 2008 20:41

RootPath = newString('/', Request.Path.Replace(Request.ApplicationPath, "").Split('/').Length - 2).Replace("/", "../");

 

Tags:

ASP.Net | C#

C# convert ArrayList into delimited string

by 14. October 2008 13:47

System.Collections.ArrayList myArrayList = new System.Collections.ArrayList();
for(int i = 0; i < 10; i++)
{
  myArrayList.Add(i.ToString());
}
string myDelimeter = ",";
string myDelimitedList = string.Join(myDelimiter, (string[])myArrayList.ToArray(typeof(string)));
System.Diagnostics.Debug.WriteLine(string);
// output would be: "1,2,3,4,5,6,7,8,9"

Tags:

C#