Andrei Rinea

.NET Framework & SQL Server

Another C# riddle..

clock February 11, 2010 14:40 by author Andrei Rinea

Just like a little game of guessing went, I want to present you another C# riddle Cool :

using System;

namespace AnotherRiddle
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var w1 = new Wee { bar = new Foo() };
            if (w1.bar is Bar)
                Console.WriteLine("A");
            if (w1.bar.GetType() == typeof(Bar))
                Console.WriteLine("B");
        }
    }

    internal class Bar { }

    internal class Foo : Bar { }

    internal class Wee
    {
        public Bar bar;
    }
}

 

1. What do you think the code snippet will print at the console? 

2. What are all the differences between the two if constructs?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Request.UserHostAddress versus Request.ServerVariables["REMOTE_ADDR"]

clock February 9, 2010 23:59 by author Andrei Rinea

I just found out a HUGE performance difference between these two. Tested on my cheap laptop (HP Compaq 615 : AMD Turion Dual core 2,2GHz, 3GB RAM, 7200 RPM HDD; 500$) on .NET 4.0 Beta2 after several test runs (averaged results), 1 million iterations, release mode and Stopwatch for time measurement (as opposed to DateTime.Now) :

var a = Request.UserHostAddress; // -> 240 microseconds

var a = Request.ServerVariables["REMOTE_ADDR"]; // -> 0,4 microseconds

What the f...rick?! 500x times faster?

What does Request.UserHostAddress to use so much more time? Let's fire up good ol' Reflector :

	public string get_UserHostAddress()	
	{	    
	if (this._wr != null)	    
	{	        
	return this._wr.GetRemoteAddress();	    
	}	    
	return null;	
	}	
	

_wr is a HttpWorkerRequest (a public abstract class). The GetRemoteAddress is also abstract so I can't guess from Reflector. So I fired up Visual Studio 2010 again and saw that _wr was a Microsoft.VisualStudio.WebHost.Request instance. So much for my astonishment.. If it's hosted in the IDE it can be slow..

I still ponder if it's worth testing in a production environment whether it's faster or not (Request.UserHostAddress) significantly or not..

 

EDIT1 : Couldn't wait to test this at work under IIS 6.0 (Windows Server 2003, Intel Core2Duo 2,4 GHz, 4GB RAM) and Request.UserHostAddress takes 86 nanoseconds to be queried... Can't wait to get home and test again on IIS 7.5 (Windows 7 Ultimate RC)

 EDIT2: At home on IIS7.5, same laptop, release mode etc. etc. 29 microseconds for Request.UserHostAddress. It's better than Cassini's 240 microseconds but it should have been at most 100 nanoseconds...that's one thousand times slower..

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


The great thief

clock November 28, 2009 00:32 by author Andrei Rinea

From the Tao programming

 

There once was a man who went to a computer trade show. Each day as
he entered, the man told the guard at the door:

"I am a great thief, renowned for my feats of shoplifting. Be
forewarned, for this trade show shall not escape unplundered."

This speech disturbed the guard greatly, because there were millions
of dollars of computer equipment inside, so he watched the man
carefully. But the man merely wandered from booth to booth, humming
quietly to himself.

When the man left, the guard took him aside and searched his clothes,
but nothing was to be found.

On the next day of the trade show, the man returned and chided the
guard saying: "I escaped with a vast booty yesterday, but today will
be even better." So the guard watched him ever more closely, but to
no avail.

On the final day of the trade show, the guard could restrain his
curiosity no longer. "Sir Thief," he said, "I am so perplexed, I
cannot live in peace. Please enlighten me. What is it that you are
stealing?"

The man smiled. "I am stealing ideas," he said. 

 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Debating on the internet

clock November 23, 2009 07:07 by author Andrei Rinea

Just like "Fighting in the internet is like competing in the special olympics : even if you win you're still retarded" there is another "saying" about these issues : 

 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Login page lameness

clock November 13, 2009 00:39 by author Andrei Rinea

This might seem like a useless midnight rant (at least it is midnight here :P ) but I hope it's not.

Why do most sites allow you (having JavaScript clearly activated) to submit the login form when at least one of the two textboxes are empty? Why allow the request to the server? You know downright that this request WILL fail. Is JavaScript so complicated?

Why? 

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Improving your Visual Studio experience : MetalScroll

clock November 5, 2009 11:57 by author Andrei Rinea

I've heard of RockScroll from Scott Hanselman a while ago in his blog entry. The Visual Studio plug-in basically replaces the vertical scroll bar with a real time thumbnail of the code. Plus it highlights words if you double-click them. It's niiiiceee!! I've soon downloaded it and used since then (more than a year).

However lacking the ease of using the window split, having parasyte double click highlightings and desynchronizing when you collapse a region of code annoyed me for a while...

Until today!!

Scott did it again and twitted about a good replacement for RockScroll : MetalScroll.

It does all RockScroll does plus :

  • double-clicking the scrollbar brings up an options dialog where the color scheme and scrollbar width can be altered.
  • the widget at the top of the scrollbar which splits the editor into two panes is still usable when the add-in is active.
  • you must hold down ALT when double-clicking a word to highlight all its occurrences in the file. RockScroll highlights words on regular double-click, which can be annoying when you actually meant to use drag&drop text editing, for example when dragging a variable to the watches window.
  • pressing ESC clears the highlight markers.
  • lines containing highlighted words are marked with 5x5 pixel blocks on the right edge of the scrollbar, to make them easier to find (similar to breakpoints and bookmarks).
  • multiline comments are recognized.
  • hidden text regions are supported.
  • it works in split windows.
  • it's open source, so people who want to change stuff or add features can do so themselves.
  • Here's how it looks in my VS :

     

     Later edit : This also comes as a patriotic thing for me as the author is a fellow romanian like me, Mihnea Balta :) 

    Currently rated 5.0 by 1 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    Home banking fail

    clock October 24, 2009 11:40 by author Andrei Rinea

      I've just set up a home banking account with a bank (ING) and I've asked the clerk if the account has browser limitations (as in "works only in IE" or stuff like that). As some of you might know about me, Opera is my favorite browser. So I've fired up Opera and tried to log in the account. Here's what I've got :  

     

     

    Yes, you've read right : their web application has failed because of the user agent string. Pathetic.

    Consider this a counter example for the applications that you develop. It's 2009, almost 2010. A web application must be able to run on any (graphical, i.e.: not Lynx) browser. Just as a side note Opera 10.00 (which I've been using in this case) passes Acid 3 test with 100%.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    A little game of guessing...

    clock October 14, 2009 11:23 by author Andrei Rinea

    Let's say I have this block of C# code that compiles 

    if (someVariable == true)
    {
        // do something
    } 

      but in a haste to optimize the code I change it into :   

    if (someVariable)
    {
        // do something
    }

    and suddenly my code does not compile anymore.

    WHAT TYPE COULD someVariable  HAVE?! Please comment on what you think about this small riddle :)

    Currently rated 2.6 by 5 people

    • Currently 2.6/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    A useful Custom Configuration Section for inline unconstrained XML

    clock September 21, 2009 00:05 by author Andrei Rinea

    As I was writing a small TCP server for serving Silverlight local TCP policy I came across a certain need. Inspired by Dan Wahlin's server implementation I chose to write a simplified version for myself. I needed to keep some XML in App.config without constraining it with a schema.

    The normal solution in this case is a custom section, sibling to appSettings if you wish. So my App.Config looked at first like this :

    <configuration>

      <
    appSettings
    >
        <
    add key="ipAddress" value="127.0.0.1"
    />
      </
    appSettings
    >

      <
    access-policy
    >
        <
    cross-domain-access
    >
          <
    policy
    >
            <
    allow-from
    >
              <
    domain uri="*"
    />
            </
    allow-from
    >
            <
    grant-to
    >
              <
    socket-resource port="4502" protocol="tcp"
    />
            </
    grant-to
    >
          </
    policy
    >
        </
    cross-domain-access
    >
      </
    access-policy
    >

    </
    configuration>

    Upon running the program even addressing the "ipAddress" key in the appSettings section throws an exception like:

    System.Configuration.ConfigurationErrorsException was unhandled
      Message="Configuration system failed to initialize"
      Source="System.Configuration"
      BareMessage="Configuration system failed to initialize"
      Line=0
      StackTrace:
           at System.Configuration.ConfigurationManager.PrepareConfigSystem()
           at System.Configuration.ConfigurationManager.GetSection(String sectionName)
           at System.Configuration.ConfigurationManager.get_AppSettings()
           at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrei\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.Configuration.ConfigurationErrorsException
           Message="Unrecognized configuration section access-policy. (C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config line 8)"
           Source="System.Configuration"
           BareMessage="Unrecognized configuration section access-policy."
           Filename="C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config"
           Line=8
           StackTrace:
                at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
                at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
                at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
                at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
           InnerException:

    So something is wrong. We need to tell the runtime that the "access-policy" section is allowed.

    <configuration>
      <
    configSections
    >
        <
    section name="access-policy" type="CustomSections.InlineXmlSection, CustomSections"
    />
      </
    configSections
    >
    ...

    At first I haven't placed the type attribute in the "section" element but it turned out it had to specified and be not empty. Moreover it must containt the fully-qualified class name and the assembly which contains it. The class must inherit from System.Configuration.ConfigurationSection.

    So I created an assembly called CustomSections, added references to the System.Configuration assembly and the System.Xml assembly.

    All you need to do is override the DeserializeSection method and load the XML document in there :

    using System.Configuration;
    using
    System.Xml;

    namespace
    CustomSections
    {
      public class InlineXmlSection :
    ConfigurationSection
      {
        public XmlDocument Content { get; private set
    ; }

        protected override void DeserializeSection(XmlReader
    reader)
        {
          (
    this.Content = new XmlDocument
    ()).Load(reader);
        }
      }
    }

    The code is pretty self-explanatory : we instantiate a new XmlDocument and load it from the XmlReader provided to us by the configuration infrastructure. If anything goes bad the exception handling will be the responsability of the caller. In this case the first call to ConfigurationManager.

    Now let's put the code to use :

    private static void Main(string[] args)
    {
      expectedRequestBytes =
    Encoding.UTF8.GetBytes("<policy-file-request/>"
    );
      listener =
    new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings["ipAddress"
    ]), 943);
      var policySection = (InlineXmlSection)ConfigurationManager.GetSection("access-policy"
    );
      policyBytes =
    Encoding
    .UTF8.GetBytes(policySection.Content.OuterXml);
      ...

    The underlined code is the relevant portion (the rest is provided for context). We get the section via ConfigurationManager.GetSection and we have to cast the result to the desired section type. The we use the section as we see fit.

    I will use this code sample in a future blog post regarding writing a very small TCP server for serving Silverlight 943 TCP Port policy XML content. Hope you find this useful.

    Currently rated 1.0 by 1 people

    • Currently 1/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    Creating a reusable class - with all the goodies - part 3 : Final analysys

    clock September 7, 2009 23:59 by author Andrei Rinea

    I've decided to write a class that would model a SSN-like personal identification number used in Romania. It should be useful both in production code and as a learning material for my readers. In the first part I've shown a preliminary analysys and further analysys in the second part.

    Validation logic and what interfaces to implement is what is left for this part.

    Let's see the fragments that can be validated so we'll see how to model the validation flow. The first digit (the fragments can be seen in the first part) can have values from 1 to 9 so all possible values are valid. Nothing to validate here. The second fragment is the year. Also all possible values (00 to 99) are valid so nothing to validate here.

    The fun starts at the next fragment, the month. Only 01 to 12 values are valid anything outside (00, 13, 14, ..., 99) are invalid as they don't represent a valid year. The dating fun gets even hotter at the day. Although 00, 32, 33 and so on values are obviously invalid, some values are valid only in some months or some years.
    29th of february is valid in 2008 but not in 2009. 31 is valid in January but not in April. 30 is valid in April but not in February and so on.

    Next, the county has a list of predefined values as shown here, in the specs, so their validations should be piece of cake. The Enum.IsDefined (remember from the previous part that I've decided to use an enum for the county) should be a snap :)

    The index value must only not be 000 any other value is valid. This brings us to the final check : the check digit. The algorithm is moderately complex (as in not really 1+1 but something close) as seen in the specs :

    You take the PNC without the last (check) digit and put it next to the predefined value 279146358279. Next you multiply the first digit of the PNC to be validated to the first digit of this special validation value. Then you store it. Then you take the 2nd digit of your PNC and the 2nd digit of the special value and multiply it and you add it (the product) to the previously stored number and so on until you finish. In the end you have a sum of products that you will modulo by 11 and have a result : for 0..9 this is the final result. For 10 the result will be 1. This is the check digit. Enough theory, let's test it on my PNC :

    My PNC :               1810623420056
    The validation value : 279146358279
    
    1. 1 x 2 = 2; Partial-result (PR) : 2
    2. 8 x 7 = 56; PR : 56 + 2 = 58
    3. 1 x 9 = 9; PR : 67
    4. 0 x 1 = 0; PR : 67
    5. 6 x 4 = 24; PR : 91
    6. 2 x 6 = 12; PR : 103
    7. 3 x 3 = 9; PR : 112
    8. 4 x 5 = 20; PR : 132
    9. 2 x 8 = 16; PR : 148
    10. 0 x 2 = 0; PR : 148
    11. 0 x 7 = 0; PR : 148
    12. 5 x 9 = 45; PR : 193

    Now 193 % (modulo) 11 = 6 => my check digit is 6. This verifies my full PNC.

    As for interfaces to implement there are already-stated interfaces (as shown in the end of part 1) :

    • IEquatable<T> (enables equality comparison to another instance; type-safe)

      NOTE : Here type safe means the comparand is forced to be of the same type whereas in the type-unsafe versions the comparand is of type System.Object from which all classes inherit in .NET which allows invalid type instances to be passed in - these are required to work with old components and classes.
    • IComparable (enables value comparison to another instance; type-unsafe)
    • IComparable<T> (enables value comparison to another instance; type-safe)
    • IConvertible (enables converting to many basic types)
    • ICloneable; I thought of this later - after the initial analysys (enables deep cloning of the instance)

    There are also interfaces necessary to improve the serialization performance (speed and memory) :

    In the end, the IsValid and Violations properties should be grouped into a IValidable<T> interface that I'll define right now :

    interface IValidable<TFieldEnum> where TFieldEnum : struct
    {
        bool IsValid { get; }
        KeyValuePair<TFieldEnum, string>[] Violations { get; }
    }

    In the next part we'll FINALLY begin writing some code :)

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    About me

    A passionated .NET Developer working closely with Microsoft technologies. View my public site.

    Page List

    Sign in