rulururu

post Linq Querys and Joins

March 31st, 2008

Filed under: .NET, Database — Kai @ 8:20 pm

I have been playing with LINQ just a few times but I can say I am impressed with it. It does nearly everything out of box. In This post I will illustrate how to use Joins in LINQ queries.

Many a times we want a query where by we retrieve the data from one table and some the related data from the other table. Let says we have a category table and a posts table. Now when I retrieve all the records of the posts I also want to have the related category name (which is there in the category table). So I need to make a join between three tables to get the records.

Here is the LINQ Query to do the job:

var t = from p in Blog.Posts
            join cp in Blog.CategoryPosts on p.PostId equals cp.PostId
            join c in Blog.Categories on cp.CategoryID equals c.CategoryID
            select new
            {
                PostId = p.PostId,
                CategoryName = c.CategoryName,
                PostName = p.PostName,
                PostSubName = p.PostSubName           
            };

So basically to make a join between two tables we use the join keyword. After specifying the join keyword we need to provide the column name on which the join will be made. And then we need to provide the condition on which the join will be made. Hence the on keyword with the condition.

It’s so simple. If you know a little bit of SQL then this syntax shouldn’t be a problem. LINQ makes working with data in its various guises easier.

By intergating it into the language, we have rich integrated support for working with data.

However, there are times where the syntax is slighly different from what you would typically expect with TSQL. Once case where this occurs is when trying to join two data sources that are related by more than one field (also know as a composite key). This differs from standard joins where one table has a primary key and the other table has a foreign key id.

post Conclusions on PWN to OWN contest

March 31st, 2008

Filed under: Computers, Linux, Windows — Kai @ 9:43 am

PWN to OWN challenge is over and the winner were awareded with a good deal of money and the laptop they cracked.

At 12:38pm local time, the team of Charlie Miller, Jake Honoroff, and Mark Daniel from Independent Security Evaluators have successfully compromised the Apple MacBook Air, winning the laptop and $10,000 from TippingPoint’s Zero Day Initiative. According to sources at the conference, Miller used an exploit against the Safari browser that ships standard with Mac OS X.

A security researcher on Friday exploited a critical bug in Adobe’s Flash Player to hack a notebook running Windows Vista Ultimate, the second machine to fall in this year’s “PWN To OWN” challenge.

The only unclaimed laptop by the contest’s end was a Sony Vaio running Ubuntu Linux.

What does this tell us? I think it’s not as easy as it looks…

I’m pretty sure that the Vista being cracked and not the Ubuntu had something to do with luck, it also could have been the way round. Cracking MacBook Air due a bug in Safari Browser we can assume that the usage of a browser that has a uncommon update system, like Safari has, is not recommented. When Safari 3.1 is not detected in a user’s machine, the updating software, by default, automatically selects the browser for installation.

The bug in Flash Player, which was accountable fot Vista’s downfall, had also been appearing in the Linux version. It kinda dependented on chance.

An interesting, but also alarming evolution is that operating system are becoming more and more secure which will lead attention of malware coders to individual software being installed on the target’s machine.
It’s alarming because it reduces the advantage Linux or Mac users had have because in further time most viruses, exploits used bugs in Windows. Not just because Windows has sufficiant bugs also because of the wide speaded usage of Microsoft’s OS.

Hopefully in future dangerous exploits won’t be a thread for all operating systems because a product is affected that is being used on every operating system.

post I {love} Unicode

March 27th, 2008

Filed under: Internet, Nonsense — Kai @ 8:51 pm

Inspirated by a post of Jeff Atwood on Codinghorror I, some minutes ago, designed and ordered this shirt:

Shirt

I thougth it was funny ’cause even if you don’t do programming with unicode you surly encounter unicode - e.g. when setting the doctype of a website.

At least if you haven’t had “a chance” to deal with this subject the way I would have liked to yet you’d read Unicode and You. I’m very much assured that it will help you to understand the basics.

Listen what Joel Spolsky from joelonsoftware.com in 2003 had to say:

So I have an announcement to make: if you are a programmer working in 2003 and you don’t know the basics of characters, character sets, encodings, and Unicode, and I catch you, I’m going to punish you by making you peel onions for 6 months in a submarine. I swear I will.

post Choosing a Good Password

March 26th, 2008

Filed under: Computers, Security — Kai @ 1:37 pm

Your password is like a key to your account, you need to safeguard it. Anyone who has your password can get into your account, and your files. Anyone who can guess your password has it. Anyone who has your password can pose as you.

There are a few basic parameters about strong password you’d take notice of.

Don’s use passwords that match any of the following:

  • Words in any dictionary.
  • Your user name.
  • Your real name.
  • Your spouse’s name.
  • Anyone’s name (crackers don’t necessarily know that your aunt’s middle name is Agnes, but it’s easy enough to get a list of 100,000 names and try each one).
  • Any word in any “cracking dictionary.” There are lists of words that crackers use to try to crack passwords: passwords that a lot of people use. Some of these lists include:

    Abbreviations, Asteroids, Biology, Cartoons, Character Patterns, Machine names, famous names, female names, Bible, male names, Movies, Myths-legends, Number Patterns, Short Phrases, Places, Science Fiction, Shakespeare, Songs, Sports, Surnames

  • Any of the above, with a single character before or after it (”8dinner”, “happy1”).
  • Any of the above, capitalized (”cat” –> “Cat”)
  • Any of the above, reversed (”cat” –> “tac”), doubled (”cat” –> “catcat”) or mirrored (”cat” –> “cattac”).
  • We used to tell people that taking a word and substituting some characters (a 0 (zero) for an o, or a 1 for an l) made a good password. This is no longer the case. New crackers have the capability to crack things like this, in certain situations.
  • Words like “foobar”, “xyzzy” and “qwerty” are still just plain words. They are also popular passwords, and the crack programs look for them. Avoid them.

Basically it’s recommented to have a password that

  • …is at least six characters long. This should be long enough to discourage a brute-force attack.
  • …is a mix of lower- and upper-case characters, numbers, and punctuation marks.

A good trick for remember a strong password is the use of an uncommon phrase, and take the first, second or last letter of each word. “You can’t always get what you want” would yield “ycagwyw”.

The best passwords are those which are totally random to anyone else except you. It is difficult to tell you how to come up with these, but you’d be able to do it.

Generate a random password:

Automatic password generation tools available in debian are for example:

  • APG (Automated Password Generator)
  • pwgen generates random, meaningless but pronounceable passwords.
  • Trigraph Password Generator generates pronounceable passwords.

My favorite tool is pwgen. It generates random, meaningless passwords but uses letter and number combinations that can be pronounced and memorized. Simply typing “pwgen” and hitting Enter will shoot back a screen full of passwords to choose from, helping to prevent shoulder-surfing sneaks, but you can easily hone down and customize the results with a few command-line switches.

A strong password is sufficiently long, random, or otherwise producible only by the user who chose it, such that successfully guessing it will require more time than the password cracker is willing to use guessing it. The length of time deemed to be too long will vary with the attacker, the attacker’s resources, the ease with which a password can be tried, and the value of the password to the attacker.

You can test your new password with Password Checker. Password Checker is a non-recording feature on this website that helps determine your password’s strength as you type.

What to do agains the attacker trying to crack your password using rainbow tables?

A rainbow table is a pre-computed table that greatly speeds up a search for a password with a given hash value. It is specific to one hash function, and usually restricted to passwords of a certain length and sometimes character set, e.g. alphanumeric passwords of up to 8 characters hashed by MD5.

  • Use passwords longer than those covered by commonly available tables.
  • Use characters not covered by commonly available tables.
  • Use a salt, which gives every installation or password a more or less unique hash function.
  • The salt is important because you often hear about community boards that have been cracked and all user passwords stored in the database are stolen.

    For an example how to use md5 checksums with salt you’d consider this (in php):

    <?php
     
    function encryptPassword($password) {
       $salt = 's+(_a*';
       return md5($password.$salt);
    }
    ?>

    Do not type passwords on computers that you do not control if you aren’t pretty sure about the provided security. Computers such as those in Internet cafés, computer labs, shared systems, kiosk systems, conferences, and airport lounges.

    Don’t take one and the same passwords for different matters. A big fault can be to register in a community with an email address and set the same password for the community login as for the email account. Obviously preventing this should be self-evident nevertheless I’m sure many people don’t even think about.

    At least, the first and most important, always to keep in mind, rule is NEVER to give your password to anyone. You can have the strongest password ever which is useless if known by anyone.

    What to do if your password is stolen?

    Imagine the not desirable case that someone has stolen your password. After changing it you be sure to monitor all the information you protect with your passwords, such as your monthly financial statements, credit reports, online shopping accounts, and so on.

    post Long Pathes

    March 25th, 2008

    Filed under: .NET, Windows — Kai @ 2:10 am

    Just a short snipped I’d like to not forget about.

    The maximal possible pathlength on Windows is, as you probably know, 255 chars. For that reason you can use the following:

    Convert short path to long:

    String s = Short2Long(@"D:\MYTEMP~1\RESOUR~1\sql.txt");
     
    public static String Short2Long(String sShortPath) {
        StringBuilder sLongPath = new StringBuilder(255);
        GetLongPathName(sShortPath, sLongPath, sLongPath.Capacity);
        return sLongPath.ToString();
    }

    Vice versa:

    String s = Long2Short(@"D:\My Temp\ResourseProvider\sql.txt");
     
    public static String Long2Short(String sLongPath) {
        StringBuilder sShortPath = new StringBuilder(255);
        GetShortPathName(sLongPath, sShortPath, sShortPath.Capacity);
        return sShortPath.ToString();
    }

    Hope it might help you somewhere along the way ;)

    post Almost Equal Floating Point Numbers

    March 25th, 2008

    Filed under: C++ — Kai @ 12:25 am

    Anyone who’s been writing code for any length of time knows how painful it can be to compare floating point numbers ’cause they’re mere approximations of their true value. For that reason a function to compare floating point values to a specific level of precision is needed.

    Don’t understand myself wrong. Usually when comparing floats you round them in a specified way and then compare them.
    Here the aim is different: Comparison of the values that were passed and find out if there are almost equal.

    Common way with rounding is:

    bool CompareFloats(double dVal1, double dVal2, double dTolerance)
    {
        return abs(dVal1 - dVal2) < dTolerance;
    }

    If you wish to have a tolerance of 0.01, then use a constant of some kind. The pow function is also efficient for different levels of decimal precision: pow(0.1, nPrecision);

    The following function does comparison of two double values and returns if they’re almost equal. The precision parameter specifies what relative error we are willing to tolerate.

    bool AlmostEqualFloats(double dVal1, double dVal2, int iPrecision)
    {
    	char sVal1[255];
    	char sVal2[255];
     
    	nPrecision = __max(__min(16, iPrecision), 0);
    	sprintf_s(sVal1, sizeof(sVal1), "%.*lf", nPrecision, iVal1);
    	sprintf_s(sVal2, sizeof(sVal2), "%.*lf", nPrecision, iVal2);
     
    	bool bResult = (strcmp(sVal1, sVal2) == 0);
    	return bResult;
    }

    There’s not much to tell about it. The major disadvantage is the usage of STL’s sprintf_s and strcmp, or better said, the manipulation of strings. Be aware that using strings is somewhat inefficient in a function like that.

    Finally, here a version of the function that doesn’t do any string manipulation at all.

    bool AlmostEqualFloats(double dVal1, double dVal2, int iPrecision)
    {
    	iPrecision = __max(__min(16, iPrecision), 0);
    	double dTmp = 1.0;
    	for (int i = 1; i <= iPrecision; i++)
    	{
    		dTmp *= 0.1;
    	}
    	bool bResult = (((nVal2 - dTmp) < nVal1) && (nVal1 < (nVal2 + dTmp)));
    	return bResult;
    }

    When watching this function work in the debugger, you might notice that performing any math of the dTmp value caused it to become impure. The very last digit of the mantissa was some random value. This almost guarantees that at some point, the value will be such that it returns an incorrect result.

    To make it clear, here’s a version of the function that accepts a direct value for dTmp in the form of an appropriate value. For instance, if you want a precision of 3, you would pass in 0.001.

    bool AlmostEqualFloats(double dVal1, double dVal2, double dTmp)
    {
    	bool bResult = (((dVal2 - dTmp) < dVal1) && (dVal1 < (dVal2 + dTmp)));
    	return bResult;
    }

    As a conclusion I can say that it is (hardly) impossible to reliably compare two floating point numbers for equality.
    Without great performance effort for math calculations can’t write a function that always returns the correct value when comparing floating point numbers. Typically, when people say “almost”, it involves some kind of relativity. For example, 1000000001 is almost 1000000000 and .999999999 is almost 1.

    ruldrurd
    Next Page »
    Powered by WordPress, Content and Design by Kai Bellmann
    Entries (RSS) and Comments (RSS)