Locations of visitors to this page
    Sprouting Synapses       Minimize  

             
            Minimize  
Author: SkySigal Created: 2/21/2008 9:28 PM
.NET:C#

By SkySigal on 9/29/2008 1:34 AM

Interesting:

Performance
In terms of raw performance, the .NET Remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In almost all the tests that we carried out to compare the relative performance of ASP.NET Web services and .NET Remoting, ASP.NET Web services outperformed .NET Remoting endpoints that used the SOAP formatter with either the HTTP or the TCP channel. More interestingly, ASP.NET and .NET Remoting endpoints that used the binary formatter and the HTTP channel were very similar in performance. (See Performance Comparison: .NET Remoting vs. ASP.NET Web Services for more details.)

Links:

powered by metaPost

By SkySigal on 9/19/2008 1:41 PM

I'm starting to really love QuickSharp (by Steve Walker) which is a very light IDE for coding .NET.

Its the right mid-point between CSScript (missing an editor) and Visual Studio (too heavy of an editor).

Especially that there's a new version out (1.3) available at http://sourceforge.net/projects/quicksharp/

 

But I just ran into a spot of trouble getting a SourceTrace to work...nothing was coming out, whereas the same code worked fine in Visual Studio.

 

The Trace Flag
Its easy to forget after a while that Tracing only works in Visual Studio, because Visual Studio sets the TRACE flag for both Debug and Release builds, by default.
Whereas with QuickSharp, out of the box, has no flags defined for the compiler...including TRACE.

Easy Fix

It's a small gotcha...but the good news is that QuickSharp is becoming very configurable, and you can easily solve this, as demonstrated in the image below (click to enlarge):

image

powered by metaPost

By SkySigal on 9/18/2008 11:37 PM

When dealing with Providers (another subject all together) and other means of configuring a software from an XML or other file source a lot of times you have to have convert a string to typed value.

It always starts off relatively easy -- but its not long before you start having to make all kinds of try/catches to handle conversions that didn't work, etc.

One of the main areas of trouble I ran into several times before I hacked out the following code, was handling the conversion of strings to Value Types and Reference Types, and handling the scenarios differently.

And the problem was acerbated when porting the software to PC (yes, I did write a whole DbDataFactory, AppSettings, and the Provider/Manager architecture to the Compact Framework) because the full framework's  TypeConverter class was not available.

The solution, with throwing in a little generics became the following:

 

/// <summary>
/// Class of static methods to work with System.Type.
/// </summary>
public static class Types {
  
  /// <summary>
  /// Helper method to convert a type to another type.
  /// Note how this is slightly better than the traditional
  /// 'ConvertTo' method, which returns all as an object that 
  /// then needs to be boxed.
  /// </summary>
  /// <remarks>
  /// <para>
  /// Can accept <c>null</c> and <c>DbNull.Value</c> 
  /// (returns <c>null</c>).
  /// </para>
  /// <para>
  /// Note: 
  /// Converts Guid using ToString("D") format, 
  /// and can recreate Guid from string
  /// in all Formats.
  /// </para>
  /// </remarks>
  /// <param name="value">The value.</param>
  /// <returns></returns>
  public static TOut ConvertTo<TIn, TOut>(TIn value) {
    return (TOut)ConvertTo(value, typeof(TOut));
  }

  /// <summary>
  /// Converts a value from given type to a destination type.
  /// </summary>
  /// <remarks>
  /// <para>
  /// Can accept <c>null</c> and <c>DbNull.Value</c> 
  /// (returns <c>null</c>).
  /// </para>
  /// <para>
  /// Note: 
  /// Converts Guid using ToString("D") format, 
  /// and can recreate Guid from string
  /// in all Formats.
  /// </para>
  /// </remarks>
  /// <param name="value">The value to convert.</param>
  /// <returns>The value converted to the destination type.</returns>
  public static destinationT ConvertTo<destinationT>(object value) {
    return (destinationT)ConvertTo(value, typeof(destinationT));
  }


  /// <summary>
  /// Converts a value from given type to a destination type.
  /// </summary>
  /// <remarks>
  /// <para>
  /// Can accept <c>null</c> and <c>DbNull.Value</c> 
  /// (returns <c>null</c>).
  /// </para>
  /// <para>
  /// Note: 
  /// Converts Guid using ToString("D") format, 
  /// and can recreate Guid from string
  /// in all Formats.
  /// </para>
  /// </remarks>
  /// <param name="value">The value to convert.</param>
  /// <param name="destinationType">The destination Type wanted.</param>
  /// <returns>The value converted to the destination type.</returns>
  public static object ConvertTo(object value, Type destinationType) {

    if ((value == null) || (value == DBNull.Value)) {
      //The pre-generics equivalent of default(T):
      //Remark: strings are not ValueType, so are returned as null.
      //Remark: Guid are ValueType, so are returned as Guid.Empty.
      //Remark: int are ValueType, so are returned as Int32.Empty.
      return (destinationType.IsValueType) ? 
        System.Activator.CreateInstance(destinationType) 
        :
        null;
    }

    //Value is not null, so safe to get type:
    Type srcType = value.GetType();

    if (srcType == typeof(string)){
          if (destinationType == typeof(string)) {
            //Don't change the normal behavior then...
            //AND 
            //Might as well get out early...
            return value;
          }
        if (string.IsNullOrEmpty((string)value)) {
          //Empty string... Hum...
          //But being converted to a string, or something else?
            //But if going to be converted........
            //Much better results to let it decide from a null, 
            //rather than choke on an empty string:
            value = null;
          }
        else{
            //we know its not going to be a string
            //so trim it:
            value = ((string)value).Trim();
        }
    }


#if (!CE) && (!PocketPC) && (!pocketPC) && (!WindowsCE)
    //PC:
    //Unfortunately TypeConverter is not on CF...

    TypeConverter tc =
      TypeDescriptor.GetConverter(destinationType);


    if (tc.CanConvertFrom(srcType)) {
      try {
        return tc.ConvertFrom(value);
      }
      catch {
        return (destinationType.IsValueType) 
        ? 
        System.Activator.CreateInstance(destinationType) 
        : 
        null;
      }
    }

    tc = TypeDescriptor.GetConverter(srcType);

    if (tc.CanConvertTo(destinationType)) {
      return tc.ConvertTo(value, destinationType);
    }
#endif

    try {
      return System.Convert.ChangeType(
          value, 
          destinationType, 
          null);
    }
    catch {
    }

    //Ok  so we failed doing it the simplest way...
    //But is there a constructor that we can use?
    //For example, Version (which is a class) 
    //can take a string arg:
    System.Reflection.ConstructorInfo constructorInfo =
      destinationType.GetConstructor(new Type[] { srcType });
    if (constructorInfo != null) {
      try {
        return constructorInfo.Invoke(new object[] { value });
      }
      catch {
      }
    }
    return (destinationType.IsValueType) 
        ? 
        System.Activator.CreateInstance(destinationType) 
        : 
        null;

    //return System.Convert.ChangeType(
//        value, 
 //       destinationType, 
   //     null);
  }
}//Class:End

With the above solution, it becomes child's play to import settings from eg: configurationElement attributes and convert them to Typed objects, without throwing exceptions.

 

[ADDENDUM]

I had better make this a bit clearer by showing inputs, and their outcome.

Things to notice are:

  • Doesn't crash and burn on reading arguments that are empty strings
  • Trims string inputs as necessary, leaving one less thing to worry about when reading from config files that end users could damage...
  • The result Type is either Null, or going to be in the right Type... Nice.
  • Handles Enums (note if given buncus, defaults to the first entry...which may or may not be the Default value...up to you to handle that)

 

public enum Stuff {
 One, 
 Two, 
 Three
}

class Program
{
 static void Main()
 {
  try
  {
   List<object[]> argsAll = new List<object[]>();
   argsAll.Add(null);
   argsAll.Add(new object[] {typeof(int),null});
   argsAll.Add(new object[] {typeof(int),DBNull.Value});
   argsAll.Add(new object[] {typeof(int),string.Empty});
   argsAll.Add(new object[] {typeof(int),"0"});
   argsAll.Add(new object[] {typeof(int),"13"});
    argsAll.Add(new object[] {typeof(int),"13 "});
    argsAll.Add(new object[] {typeof(int)," 13"});
    argsAll.Add(new object[] {typeof(int),"13.25"});
    argsAll.Add(new object[] {typeof(int),13});
    argsAll.Add(new object[] {typeof(int),13.24});

    argsAll.Add(null);
    argsAll.Add(new object[] {typeof(double),null});
    argsAll.Add(new object[] {typeof(double),DBNull.Value});
    argsAll.Add(Read More »
          
        

By SkySigal on 9/17/2008 11:43 PM

image

Right! Yar little raskalls! Witch one of you little Microsofties decided to make the constructor of the System.Diagnostics.TraceListenerCollection an internal?!?!
Come on! Spit it out!

Strong Hate of Intnerals
I just want to say that it the use of the internal keyword -- especially in a Framework -- is too restrictive.
Solve your security by other means!

 

Workaround
Because the work around, although possible,  stinks as it requires extra CAS permissions, etc:

Type type = typeof(TraceListenerCollection);

ConstructorInfo constructor = 
    type.GetConstructor(
        BindingFlags.Instance | BindingFlags.NonPublic, 
        null, 
        new Type[] {}, 
        null);

        
TraceListenerCollection instance = 
    (TraceListenerCollection)
      constructor.Invoke(new object[0]{});

 

Seriously...

A general poll: Do you use the internal keyword? Why exactly? 
Don't be, privateinternal, or protected about this important question: be public -- post a comment!

Links

System.Diagnostics.TraceListenerCollection

powered by metaPost

By SkySigal on 9/10/2008 3:37 AM

This looks like an excellent tutorial of the ins/outs on Fusion, which is the .NET technology used to locate and load .NET assemblies.

 

<<<

This Workshop Will Teach You

  • Location of .NET assemblies and how to change the default locations
  • Using .NET tools to resolve problems with assembly locations and how to fix broken applications
  • Sharing assemblies with the GAC, updating GAC dependencies with publisher policy files, GAC references
  • Satellite assemblies and culture specific resources
  • Dynamic loading of assemblies, partial named assemblies
  • Accessing the Fusion API
  • Fusion and the Compact Framework
  • Generating Native Images from .NET Assemblies
  • Native Assemblies

>>>

powered by metaPost

By SkySigal on 9/8/2008 8:55 PM

image Cute: A colorized ConsoleTraceListener:

http://flimflan.com/blog/ASimpleColorConsoleTraceListener.aspx

 

Gives you output like this:

 

Maybe it could be enhanced to allow for custom colors, but I don't see much use for it ("Critical" should be in red, not neon pink...)

powered by metaPost

By SkySigal on 9/8/2008 6:23 PM

image I use the EventLog class not very much.

I'm not exactly sure when I picked up the habit of disliking it so much.
Maybe it was the fact that it a) demands way too much security b) heavy on the hard-drive, c) I've never yet found an EventLog message that is readable, or understandable by the average joe.

That out of the way, in case you need to use it, here are a couple of tips...

Read More »

By SkySigal on 8/30/2008 10:47 AM

Reminder:

"Avoid creating socket permissions using host names, as these names have to be resolved to IP address es , and this might block the stack. "

Src: http://msdn.microsoft.com/en-us/library/system.net.socketpermission.aspx

powered by metaPost

By SkySigal on 8/24/2008 6:01 PM

image The scourge of my life: email!

That out of the way, in case you have an app that has to send you a email when it crashes, here's how to do it...

Read More »

By SkySigal on 8/18/2008 10:36 PM

I'm pretty sure this doesn't look ethical...but heads up in case it is.

Someone is hosting free e-books out there, including C# how-to's, etc.

Some of them actually look somewhat current and quite interesting!
For example:  Pro WPF in C# 2008 Windows Presentation Foundation with .NET 3.5

powered by metaPost