January 2, 2007

Creating A Temp File In The Temporary directory

Use a specific file name in the temporary directory:
private readonly string testPath = 
    Path.Combine(Path.GetTempPath(), "TestSerializer.xml");
Create a temporary file name in the temporary directory but with a specified extension:
public static class PathClassExtender
{
  public static string GetTempFileName(string newExtension)
  {
    string res = Path.ChangeExtension(Path.GetTempFileName(), newExtension);
    return res;
  }
}
Sample usage:
string filename = PathClassExtender.GetTempFileName(".bat");
filename will get set to something like
"C:\Users\RB\AppData\Local\Temp\tmp517F.bat"

Controlling TextBox Character Input

Good set opf samples
/// <summary>
/// Ensure only alpha numeric characters and
/// backspace are acceptable characters for the Thingey
/// </summary>
/// <param name="sender"></param>
/// <param name="kpea"></param>
private void OnSomeTextBox_KeyPressEvent(object sender, 
    KeyPressEventArgs kpea)
{
    const char BACKSPACE = '\b';
    const char FULLSTOP = '.';
    if (textBox.Text.Length > 0) // AFter first character
    {
        if ( !Char.IsLetterOrDigit(kpea.KeyChar) && 
            (kpea.KeyChar != BACKSPACE) && 
            (kpea.KeyChar != FULLSTOP))
        { // input is not passed on to the control(TextBox)
            kpea.Handled = true; 
        }
    } // First character must be an alphabetic character
    else if (!Char.IsLetter(kpea.KeyChar)) 
    {
 // input is not passed on to the control(TextBox)
        kpea.Handled = true; 
    }
}

// Another example
    switch(kpea.KeyChar) 
    {  
        case 'a': 
        case 'b': 
        case 'c': 
        case '#': 
        case '*': 
        case '1': 
            e.Handled=true; //event is handled.
            this.errorProvider.SetError(this.textboxChars, 
               "not allowed chars: 'a','b','c','#','*','1'");
            this.statusBar.Text="not allowed char..."+e.KeyChar;
            break; 
       default:
            //clear error
            this.errorProvider.SetError(this.textboxChars, "");
            break;
    } //switch 


    private static class FilterCharacters
    {
        public static void FilterSample(TextBox tb, 
     KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            const char FULLSTOP = '.';
            const char HYPHEN = '-';
            const char UNDERSCORE = '_';
            if (tb.Text.Length > 0)
            {
                if (!Char.IsLetterOrDigit(kpea.KeyChar) && 
                    (kpea.KeyChar != BACKSPACE) && 
                    (kpea.KeyChar != FULLSTOP) &&
                    (kpea.KeyChar != HYPHEN) &&
                    (kpea.KeyChar != UNDERSCORE) )
                { // input is not passed on to the control(TextBox)
                    kpea.Handled = true; 
                }
            }// First character must be an alphabetic character
            else if (!Char.IsLetter(kpea.KeyChar)) 
            {// input is not passed on to the control(TextBox)
                kpea.Handled = true; 
            }
        }

        public static void NumericOnlyFilter(TextBox tb,
      KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            //const char FULLSTOP = '.';
            if (!Char.IsDigit(kpea.KeyChar) && 
                // If you want decimal numbers
                //(kpea.KeyChar != FULLSTOP) && 
                (kpea.KeyChar != BACKSPACE) ) 
            {
               kpea.Handled = true; 
            }
        }
    }

Creating A Hash Of A String

// A quick and simple implementation
public string HashString(string target)
{
    if ((target == null) || (target.Length == 0))
        return string.Empty;

    byte[] targetAsBytes = Encoding.UTF8.GetBytes(target);
    SHA1 sha1 = SHA1.Create();
    byte[] hash = sha1.ComputeHash(targetAsBytes);
    return Convert.ToBase64String(hash);
}

December 21, 2006

C++/CLI Quick Comparison with C#

The following table provides a summary of the most common constructs for quick reference.
Description C++/CLI C#
Allocate reference type ReferenceType^ h = gcnew ReferenceType; ReferenceType h = new ReferenceType();
Null reference ReferenceType^ h = nullptr; ReferenceType h = null;
Allocate value type ValueType v(3, 4); ValueType v = new ValueType(3, 4);
Reference type, stack semantics ReferenceType h; N/A
Calling Dispose method ReferenceType^ h = gcnew ReferenceType;

delete h;

ReferenceType h = new ReferenceType();

((IDisposable)h).Dispose();

Implementing Dispose method ~TypeName() {} void IDisposable.Dispose() {}
Implementing Finalize method !TypeName() {} ~TypeName() {}
Boxing int^ h = 123; object h = 123;
Unboxing int^ hi = 123;

int c = *hi;

object h = 123;

int i = (int) h;

Reference type definition ref class ReferenceType {};

ref struct ReferenceType {};

class ReferenceType {}
Value type definition value class ValueType {};

value struct ValueType {};

struct ValueType {}
Using properties h.Prop = 123;

int v = h.Prop;

h.Prop = 123;

int v = h.Prop;

Property definition property String^ Name
{
String^ get()
{
return m_value;
}
void set(String^ value)
{
m_value = value;
}
}
string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
Exposing an event TODO // expose the event
event System::EventHandler^ OnEventOccurrance;

//Fire the event
if (OnEventOccurrance != nullptr)
{
OnEventOccurrance(this, gcnew System::EventArgs());
}
Simple type methods, double example double.IsNaN(someDouble); double.NaN; System::Double::IsNaN(someDouble)
System::Double::NaN

December 1, 2006

Authentication and Authorisation in .NET

Detailed workshop on Principal Based security - Simple samples. Authentication is the part of verifying your identity. Authorization is determining whether or not a user has the permission to perform an action in the application. .NET framework provides access to the user through an identity and authorization access through a principal. Principal is (user or group of users) The framework provides two different types of principals, A Windows principal (WindowsPrincipal). It works against the underlying Windows OS A generic principal (GenericPrincipal). A principal and identity that is not bound to the underlying Windows user. + custom principal and identity by implementing the IPrincipal and IIdentity interface.

Reflection And Custom Attributes

Reasonable explanation of reflection Defining a custom class attribute
[AttributeUsage(AttributeTargets.Class)] // attribute is for classes only
public class CustomClassAttribute : System.Attribute
{
    private string m_Caption;
    public CustomClassAttribute(string caption)
    {
       m_Caption = caption;
    }

    public string Caption
    {
       get { return m_Caption; }
    }
}
Processing the Assembly to get the attributes
public void Discover()
{
    Type[] types = System.Reflection.
Assembly.GetExecutingAssembly().GetTypes();
    foreach (Type type in types) // Go over all the types
    {
      // Look for all types derived from BaseClass 
      if (type.BaseType == typeof(BaseClass)) 
      {
        // Look for the 'CustomClassAttribute' attributes on that type
        object[] attributes = 
type.GetCustomAttributes(typeof(CustomClassAttribute), false);
        if (attributes.Length > 0)
        {
          // iterate through the attributes, retrieving the 
          // properties
          foreach (Object attribute in attributes)
          {
            CustomClassAttribute fca = (CustomClassAttribute)attribute;
            DoSomething(type.FullName, fca.Caption);
            break;
          }
        }
      }
    }
}
The attribute is used like this
[CustomClass("Some caption")]
public class SomeClass : BaseClass 
{

...
}
For example, say you have some properties on a type that you wish to iterate through but you do not wish to get the Obsolete ones (marked using "[Obsolete]", then the code would be something like this:
Type type = typeof(MyXXXType);
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
    object[] attributes = prop.GetCustomAttributes(typeof(ObsoleteAttribute), false);
    if (attributes.Length > 0) // If property is marked as Obsolete then ignore it
        continue;

    // otherwise do something with the property
}

Converting an Integer to a string in Managed C++

String* msg;
msg = String::Format(S"b{0:X4}", __box(m_intValue));
OR
System::Int32 test = iExposureMS*1000; 
String* sst = String::Format("sst {0}", test.ToString());