Online Store | About Us | Blog
Page 1 of 7 in the Personal category Next Page
# Saturday, July 31, 2010




C# Serializable Dictionary - a Working Example

Here is the example:

using System;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;

[Serializable()]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
{
        #region Constants
        private const string DictionaryNodeName = "Dictionary";
        private const string ItemNodeName = "Item";
        private const string KeyNodeName = "Key";
        private const string ValueNodeName = "Value";
        #endregion
        #region Constructors
        public SerializableDictionary()
        {
        }

        public SerializableDictionary(IDictionary<TKey, TVal> dictionary)
            : base(dictionary)
        {
        }

        public SerializableDictionary(IEqualityComparer<TKey> comparer)
            : base(comparer)
        {
        }

        public SerializableDictionary(int capacity)
            : base(capacity)
        {
        }

        public SerializableDictionary(IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer)
            : base(dictionary, comparer)
        {
        }

        public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
            : base(capacity, comparer)
        {
        }

        #endregion
        #region ISerializable Members

        protected SerializableDictionary(SerializationInfo info, StreamingContext context)
        {
            int itemCount = info.GetInt32("ItemCount");
            for (int i = 0; i < itemCount; i++)
            {
                KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<TKey, TVal>));
                this.Add(kvp.Key, kvp.Value);
            }
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("ItemCount", this.Count);
            int itemIdx = 0;
            foreach (KeyValuePair<TKey, TVal> kvp in this)
            {
                info.AddValue(String.Format("Item{0}", itemIdx), kvp, typeof(KeyValuePair<TKey, TVal>));
                itemIdx++;
            }
        }

        #endregion
        #region IXmlSerializable Members

        void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
        {
            //writer.WriteStartElement(DictionaryNodeName);
            foreach (KeyValuePair<TKey, TVal> kvp in this)
            {
                writer.WriteStartElement(ItemNodeName);
                writer.WriteStartElement(KeyNodeName);
                KeySerializer.Serialize(writer, kvp.Key);
                writer.WriteEndElement();
                writer.WriteStartElement(ValueNodeName);
                ValueSerializer.Serialize(writer, kvp.Value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            //writer.WriteEndElement();
        }

        void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                return;
            }

            // Move past container
            if (!reader.Read())
            {
                throw new XmlException("Error in Deserialization of Dictionary");
            }

            //reader.ReadStartElement(DictionaryNodeName);
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.ReadStartElement(ItemNodeName);
                reader.ReadStartElement(KeyNodeName);
                TKey key = (TKey)KeySerializer.Deserialize(reader);
                reader.ReadEndElement();
                reader.ReadStartElement(ValueNodeName);
                TVal value = (TVal)ValueSerializer.Deserialize(reader);
                reader.ReadEndElement();
                reader.ReadEndElement();
                this.Add(key, value);
                reader.MoveToContent();
            }
            //reader.ReadEndElement();

            reader.ReadEndElement(); // Read End Element to close Read of containing node
        }

        System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        #endregion
        #region Private Properties
        protected XmlSerializer ValueSerializer
        {
            get
            {
                if (valueSerializer == null)
                {
                    valueSerializer = new XmlSerializer(typeof(TVal));
                }
                return valueSerializer;
            }
        }

        private XmlSerializer KeySerializer
        {
            get
            {
                if (keySerializer == null)
                {
                    keySerializer = new XmlSerializer(typeof(TKey));
                }
                return keySerializer;
            }
        }
        #endregion
        #region Private Members
        private XmlSerializer keySerializer = null;
        private XmlSerializer valueSerializer = null;
        #endregion
}


The full C# file can be downloaded here: SerializableDictionary.cs

This class is both XML-serializable and binary-serializable. It is hard to find examples out there that do both.

July 31, 2010 2:42 AM Eastern Daylight Time  #    Comments [0] - Trackback
.NET | News | Personal | Technology | Tips
# Tuesday, July 27, 2010




CPU Upgrade - The YouTube Test

The Role of the CPU

In general, the CPU is very rarely a bottleneck when it comes to performance. It is rarely noticed by most users because the tasks they perform are rarely CPU-intensive. Games generally use the video card heavily but not the CPU. The operations in which the CPU matters most are: video playback, file conversion, and compression. Most of us rarely care about file conversion or compression performance, since we generally tend to do those things in the background. However, there is one operation where the CPU is becoming more and more essential: video playback.

The YouTube Test

Since smooth video playback is very important to most users, there is actually a very easy test that can be done to see if the CPU is fast enough for typical usage. It's called the YouTube test.

  1. Go to YouTube and search for some videos.
  2. Pick one that is available in HD (720p) format and play it. (Example: "Moon" HD Trailer)
  3. If it plays at a low frame rate or lags occasionally, there is a chance the CPU may be too slow.
  4. Open Task Manager (right-click the task bar and choose Start Task Manager).
  5. Go to the Performance tab.
  6. From the Options menu, choose Always On Top.
  7. Now go to YouTube and start playing the video.
  8. Watch the CPU usage carefully. If it spikes up to 90% or more, that is not good news. It means that your CPU is too slow.

If your CPU usage goes to 90% or more while playing a YouTube video, your CPU is a significant bottleneck. Unless you're happy with choppy video, you should upgrade your CPU.

What Should I Upgrade To?

This is where Dacris Benchmarks comes in. Open Dacris Benchmarks and run the CPU test. You can run the other tests too but it is not necessary. Save your results (File - Save Results). Now, go to File - Compare Results and select a system with a CPU you'd be willing (and able) to upgrade to (e.g. Core 2 Duo E8400). Now you can see on the main screen what your CPU score would be with the new CPU. If the score is at least 5000 (the current YouTube threshold), it would be a good upgrade.

Summary

Try the YouTube test to see if your CPU can handle HD video. A CPU with a score of 5000 or more in Dacris Benchmarks can handle HD video at a smooth frame rate. So if your CPU scores less than 5000, it is likely that it cannot handle HD video on YouTube.

July 27, 2010 2:59 AM Eastern Daylight Time  #    Comments [0] - Trackback
Business | Commentary | Personal | Technology | Tips
# Friday, July 23, 2010




WCF – A Gigantic Monstrosity from the Depths of Hell

So it seems everyone out there who wants to create REST services is using WCF to do it. I don’t know how this trend got started, but it’s wrong. You see, WCF was never made for the web. It was made to replace inter-process communication which used to be done through RPC. Then, it grew into a bloated Swiss-army-knife solution trying to solve all of the world’s problems, including (as it happens) REST. Sure it solves the problem, but not very well. Only if you accept the gigantic limitations that WCF imposes on you.

Trying to build a REST service with WCF is like trying to open a beer bottle with explosives. It will open, but then you’ve got a whole mess on your hands.

This week I’ve been struggling to do exactly that – set up a REST service with WCF. Given that I have shared web hosting (I know, poor old me) and have multiple sub domains hosted on the same IIS service, it proved to be impossible. The error: “This collection already contains an address with scheme http.”

Looking around on the web for a solution proved to be futile. It appears that unless you have a dedicated IIS instance just for your WCF REST service, it ain’t gonna happen.

Another thing that really makes my blood boil with WCF is the fact that tracing is so difficult. You have to use a proprietary tool to view a proprietary trace format – and that’s when you finally get it to work right. If you can’t get it to work (I couldn’t), the result is that you try to access one of your service methods and, if there's something wrong with the method, you only get a blank browser screen. No debug output, no exception message, nothing.

I then realized there’s a much easier way to make it happen. The answer is so staggeringly simple you will laugh…

Global.asax

Here’s how you do it:
  1. Take out all the WCF junk from the web.config. God knows WCF likes to flood you with configuration.

  2. Add one line to Global.asax.cs, in Application_BeginRequest:
    MyService.ProcessRequest(HttpContext.Current);

  3. Then, create a class called MyService, with a bit of reflection to figure out which service method to call (based on your URL and query string parameters), and a call to XmlSerializer to convert the return value to XML. One example (in my case, called SearchService), can be found here.
That’s it. Three easy steps! Now you have a REST service. No changes to your WCF service contract. Your interface can stay intact – even with the WCF attributes still on it!

So to those who want to implement a simple REST service without the hassle of WCF, here you go. From now on, I prefer not to use WCF unless I absolutely have to.
July 23, 2010 6:37 PM Eastern Daylight Time  #    Comments [0] - Trackback
.NET | Commentary | Internet | News | Personal | Technology | Tips
# Friday, July 16, 2010




Project Vmana: Lucene.NET in the Cloud

An idea has been tossing & turning in my head for months now - 3 months actually. Rarely does an idea stick around that long without me finding some way to dismiss it.

The idea is a hosted customizable search engine, similar in ease of use to GSA (Google Search Appliance) but more capable - more like Lucene.

After searching for hours & hours for a decent hosted search engine, guess what? I found nothing.

The closest thing I was able to find was GAELucene (on Google Code). It's a Google App Engine version of Lucene. However, the index can only be read-only. It does not support a dynamic index. Without that, it's useless to me.

Hosted Applications - Some Examples

Just so you are less inclined to think I have finally lost my marbles:
  • IIS --> Windows Azure
  • SQL Server --> SQL Azure
  • Outlook --> Gmail
  • Backup --> Mozy
  • Bugzilla
  • SVN
There is a clear trend towards traditional server/desktop applications moving over to hosted services.

Getting a Customized Search Engine ... the Traditional Way:

These days, if you need a customized search solution, your options are as follows:
  1. Purchase, deploy, and maintain a gigantic enterprise search application (e.g. Google search appliance, Endeca, FAST).
  2. Integrate Lucene (or another free search engine) into your application (Java/ASP.NET) and develop your own management interface for it.
  3. Drop the customization and integrate a basic Google search box into your web app, that can only index & search your HTML pages.
Clearly, none of these options are particularly appealing to a small or medium-sized business. Why?

- Option 1 is super-expensive. Not only is the entry cost in excess of $20,000, the cost of maintenance and operation also exceeds $10,000 per month.
- Option 2 is less expensive, although certainly not free, and very time consuming. It could take at least 5 weeks to get a working solution, resulting in more than $5,000 in development costs. Then there's the cost of hosting Lucene yourself. With a large index, you probably need a dedicated server - around $200 per month!
- Option 3 is super cheap, but it's not at all what you want. It's basically the same as giving up.

Is there a better way?

Yes! There is one more option - option 4. But nobody's built it yet.

Option 4 is a hosted search engine where you control what data flows in & how it comes out, but the management & maintenance is handled by someone else.

Think of it as cloud search.

Two words! Simple.

Enter Project Vmana. Thinking search? Think Vmana.

How would it work?
  1. You go to vmana.com and sign up for your free entry-level search account.
  2. Just like App Engine, Vmana is metered. Let's say your entry-level account has 500 MB of index space and 100,000 queries per month.
  3. Using an easy-to-use admin interface, you configure your data sources:
    1. You want some data to be pulled in from your blog, so you give it your RSS feed URL.
    2. You want it to crawl your website, so you give it your home page URL.
    3. You set up some exclusion lists using regular expressions to filter out unwanted URLs.
    4. You have some custom objects with metadata that you will feed in with your own feeder application.
  4. Vmana handles all of your object types & indexes them regularly. You can check your stats using the built-in dashboard.
  5. Vmana provides a testing console - a simple web page where you can type in queries, see results, and build out customized result templates for use later.
  6. You then use the Vmana XML API to send queries from your web application. Your web app just builds the query, sends it to Vmana, and retrieves the results in XML format. Then, you apply a bit of XSL and magic happens - you've got your fully-customized search results page.
How much development effort is involved? Probably about 5 days. Under $1,000.

The value in Vmana lies mainly in the management & admin interface. Lucene does not provide it. If you did option 2, you'd have to build it yourself from scratch. Building all that crawling logic and pretty reporting UIs is not that easy, which is why I said 5 weeks, and that's probably a conservative estimate!

Why "Vmana"? I like the name - it's short, and the domain was available. ;)

Summary

With Vmana, your costs are reduced to about one-fifth relative to comparable options and you get better value & peace of mind!

The project has already begun. Stay tuned for additional status updates - probably in about 3 days.

Release Schedule

The first phase is a working internal prototype that we can showcase via screenshots. That is probably about 2 weeks away. Following that, a public beta - if one happens at all - would arrive around late August. The quality would be similar to the App Engine beta or the Azure CTP. The beta would continue probably for at least two months. Expect heavy promotional giveaways during the beta (i.e. high quotas).

This is all I will divulge at this time. I have nothing more anyway.

July 16, 2010 4:39 AM Eastern Daylight Time  #    Comments [2] - Trackback
.NET | Business | Commentary | Internet | News | Personal | Search | Technology




Memorable Seinfeld Quotes

Seinfeld, a sitcom created by Larry David in the early 1990s, has managed to have a lasting impact on our society.

So with that I think I'll summarize the most memorable Seinfeld quotes that I still hear nowadays. Seinfeld fans will know them instantly.
  1. Not that there's anything wrong with that.
  2. Oh yeah, well I had sex with your wife! ... (random guy to George: George, his wife is in a coma!)
  3. The last thing this guy's qualified to give a tour of is reality.
  4. Jerry: That's an old wives tale. Kramer: Is it? Look at this! (shows hairy chest) LOOK AT IT! LOOK AT IT!
  5. Marriage? Children? They're prisons! Man-made prisons! You're doing time! You get up in the morning, she's there. You go to sleep at night, she's there. It's like you, you gotta ask permission to use the bathroom. Honey, can I use the bathroom now? And you can forget about watching TV while you're eating. Because it's dinner time. And you know what you do at dinner? You talk about your day. How was your day today? Did you have a good day or a bad day? Well, I dunno, how about you how was your day? ... Jerry: I'm glad we had this talk. Kramer: Oh you have NO idea!
  6. Occasionally I like to help the humans.
  7. Hoochie mama!! Hoochie mama!!
  8. Serenity now.
  9. That's GOLD, Jerry. GOLD!
  10. OK. So that's one tuck, one no-tuck.
  11. NO SOUP FOR YOU!
  12. Believe it or not George isn't at home, please leave a message at the beep. I must be out or I'd pick up the phone, where could I be? Believe it or not I'm not home....BEEP!
  13. Hello, and welcome to movie phone. If you know the name of the movie you'd like to see, press one now. ... You've selected, Agent Zero. If this is correct, press one. ... You've selected, Brown Eyed Girl. If this is correct, press one. ... Why don't you just tell me the name of the movie you selected?
  14. Quone! To quone something!
  15. Bubble boy: The Moors! George: No, I'm sorry it's the Moops!
  16. WHO? WHO DOESN'T WANT TO WEAR DE REEBON??!
  17. Yoyoma!
  18. Giddyup!
  19. Oh I'm stressed.
  20. These pretzels are making me thirsty!
  21. Stick a fork in me ... I'm done!
  22. The sea was angry that day my friends. Like an old man trying to send back soup in a deli.
  23. How many times do I have to tell you? Poise counts!
  24. I wished that you would drop dead!
  25. It's fusilli Jerry!
  26. Jerry Seinfeld's a funny guy!!!
  27. I'm not telling you any ... more ... secrets! (Elaine on Schnapps)
  28. I heard *something*.
  29. I like to stop at the duty free shop.
  30. You don't even know what a write-off is.
  31. Snapple? ... No thanks.
  32. Can't you two see, that you're in love with each other?
  33. You put the balm on? Who told you to put the balm on? I didn't tell you to put the balm on? Where'd you get that da*n balm anyway? ... The Maestro. ... The WHO?!
  34. Hello Jerry! ... Hello, Newman.
  35. How can anybody not like him?
  36. George: What kind of a person are you? ... Jerry: I think I'm pretty much like you... only successful!
  37. Every group has someone that they all make fun of. Like us with Elaine.
  38. Jerry, I don't know sometimes...
  39. George: WHY did you have to destroy 25 computers? Kramer: George, listen ... I owe you one!
  40. I can't be with someone if I don't respect what they do. ... Jerry: You're a cashier!!

July 16, 2010 12:03 AM Eastern Daylight Time  #    Comments [1] - Trackback
Commentary | History | Internet | Personal
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein do not represent the opinions of the author or of any employer, employee, or associate of the author.

© Copyright 2010
Dan Tohatan
Sign In
Statistics
Total Posts: 182
This Year: 38
This Month: 0
This Week: 0
Comments: 46

Computers
Top Blogs


Copyright © 1999-2010 Dacris Software, Inc. All Rights Reserved.     Privacy Policy  |  Who We Are  |  Blog

Need professional resume writing services?