CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Ranjan Sakalley

January 2005 - Posts

  • Suppress serialization of a public property

    A post on one of the microsoft groups prompted some research, I was bent upon finding out a solution one way or the other.


    [Serializable]
    public class Tested
    {
           
            private string _value;
            public string Value
            {
                    get
                    {
                            return this._value;
                    }
                    set
                    {
                            this._value = value;
                    }
            }
    }

     

    When you serialize the class above, after setting the property Value to, say "test" using the default XML serializer that comes with the BCL (XMLSerializer instance) you will get something like this as an output -

    <?xml version="1.0" encoding="IBM437"?>
    <Tested xmlns:xsd="
    http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-nstance">
      <Value>test</Value>
    </Tested>

    What will you do to make the default serializer ignore a public property? Lets start with a public member variable. Mark it as [NonSerialized] ofcourse. So if the class were something like this

    [Serializable]
    public class Tested
    {
            [NonSerialized]
            public string Value;
           
    }

    and you serialized an instance of this class using XMLSerializer, the NonSerialized attribute is totally ignored, and you get

    <?xml version="1.0" encoding="IBM437"?>
    <Tested xmlns:xsd="
    http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-nstance">
      <Value>test</Value>
    </Tested>

    So the XMLFormatter is not a solution at all. Also, you cannot mark a property with NonSerialized, as this attribute applies to fields only

    Next, use a SoapFormatter and Serialize this instance, sending the instance as a graph you get


    <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <SOAP-ENV:Body>
    <a1:Tested id="ref-1" xmlns:a1="
    http://schemas...">
    </a1:Tested>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

    Value” is not serialized here, which is good for me and I can move back to my original problem, the one where I want the serializer/formatter to ignore a public property.

    [Serializable]
    public class Tested
    {
            [NonSerialized]
            private string _value;
            public string Value
            {
                    get
                    {
                            return this._value;
                    }
                    set
                    {
                            this._value = value;
                    }
            }
    }

    Worked

    Lessons learnt
    XMLSerializer
            Serializes public properties and fields, doesn't matter if you mark them as NonSerializable or not.
    Also, I must note that properties are serialized; even thought they are actually methods internally, the XMLSerializer calls them.

    SOAPFormatter
            Serializes all fields (no properties), and respects NonSerializable.

     

    Is this differing behaviour by design, or am I missing some configuration setting

    Whatever be the case, I would still advocate implementing ISerializable, and writing your own serialization/deserialization code.

    Posted Jan 28 2005, 05:37 AM by rsakalley with 8 comment(s)
    Filed under:
  • 40tude Dialog

    If you ever were looking for a replacement for Outlook Express (msimn), or for that matter, any good news + mail reader, this is it.

    1. Doesn't open Windows Messenger by default. ( major PITA with msimn)

    2. Color coding. Quoted messages (with > and >>) with different levels are coloured with different shades for upto 4 levels.

    3. Great UI. One of the best you will see. Highly customizable. Great icons, treat to use. Fast, unlike the new blog + news readers.

    4. Great Mail Viewer. Thread identification for Mails too (like GMail), gives you more access to what you are sending and your identity (unlike Outlook etc, every mail can be sent using one of the many mail accounts that you keep, and can customize all Mail headers like ReplyTo, Organization, Sender Name, Keywords ,X-Headers etc easily, which is the keyword here.)

    5. NNTP. Awesome viewer. Subscribe different groups with different accounts, change them while sending mails without any fuss at all. Identifies abbreviations and tool-tips them :), scoring (havent used, i dont need it, but its a very good idea), hide signatures , hide quoted lines, it marks the thread as read if you move to the next one after getting bored reading one or more messages in the thread. Read raw message.

    What I need  >> RSS reader plugin.

    Check it out.

     

    Posted Jan 27 2005, 09:20 PM by rsakalley with 2 comment(s)
    Filed under:
  • "as" or "is" for decision making

    Thanks to Michal Boleslav Mechura, who pointed me back to Jeffrey Richter's "Applied Microsoft .NET Framework Programming" on this.

    Basically whenever you do an “is“ comparison for decision making, for example

     if( _control is TextBox)

    {

       // do your stuff

    }

    else

    {

       // do other stuff

    }

    there is a cast thru “as“ done anyways.  This is nothing new.

    The delay comes when you do this

     if( _control is TextBox)

    {

         TextBox _textbox = (TextBox)_control;

     }

    else

    {

        // do other stuff

    }

    Notice that you are doing the type cast again. For this case, it is better to do this

    TextBox _textbox = _control as TextBox;

    if(_textbox != null)

    {

        // do your stuff

    }

    else

    {

        // do other stuff

    }


     

    Posted Jan 24 2005, 07:40 AM by rsakalley with 5 comment(s)
    Filed under:
  • Get IP Addresses of all machines in your network

    I searched the .Net BCL for a solution to this, and then I had to go back to net.exe to do this. This is a very brittle solution, so if you have a better one, dont forget to enlighten me.

    using System;

    using System.IO;

    using System.Diagnostics;

    using System.Net;

    using System.Net.Sockets;

    using System.Collections.Specialized;

    namespace NetworkIPs

    {

    public class Names

    {

    public StringCollection GetNames()

    {

    ProcessStartInfo _startInfo = new ProcessStartInfo("net","view");

    _startInfo.CreateNoWindow = true;

    _startInfo.UseShellExecute = false;

    _startInfo.RedirectStandardOutput = true;

    Process _process = Process.Start(_startInfo);

    StreamReader _reader = _process.StandardOutput;

    StringCollection _machineNames = GetMachineNamesFromProcessOutput(_reader.ReadToEnd());

    StringCollection _machineIPs = new StringCollection();

    foreach(string machine in _machineNames)

    {

    _machineIPs.Add(IPAddresses(machine));

    }

    return _machineIPs;

    }

    private static string IPAddresses(string server)

    {

    try

    {

    System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();

    // Get server related information.

    IPHostEntry heserver = Dns.Resolve(server);

    //assumin the machine has only one IP address

    return heserver.AddressList[0].ToString();

    }

    catch

    {

    return "Address Retrieval error for " + server ;

    }

    }

    //string manipulations

    private StringCollection GetMachineNamesFromProcessOutput(string processOutput)

    {

    string _allMachines = processOutput.Substring( processOutput.IndexOf("\\"));

    StringCollection _machines= new StringCollection();

    while(_allMachines.IndexOf("\\") != -1 )

    {

    _machines.Add(_allMachines.Substring(_allMachines.IndexOf("\\"),

    _allMachines.IndexOf(" ",_allMachines.IndexOf("\\")) - _allMachines.IndexOf("\\")).Replace("\\",String.Empty));

    _allMachines = _allMachines.Substring(_allMachines.IndexOf(" ",_allMachines.IndexOf("\\") + 1));

    }

    return _machines;

    }

    }

    public class Runner

    {

    static void Main()

    {

    Names _names = new Names();

    StringCollection names = _names.GetNames();

    foreach(string name in names)

    Console.WriteLine(name);

    Console.ReadLine();

    }

    }

    }

    Posted Jan 21 2005, 01:46 AM by rsakalley with 3 comment(s)
    Filed under:
  • Algorithmic and Heuristic approaches towards software development

    If you look beyond the periphery of day to day programming, and try to find out where you are headed, for once you will notice that you are playing at the hands of a higher power. This higher power depends from one corporation to another; sometimes it’s a customer, at others it’s your immediate manager. At times it’s a company policy that hurts you, while some place else, you strive to be played on.

    If you pick a sample space of programmer’s from diverse backgrounds and geographical locations, I bet you will find that there is a good mix of content and, on the other side, angry coders, amongst them.  Try to break this set of people, and you will find definite boundaries between the subsets.

     Human beings are inquisitive by nature.

       Having questions about an approach is good. But once ‘the’ power starts feeding you the answers before you ask the questions, where is the fun? Writing loops and recursive functions for 3 months is more than enough to kill my appetite to sit in front of a machine and type.  What’s worse, they don’t even let you name your variables these days. Everything is in the printout. It’s a PROCESS. 9 to 6. Do not use your brain, the business is running quite well without it. The satisfaction levels go really low at such places.

      On the other hand, there are corporations that believe in their programmers. They give them the problem, for them to RTM, understand the business needs, and then find a solution.

    The previous approach (Algorithmic, CC2e Chapter 2) is a top-down approach, where managers think a lot, design the apps, and programmers just improve their typing skills. The second one (Heuristic, same reference) is where a company is driven by the bottom line.   

     Respecting the bottom line, as a necessity as well as a practice.

       Most big service providers, follow the top-down approach. All algorithms are made and maintained by the Managers, while the good under-paid developers keep shifting from one company to another in search of the little discovery they will make, a sense of purpose that gives them a moral boost to strive for more. Upon finding nothing, they shift purely in search of money, trips abroad. The industry is new, and there are no precedents about where such an implementer ends when they are 40. There are no lessons to be learnt, people just want to make merry while the sun is shining.

       If you think about Indian programmers for example, as a microcosm, you will distinctly find such a subset of the whole, and they don’t know what will happen in the next 10 years when every Chinese will know English, and will take half the money we charge. What I mean to say is, and I hope it’s not true, that this state is temporary. The long night will follow, and you never know when the sun will come up next time. Irresponsible business planning has led to this myopic vision of the bottom line.

    Being bred by such a system has other consequences too. When I look around for a good programmer, all I get to see is tech buzz words, “I know this, that” etc. etc. Fake certificates, fake engineers, and fake experiences flooding the job market. The top-down companies do not care, because they need typewriters. Everything is hollow.

     

    Anyway, there is another set of corporations which has another set of people. The managers follow the heuristic approach, and DEVELOPERS are busy solving problems, and being happy about them. What’s the need of hiring engineers otherwise? The only way to extend the sunshine is well respected at such places. And it’s to develop talent. These corporate know that developing individuality is the only way to stay in contention and competition forever. They acknowledge genuine knowledge. These people develop a niche in the industry, and that’s because they respect the developers, and respect their ideas. The heuristic approach pays its dividends. It should pay.

     To create a good enterprise, there should be a good mix of these approaches.

     There goes my research into creating a small and effective software development company. Please comment if you feel I am wrong, or my approach is parochial.

  • Nullable Types in 2.0 and Serialization

    Just wanted to know the effect on serialization of nullable value types. And if there is none, how come. I have used wrappers till now, and just wanted to check it out. Any pointers?
    Posted Jan 07 2005, 01:01 AM by rsakalley with 8 comment(s)
    Filed under:
  • When you manage an off shore project......

    If you are thinking about managing one, you should be ready with a few set of things

    1. Specifications. Many companies overdo the cost-cutting practice, by following an iterative process, wherin the specs are made as they come into picture. This  becomes a major issue, and mind you, not later, probably a month into the work.
    2. Timings You may have to take care of weird timings. So before taking up a project, I think you should decide on who should work their nights out, you or the offshore dev team.
    3. Boudaries both legal and international It is a very sorry fact, but there are cases in many offshore countries where people did not possess the morality to respect legal boundaries and went into piracy, and in other cases, broke someones code to write some for you. Beware and make sure this doesnt happen. Along with this, it is highly probable that you will have to travel atleast once to meet up you offshore team, and from some i have heard its not an easy process for a US citizen to travel to a third world country on a business visit; i may be wrong, but atleast its a cause of concern. Dont forget to bring your spouse, we are very good hosts by nature.
    4.  Processes  You should define the processes first, its a personal experience that things progressively get from bad to screwed up, if you rely on daily mails only. Major things that will help you would be Continuous Integration (something like Cruise Control.Net) , TDD, Source OffSite(or some other), because these are the only things that will help you manage the direction, and administer the growth.

    Ofcourse there are many other things, but mine is a perspective of a small offshore company working with consultants for small companies in the US, working on products. Things are majorly different for big companies and the services industry, and really, I dont care for them.

     

  • Convert numbers to text

     A new problem for the day.

    program input :
    1,291

    program output:

    "one thousand two hundred and ninety one"

    Basically pick out the number in the form 1 x 10^3 + 2 x 10^2 + 9 x 10 + 1,
    have this as a list, and switch each element with the text required.
    Remember that the tenth place should have a different set (twenty,thrity etc) and that 11 to 19 are another list again.
    Sometimes you just need to hard-code

    p.s.: I will post the code as a comment.

  • Change the Positive Testing style.

     By now, almost all developers know how important Unit Testing is. And still everybody, including managers who create schedules, and developers who break them, follow an ignorant approach. From my experiences as a developer, I have been following the positive testing path. To elaborate on this, lets say i have written a function to multiply two numbers. While testing, 99% of the time, I was testing whether my function, given two numbers, was giving me the right answer or not. I was (and I admit i have seen people doing this like i was) ignoring that though

    10* 2 =20, null *2 should throw a verbose, appropriate exception.
    Now what i wrote about above, its just a tiny bit of ignorance, building up to what i call a positive testing path. How to change this parochial approach?
    Lets see what i tried to do, am still doing, and trying to change the way i code.
    Use XUnit. This is one major tool that need to embrace. (Infact when we hire these days, one of the qualities that we look for in a candidate si if he is comfortable using any xUnit tool.)
    So now, when working on a piece of code, i actually work on two.
    a. I write test cases (following TDD or not is not a concern for me) and
    b. I write code.

    My positive test for my code is to make it work.
    My positive test for my test cases is to make them fail.

    This way, I am able to see the shine on both the sides of the coin.
    More to come on NUnit, automated builds and yes, I am working on a tool for automating/aiding this whole process while writing code.

    Posted Jan 05 2005, 10:56 PM by rsakalley with 5 comment(s)
    Filed under:
  • Speed up your lousy data reads

     I had worked on this almost 2 years back, .net was kind of unknown then, and we were probably the first team in Bangalore working on it.

    Problem : Your query resultset (may be a DataSet ) has 50000 rows with 5 ( or > ) columns.  You can't optimize the query/SP anymore,  and over all this, you are using Remoting/WebServices to get this data from a server.

    Internals: Each cell (I presume that you are using a DataSet, as I was. I will write about collections later) has an address. These addresses are stored in Hash Tables. Ofcourse there is a linking between all the elements of the DataSet, either direct or indirect. But the Hashing algorithm used by MS is very generic, does not depend on the number of addresses.  So every time the hash limit ( 4 buckets of 5 addresses each initially)  addresses are rehashed ( the next prime number after 2 x previous bucket size, so 11, then 23 and so on).  For the above case, you(CLR) may have to rehash around 16-18 times. This takes a lot of time, and you may face time outs, whitescreens on Deserialization.

    Solution : Use batches. Add an identity column to the tables.  Make batch sizes optimal for you resultset. say of 10000 each.  Fetch these batches one by one, merge these batches (bad solution, you are not improving the rehashing times here) or better create new a DataTable and add rows as they come(another bad solution, but a little faster). So what do we do next? Not moving from this approach, use Asynchronous remoting(if you are not using webservices) to run a for loop to get the data(call the fetch method for each batch at once in a loop, and wait for the server to serve you. then create a DataTable and add rows). No whitescreens this time around.

     While these solutions may reduce your fetch times to 50%, you should know that these are not robust solutions. Actually for me, the overhead that a DataSet has, keeping all the addresses it should not for my custom programs, is unaffordable. Binding controls with collections is possible and therefore I create custom classes for each resultset (many robots can be found for this nowadays, back then I had to write them all ) and have a collection defined for these classes, and remote them. Speeds up things a lot, makes you more responsible and so, more at control with things.

    Oh yes, I forgot to mention that you can improve times even when using DataSets. All you have to do is write a custom serializer.  You will need some help for this and
    here it is.  I would still suggest collections, custom classses and asynchronous calls though, datasets are a load anyway. 
    Posted Jan 05 2005, 10:50 PM by rsakalley with 8 comment(s)
    Filed under:
  • VS.NET Wizard mayhem

     The pop-up says
      Could not run the 'C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\CSharpProjectItems\LocalProjectItems\..\CSharpAddClassWiz.vsz' wizard.

    Annoying. You can't create a new project, can't create a new class. Nothing.
    Cause ? Some Add-in messed up all the wizards or scripting or both.

    Been working on this since 10 am today and no success. Google says this is a popular search, and Microsoft hasn't posted a fix. Doomsday. So I tried what Pete here suggested.

     1: Open a command prompt and go to the IDE directory of your VS.NET install. On my machine it's found here: C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE

    2: Type: regasm extensibility.dll

    3: Type: regasm vslangproj.dll

    4: Download this file (regtlb.zip) and unzip it to a location that's in your path. I have a utils directory where I keep a bunch of command prompt tools.

    5: Go to the directory: C:\Program Files\Common Files\Microsoft Shared\MSEnv

    6: Type: regtlb vslangproj.tlb

    Still no relief from the constant whining and popups. What do we do next? Reinstall Microsoft Scripting Engine from this page.

    Oops, its asked me restart my machine. Be back and write down what happened.

    Back

    Worked. Phew.

    Back to coding.

    Posted Jan 05 2005, 10:49 PM by rsakalley with 16 comment(s)
    Filed under:
More Posts