Navigation

Search

Categories

On this page

FizzBuzz
Speed Testing Pattern
It's no longer hip to be square.
Checking for even 1 unread message Using Outlook as a client
Retrieve Messages from Exchange using VBScript
Indiana or Bust

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 120
This Year: 1
This Month: 0
This Week: 0
Comments: 40

Sign In
Pick a theme:

# Wednesday, April 18, 2007
Wednesday, April 18, 2007 9:05:04 AM (Mountain Daylight Time, UTC-06:00) ( )

Fizz, Buzz

for (int i = 1; i <= 100; i++) // Count from 1 to 100
{
  Console.WriteLine(
    String.Format("{0,3:d} {1}{2}",
    i, // Display the number
    (bool)(i%3!=0) ? "":"Fizz", // Display Fizz if divisible by 3
    (bool)(i%5!=0) ? "":"Buzz") // Display Buzz if divisible by 5
  );
}

Comments [0] | | # 
Wednesday, April 18, 2007 8:36:40 AM (Mountain Daylight Time, UTC-06:00) ( )

I do not remember where I found this. I like it though. Props to whoever did this.

using System;
using System.Diagnostics;

public class TestHarness
{
private static Stopwatch _watch;
public static int algo = 0;
public TestHarness()
{
_watch = new Stopwatch();
}
public static long RunTest(int test)
{
if (_watch == null)
_watch = new Stopwatch();
string str = string.Empty;
switch (test)
{
case 1:
_watch.Start();
str = String.Empty;
for (int i = 0; i < 10000; i++)
{
str = str + "blue_toothbrush";
}
_watch.Stop();
break;
case 2:
_watch.Start();
System.Text.StringBuilder SB =
new System.Text.StringBuilder(String.Empty);
for (int i = 0; i < 10000; i++)
{
str = str + "blue_toothbrush";
}
_watch.Stop();
break;
default:
break;
}

long elapsed = _watch.ElapsedMilliseconds;
_watch.Reset();
return elapsed;
}
}


class Program {
public static int Main(string[] args)
{
long elapsed = 0;
for (TestHarness.algo = 1; TestHarness.algo <= 2; TestHarness.algo++)
{
Console.WriteLine("Commencing test of algo {0}", TestHarness.algo);
elapsed = TestHarness.RunTest(TestHarness.algo);
Console.WriteLine("Test of algo {0} took {1:#.00} seconds", TestHarness.algo, (double)elapsed/1000);
}
return 0;
}
}

Comments [0] | | # 
# Monday, April 09, 2007
Monday, April 09, 2007 9:28:29 AM (Mountain Daylight Time, UTC-06:00) ( )

Jeffs at SQL Team is my hero.

What do you do with something like this? It was found because of it broke a dump to a text file for moving to a different database. You end up with this.\

"foo

foo"

Those non-printing characters, or squares, cause all kinds of problems if you're not expecting them.

I have no control over what front-end people are using to get this into my database, or do I...

A check constraint would have stopped these nefarious character codes dead in their tracks, and will certainly put the axe on any more sneaking into my database. How do I express that I just don't want certain characters in my database?

Better get some help here. SQL Books Online, check constraints, use the like operator, ranges, got it. Wait. Don't go it.

SQLTeam.com to the rescue. Find a victim, er, helpful pal to make friends with. Great. Write a question, check. Get a response. Fine. http://weblogs.sqlteam.com/jeffs/archive/2007/04/05/check-constraints.aspx

Here's the rub though. Little did I know that a "Range" in the "Like" operator uses character attributes. If you've done any work with System.Char in the .Net framework, it will clearly show what I mean.

Final solution - Check Column Not Like '%[ -~a-z0-9]%' -- three ranges, symbols, letters, numbers.

This reminded me of some certain methods in the System.Char structure.

You know, the ones like, IsLetter, IsCharacter, IsNumber, IsSymbol...

So, says I, why not run down the list and show those...

const char sepchar = ',';
for (int i = 0; i < 256; i++)
{
	b.Append(Char.IsControl(c)); b.Append(sepchar);
	b.Append(Char.IsDigit(c)); b.Append(sepchar);
	b.Append(Char.IsHighSurrogate(c)); b.Append(sepchar);
	b.Append(Char.IsLetter(c)); b.Append(sepchar);
	b.Append(Char.IsLetterOrDigit(c)); b.Append(sepchar);
	b.Append(Char.IsLower(c)); b.Append(sepchar);
	b.Append(Char.IsLowSurrogate(c)); b.Append(sepchar);
	b.Append(Char.IsNumber(c)); b.Append(sepchar);
	b.Append(Char.IsPunctuation(c)); b.Append(sepchar);
	b.Append(Char.IsSeparator(c)); b.Append(sepchar);
	b.Append(Char.IsSurrogate(c)); b.Append(sepchar);
	b.Append(Char.IsSymbol(c)); b.Append(sepchar);
	b.Append(Char.IsUpper(c)); b.Append(sepchar);
	b.Append(Char.IsWhiteSpace(c));
	Console.WriteLine(b.ToString());
}

But, thats kinda lame. Why not flex those programmer muscles, and prove we know some stuff. It's not always more efficient, but it's certainly elegant, and impresses the kids. Read the comments. It's all good stuff.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;

namespace CharAttributes
{
    class Program
    {
        
        static void Main(string[] args)
        {
            char objTest = new char();
            Type objType = objTest.GetType();
            const char sepchar = ',';
            _MemberInfo[] arrayIMemberInfo;
            
            #region nonPrintingNames
            string[] nonPrintingNames = new string[]{
                "(null)",
                "(start of heading)",
                "(start of text)",
                "(end of text)",
                "(end of transmission)",
                "(enquiry)",
                "(acknowledge)",
                "(bell)",
                "(backspace)",
                "(horizontal tab)",
                "(ML line feed; new line)",
                "(vertical tab)",
                "(NP form feed; new page)",
                "(carriage return)",
                "(shift out)",
                "(shift in)",
                "(data link escape)",
                "(device control 1)",
                "(device control 2)",
                "(device control 3)",
                "(device control 4)",
                "(negative acknowledge)",
                "(synchronous idle)",
                "(end of trans. block)",
                "(cancel)",
                "(end of medium)",
                "(substitute)",
                "(escape)",
                "(file separator)",
                "(group separator)",
                "(record separator)",
                "(unit separator)",
                };
            #endregion

            try
            {
                //Find all static or public methods in the Object class that match the specified searchCriteria.
                // In our case, we want all of the public static instance methods of the Char struct
                // We're also going to use the DeletgateToSearchCriteria delegate to do some additonal filtering
                arrayIMemberInfo = objType.FindMembers(MemberTypes.Method,
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                    new MemberFilter(DelegateToSearchCriteria), null);
                int methodCount = arrayIMemberInfo.Length;
                // Build the header
                StringBuilder header = new StringBuilder();
                // Append first two rows
                header.Append("value");         header.Append(",");
                header.Append("character");     header.Append(",");
                int arrayLen = arrayIMemberInfo.Length;
                // Append the names of the Methods
                for (int i = 0; i < arrayLen; i++)
                {
                    header.Append(arrayIMemberInfo[i].Name);
                    if (i != arrayLen - 1)
                    {
                        header.Append(",");
                    }
                }
                // Print the headers
                Console.WriteLine(header.ToString());

                // Use the methods we found earlier and 
                // invoke them on the range of ASCII characters
                for (int i = 0; i < 256; i++)
                {
                    StringBuilder line = new StringBuilder();
                    // append the value
                    line.Append(i); line.Append(sepchar);
                    // append the actual character
                    if (i < 32)
                        line.Append(nonPrintingNames[i]);
                    else
                        line.Append((char)i);
                    
                    line.Append(sepchar);

                    for (int j = 0; j < methodCount; j++)
                    {
                        MethodInfo m = (MethodInfo)arrayIMemberInfo[j];
                        line.Append((bool)m.Invoke(null, new object[1] { (char)i }));
                        if (j != methodCount - 1)
                        {
                            line.Append(",");
                        }
                    }
                    Console.WriteLine(line.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception : " + e.ToString());
            }

        }
        public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object objSearch)
        {
            MethodInfo m = (MethodInfo)objMemberInfo;
            ParameterInfo[] p = m.GetParameters();
            if (p.Length == 1) // one and only one parameter
            {
                if ((p[0].ParameterType == Type.GetType("System.Char")) && // parameter of type System.Char
                    Regex.IsMatch(m.Name, "^Is") && // Method name begins with Is
                    m.ReturnType == Type.GetType("System.Boolean")) // Returns a System.Boolean
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}
Comments [0] | | # 
Monday, April 09, 2007 8:03:47 AM (Mountain Daylight Time, UTC-06:00) ( All things Microsoft )

If Not InStr(1, WScript.Fullname, "cscript.exe") = 0 Then
 Dim WshShell
 Set WshShell = WScript.CreateObject("WScript.Shell")
 Call WshShell.Popup("Use this syntax: cscript " & WScript.ScriptFullName, 5, "Error", 0)
 WScript.Quit
End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const olFolderInbox = 6

Dim myolApp 'As Outlook.Application
Dim myNamespace 'As Outlook.NameSpace
Dim myInbox ' As MAPIFolder
Dim sycs 'As Outlook.SyncObjects
Dim syc 'As Outlook.SyncObject

' Setup Outlook
Set myolApp = CreateObject("Outlook.Application")
If Err Then
    WScript.StdOut.Writeline "Could not create Outlook Application!"
    WScript.Quit
End If

' Setup the default MAPI namespace
Set myNamespace = myolApp.GetNamespace("MAPI")
If Err Then
    WScript.StdOut.Writeline "Could not create MAPI Namespace!"
    WScript.Quit
End If

' Force a send/receive
' Start Syncing (send/receive groups)
Set sycs = myNamespace.SyncObjects
For i = 1 To sycs.Count
 Set syc = sycs.Item(i)
 WScript.StdOut.Writeline "Starting send/receive on " & syc.Name
 syc.Start
Next

WScript.StdOut.Writeline "Retreiving unread count"
Set myInbox = myNamespace.GetDefaultFolder(olFolderInbox)

WScript.StdOut.Writeline "There are " & myInbox.UnReadItemCount & " unread messages"
WScript.Quit myInbox.UnReadItemCount

' Return code == 0 means there is no unread mail.
' Return code != 0 means there is that many read mail.

Comments [0] | | # 
Monday, April 09, 2007 8:00:21 AM (Mountain Daylight Time, UTC-06:00) ( )

This uses a Dynamic Profile (MAPI profiles are a pain). This is using the CDO 1.21 (Outlook) object model.

On Error Resume Next

Public Sub ShowUndreadMessages(server, mailbox)
 
   Dim objSess, objInbox, objMsgColl, objMsgFilter
   Dim objMess

   Set objSess = CreateObject("MAPI.Session")

   strProfileInfo = server & vbLf & mailbox
   objSess.Logon , , False, True, , False, strProfileInfo

   Set objInbox = objSess.Inbox
   If objInbox Is Nothing Then
      MsgBox "Invalid IPM Inbox from session"
      Exit Sub
   End If
  
   Set objMsgColl = objInbox.Messages ' get Inbox’s messages collection
   ' ( ... then validate the messages collection before proceeding ... )
  
   Set objMsgFilter = objMsgColl.Filter
   ' ( ... then validate the message filter before proceeding ... )
  
   objMsgFilter.Unread = false ' filter for unread messages

   ' Message filter is now specified; ready for display loop
   For Each objMess in objMsgColl ' performs loop, Sets each objMess
      WScript.Echo _
      "Inbox" & vbTab & _
      objMess.Subject & vbTab & _
      objMess.ReceivedTime
   Next ' even easier than objMsgColl.GetFirst and .GetNext

   objSess.Logoff
  

End Sub

ShowUndreadMessages "ExchangeServer","mailbox.name@domain.tld"

 

Comments [0] | | # 
Monday, April 09, 2007 7:50:18 AM (Mountain Daylight Time, UTC-06:00) ( Musings )

Drove to Indiana this weekend to move Adam.

Things I learned.

  1. A rubber mallet can be used in place of a leaf-spring on a small trailer, sometimes to greater affect.
  2. Quality Inn feels great after an 8 hour day at work and 10 hours on the road.
  3. Continental breakfasts should have a better way to describe how much you should really eat.
  4. Indiana has amazing cathedral pine forests, very Narnia-ish.
  5. My (now ex) roomie couldn't be happier living as close as he is to his amazing girl, I wish them both the best.

 

Comments [0] | | #