Wednesday, November 10, 2010

Object Serialization in .NET

Serialization and its counter-process (Deserialization) is a mechanism to "package" an object for transport to another application or process.

You might want to send a stream of data over a web service, store it in a database, or need some type of interop way to transport an object across system.

The two main methods of serialization in .NET is the Binary and XML.  In a binary serialization, the object is converted to (get this) a binary stream; which is the fastest method of serialization.  Alternately with the XML serialization the stream is plain text which is better for interop.  One key note is that XML doesn't preserve the data type as well as binary but binary is really only useful for .NET to .NET type communication/transport.

Prerequisites to serialization... Serialization is not "free" in the sense that you have to do some work to make your classes/objects serializable.  The easiest way to do this is to mark your class with the attribute as shown here:

    [Serializable]
    public sealed class SomeObject
    {
        public int n1 = 0;
    }

This works because basic data types like int, string, etc .NET already knows how to serialize. However, if I had another custom class it would need to be marked as Seralizable as well.  This can has a cascading effect (all objects in the tree must be serializable [or marked as NonSerialized]) so keep that in mind when looking into this solution.

As I just alluded to if you want something to skip the serialization step then it needs to be marked as [NonSerialized] but keep in mind that object will be null when you Deserialize your object.

A simple example of how to serialize an object:

//Required namespaces
using System.IO; //required for stream
using System.Runtime.Serialization.Formatters.Binary; //required for binary formatter
using System.Runtime.Serialization; //required for Formatter Interface

SomeObject obj = new SomeObject();

IFormatter formatter = new BinaryFormatter();

Stream stream = new FileStream("MyFile.bin",
                                     FileMode.Create,
                                     FileAccess.Write, FileShare.None);

formatter.Serialize(stream, obj);
stream.Close();

As you see above we use a formatter. In this case we used the Binary Formatter but could have used the XML Formatter as well.  The formatter as the name suggests converts the object into the specified serial format and puts it into a stream.

In this case I put the object into a file but I could modify the code and store it in a string or some other container.

As I mentioned earlier now with this object stored in a stream/file/whatever we can now do with it what we please.  For our example, we'll say that this binary goes into a folder for processing by a Windows Service.  In the service it is very simple to pull the object back into memory and start working with it...

FileStream fs = new FileStream("MyFile.bin", FileMode.Open);
BinaryFormatter readFormatter = new BinaryFormatter();
SomeObject serialObj = (SomeObject)formatter.Deserialize(fs);

Just like that we now have our object back and can start working with it.

Limitations...  Some things to keep in mind when doing serialization ... I already mentioned that data that is marked as NonSerialized will be blank/null in the object.  But also keep in mind deserializing an object is not the same as creating a new object.  Therefore, the constructor don't be called.

Also, only public information is serialized.

Custom Serialization... I didn't touch on it but you can inherit the ISerializable interface and invoke your own GetObjectData method to write your own custom serialization for an object.  By default, you don't need to do this unless you have special requirements for the output of the serialization (say your formatting your XML to a schema that another system will consume, etc).

Thursday, November 4, 2010

Alternatives to Try Catch type casting

Back in the early stages of .NET in C# there were limited tools to determine if a cast would work or not.

So typically you'd see something like

int myInt = 0;

try
{
   myInt = (int)TextBox1.Text //some input
}
catch
{
   MessageBox.Show("This is not a valid integer.");
  return;
}

In 2.0 the TryParse came along.  TryParse will return a bool (if the cast worked or not) and put the value of the successful cast into a value.

Example:

int myInt = 0;

if !(int.TryParse(TextBox1.Text, out myInt))
{
  MessageBox.Show("This is not a valid integer.");
}

Visually, this is a little less code but is also a more legitimate way of testing your casting.  Really, you could do a lot more checks using Regular Expressions, etc but something like this is a simple way to do validation in simple scenarios... IE... you just need there to be a number in there not a number with a decimal and x number of digits before and after, etc.

That example was for simple data types... but we can use IS for more complex data types like objects.

The IS keyword basically evaluates if the object to the left of the IS inherits (or is actually) of the same type.  This is useful in places where you want to pass an object as something simpler than it really is to made your function more versatile.

Using the Try Catch paradigm we could do something like this...

public static boolean SaveData(object myObj)
{
     SomeBaseClass b = null;

      try
     {
          b = (SomeBaseClass)myObj;
          return b.SaveData(); //assumes that method returns bool
      }
     catch
     {
         return false;
      }
}

A simpler way is to use the IS keyword...


public static boolean SaveData(object myObj)
{
    SomeBaseClass b;

    if (myObj is SomeBaseClass)
  {
          b = (SomeBaseClasse)myObj;
         return b.SaveData();
   }
  else
  {
   return false;
  }
}

Now in a case like this I'd probably make my SaveData function accept a SomeBaseClass object instead of a regular object and call the save... or make the object implement some type of interface that any object wanting to use this method could call.

However, this is just to give an example of how you can evaluate objects.  Maybe you support some types of objects (or handle them slightly differently) and want to run them all through the same method and this way you can easily do that.

Wednesday, October 27, 2010

Tech Tidbits

Nothing really new to discuss in the world of .NET right now (but I've got some stuff in the works to show).

A new things from around the tech world.

1. iPhone for Verizon.  It looks like it will be happening soon.  AT&T has increased its termination fees and Verizon is going to offer iPads with unlimited data plans as two signs.

2. iPad competition.  HP and Asus among are offering table PCs comparable in features, size, and price of the iPad.  Expect more to come out in the near future.  Interestingly, many of these new tablets are running Windows 7.

3. Windows 8.  It is being reported that Windows 8 is about 2 years aways (give or take).  Windows 7 was just released a year ago.

Friday, October 15, 2010

Technical Interviews

In my career I've done numerous in-person interviews, phone screens, technical evaluations, skill tests etc both from the employer and employee side and it amazes me the number of people who seem to bomb job interviews.  Normally, a person decides if they want to hire you within the first few minutes of an interview.  So you literally have only a couple of minutes to sell yourself to a potential employer.

Here are some common mistakes I've seen in interview and how to avoid them:

1. Being too general.  If an interviewer asks you about your experience the likely answer is to give a high level overview (C#, ASP.NET, SQL) which doesn't tell the much.  Likely since you're being interviewed they already know this information.  Instead, talk about what do you with the technologies you use.

I've heard countless interviews where the interviewee will describe their experience by merely listing out keywords: "C#, SQL, ASP.NET, Web Service, SQL, Oracle..."

A better example, "I primarily build ASP.NET sites using C# and ASMX web service.  On my sites I use the AJAX toolkit to communicate to the server to get combo box values and dynamically load content based on user selections.  I also use JavaScript for client-side validation of user input."

You might also throw in any applicable controls you've used that employer might be looking for.  Example (continuing from the fist example): "In my most recent project at ABC I've been using the RAD controls for data grids that display accounting information that the user can edit which is 2-way data bound to my Entity Framework business objects."

2. Overstating your qualifications.  Generally, questions like "What is your experience with x?" is a setup question.  If you answer "Yes" then you'll probably get 3-4 more follow-up questions.  Be honest about your experience with a technology and what you have done with it.  If you don't have any experience then a good answer is "No but I'd like to learn more about it and work with it."  Additionally, try and take a positive spin if possible and talk about a similar technology or approach you've used in the past.  Example: "I don't have experience with Biz Talk but I have used Windows Workflow before to create processes and tie business processes together."

3. Being an interview killer.  Killing an interview is where you say something (or several things) that will automatically disqualify you to an employer.  Listening is key to getting a job.  Listen to what the interviewers say.  If they have a different lingo for something; use their lingo.  For example if they call XML returned from a web service a "payload" then call it a payload when you talk about it instead of an "XML string" if that's your word for it.  This tells them you are listening and helps show that you can fit in and adapt to the team.

Additionally, don't contradict the position you are interviewing for.  For example, many times I will tell someone the position is a UI or back-end job and they'll later state their preference is the opposite (or something different) of what we're looking for.  If the job is not one you want; don't interview for it.

Last, don't be absolute about how you do things.  For example, "I would never hard code SQL into my application."  This can make for tense moments and give a bad impression if this is a habit or approach your potential employer is taking.  You might say instead, "Normally, I don't hard code SQL into my application I keep it in the stored procedure but there are circumstances I would do things differently."

In review, always talk about what you've don with the technology (not what technologies you know), be honest about your qualifications and turn negative into positives by talking about similar technologies or approaches taken in the past, and don't kill the interview; listen, use their terms, and don't be absolute.

Tuesday, October 12, 2010

XBox 360 Data Migration Cable Warning

I recently purchased a 250gb XBox 360 drive through EBay and ordered a data migration cable for the Xbox 360 through another seller.

Visually, the cable I received looks like the Microsoft cable but it doesn't have Microsoft stamped on the side.  The included software was also not Microsoft and when I inserted the disk the label of the CD was in Chinese!

After scouring the internet I found that the real data migration cable works by inserting the new drive into the XBox 360 slot and attaching the old drive using the cable.  When you power on your XBox it recognizes the old and new drive and offers to migrate your data automatically.  No CD required!  However, since this wasn't a real Microsoft cable... it didn't recognize my old drive when I tried this.

Additionally, the software that was included with my knock-off kit had very poor instructions an didn't recognize the drive when connected to my laptop either... so I couldn't even attempt to copy my data over via that mechanism.

I'm a little skeptical now that the Ebay seller, despite a very high ranking, didn't but a hard drive case and cram a compatible drive into it.  This could violate the XBox TOS (terms of service) and cause me to get banned on XBox Live!  I'm going to throughly investigate the drive before using it!

Thursday, October 7, 2010

Google Chrome - very good with some minor flaws.

I have to say that since using Chrome since April I've been very impressed with it.  For the most part it is visibly faster when browsing the overwhelming majority of sites when compared to IE.

Typically I browse on a Dual 1GHz machine or a Netbook running a 1.7Ghz Atom processor and reserve games for my XBox 360 or heavy duty processing (database and programming) to a dedicated machine.  So in these slower CPU environments you can really tell a difference when a browser is working well vs. a higher end machine brute forcing its way through inefficient coding.

That said, there is one time I find Chrome lacking and switch over to IE which is e-Commerce.  I've noticed on several sites when I attempt to purchase something and SSL is involved that I get session timeouts, errors, or the domain mismatch warning messages.  Even if I click "Proceed Anyway" I have issues.  I switch over to IE and have no problems.  So, I'd say its probably 5% IE (online purchases and some rare cases where Chrome doesn't render a site properly but IE does) and 95% Chrome in terms of my browsing usage.

As an aside some websites to try when comparing Chrome to IE:
Realtor.com
FoxSports Fantasty Football site  (which is horrid, see my random blog entry)

Increasing Computer Performance

I haven't really had any blog worthy tech stuff recently so I thought I'd relay some information about Overclocking in computing for those who might be interested to know more.

Basically with overclocking you are increasing the number of instructions the CPU can process in a given clock cycle by changing some basic BIOS settings.  Typically at the expense of stability (tho this can be nominal) and power consumption you can see major speed improvements over your stock CPU settings.  Conversely, many laptops use underclocking which saves power and wear on the CPU by decreasing the number of clock cycles.

Overclocking has two components the clock cycles on the CPU (called the multiplier typically) and clock rate on the FSB (Front-Side Bus).  The CPU multiplier is the instruction speed internally to the CPU while the FSB is how quickly information is sent to the other components.  Quick note: The FSB is the communication pipline from the CPU to the Northbridge which is what communicates to many of the other Motherboard components like the RAM and installed cards.  Contrastingly, the Southbridge communicates with the "slower" devices like drives and other I/O devices.  For newer chips the FSB is now being called the QPI (Quick Path Interconnect) but its the same concept.

By switching the multiplier settings and clock rate you can increase the performance of your machine if done correctly.  You'd also change the timing on your RAM as well to get an increase in performance since any slow point in the chain is going to cause bottlenecks.  You'll notice many GPUs will have similar settings like the motherboard to overclock.

One thing you'll also need to factor in is cooling and your power supply's ability to handle the increased draw for overclocking.  This is why many overclocked machines use water or other non-air cooling solutions in addition to high wattage power supplies.

There is no real formula on which settings to use to overclock your machine... its a process of trail and error but there are sites that might help you in this area.

One last thing to talk about is unlocking vs overclocking.  Overclocking is increasing hardware performance by increasing power consumption while unlocking is enabling existing hardware functionality that was intentionally disabled by the manufacturer.  When unlocking is applicable is scenarios where a piece of hardware is the same across product models but high-end features are disabled.  An unlocked card would a cheaper end of that line that has been flashed (firmware updated) to allow all the features that are normally reserved for the higher-end card.   The drawback to this method of performance tuning is that some cards are not tested to work at their max settings if they're a lower end card so it might not work OR the manufacturer has modified the hardware in such a way that the features don't work on the lower end card like severing the pathways on the board.