Rss Directory > Programming > Tips > C# articles and tutorials on SharpDeveloper.NET
C# articles and tutorials on SharpDeveloper.NET
Sharpen your .NET skills with our C# articles, tutorials, demos, and source code by Sameer Alibhai
Copyright: Sameer Alibhai
  Fri, 03 Oct 2008 16:06:49 +0200
Change of atmosphere is actually a much faster way to learn, as I recently found out due to a job change.  A lot of time spent in the same environment working with the same people and learning stagnates.  If you really want to learn something different, be bold, take a risk, and change jobs.  Another factor is type of company - changing company types can increase learning speed by working in a different environment.  Technical skills are not the only skills that matter, so keep that in mind.  By looking at how different companies work together and achieve goals is a learning experience in itself.  I was concerned that moving from a team with many talented developers to moving to a team of one developer (me) my learning would stagnate.  However, this is not the case.  I feel like I've learned so much in the last few days just by being in a different environment.  Take risks!  Be bold!

Factors to note

- Background of those you are working with
- People who you are working with (non technical)
- Location of new job/environment
- Number of work hours

I think Justin of CodeThinked (a nice .NET blog that I subscribe to) sums it up pretty well why he changed jobs.
  Fri, 18 Jul 2008 00:40:22 +0200
In order to succeed as a team, in any sort of team, you have to follow this basic principle, which has been applied and maybe is accepted universally.
The principle is simple. 
 
  1. Appoint a Leader
  2. Leader makes council with the team
  3. Leader makes a decision
  4. Team supports leader in his or her decision
 
Its that simple. In this way, an organization, a team, a family, or a company can move forward. Every decision that you need to make, is done in this manner. The team will work together for the best solution, but in the end the leader needs to make a decision. Once that leader makes a decision, the team needs to move forward WITH the leader. 

This means, the leader doesn’t necessarily dictate, but he or she has gathered input from the team and made a decision. Then they will have to choose a solution and go with it. If the team continues to argue and fight over the decision, progress will be slow. I believe this applies in families too. There has to be a decision maker in the family, for example that is appointed for financial decisions, and then having a discussion or gathering input from the family is great, but in the end one person has to make the decision, and the family needs to be supportive, even if they don’t all agree with it. However, this applies in normal circumstances and there are caveats.   There might be some cases where it would be unethical for team members to support a plan if its morally wrong or it goes against everything inside them and they feel it’s a plan headed for disaster.
 
It pains me that time and time again I see this happen – the leader makes a decision and the team continues to question him at every step of the way – “Why are we doing this”, “Why are we doing this”, and “why are we doing this” instead of understanding that they were appointed for this role (they might be your boss for example) and they are ultimately responsible for the decision, you need to do your job and support them.  I have seen some cases where I questioned my manager because I didn't see the wisdom in the decision he made, but in the end it turned out he was right and it was just my foresight wasn't as far as his...  So I learned my lesson, be patient, and be a team player. 

As a team member, sometimes I have to swallow my feelings and say, “okay I don’t think this is the smartest decision and my idea is actually better, but I will go with you on this”.
From a developers perspective, you can think of this as requirements. Your boss gives you the requirements, you implement it. How you implement is up to you, but you won’t be able to proceed if you start arguing about the requirements. Requirements are requirements, once they are agreed upon, please continue.

So in normal circumstances, if you want to succeed, get a leader, and help him with his decisions, but in the end.. Respect the decision he makes and go with it. (He or she, that is).
The best team isn't necessarily the one with the best players, it's the one that plays together the best. 

To management, the idea of outsourcing sounds very sexy.... The idea of producing the same content (code, or what not) at 1/2 or 1/3rd the cost is almost a wet dream for management, if I may be so bold. Even though it sounds great in theory, it's actually a very tricky function to master. Here are some things I have learned with my outsourcing experience.

Keep in mind I am not discussing the outsourcing style of passing requirements and getting the end product complete. I am discussing the style of hiring outsiders and working with them on a daily basis.

You have to start by looking at what is the purpose of outsourcing. Is it to save money? Or is it to improve quality? Or is it so that your team can focus on other things? Get this straight first before going any further. My points below are in the context that you are a software company (or at least do some software development) and you are considering outsourcing to save money and cut costs.

From friends, I know that some very popular companies outsource, such as E-Trade Canada, Accenture, and recently the new online T.V. web site Hulu which outsourced its development to China.

  1. Before you start outsourcing, have your process solid - i.e. have regular scrum, know how much code you are generating each week, and so on. It's very important that you have some idea of costs for developing software for your local team. If you have no idea, you won't be able to see if you are really saving money or wasting it.
  2. Know velocities of individual team members so you can measure cost effectiveness of your outsourced work.
  3. Build your estimation skills. Read Joel's article on estimation and his second article on estimation (which is really a promo for his bug tracking software but still worth reading) and Steve McConnell's book on Software Estimation (highly recommended, very easy to understand).
  4. Get smart/able/competent guys. This can make or break your outsourcing project. If you are going to get developers that need baby sitting, then hire a baby sitter on their end to clean up their code, otherwise you are going to waste your valuable resources fixing and re-fixing and re-fixing their code. In this case you might not be actually saving money.
  5. Review their code. Someone on your side is going to have to review their code to make sure that they aren't purposely obfuscating it in order to secure their jobs in the future. I have seen a Flash application that was built in this manner, the team overseas purposely messed up the code in such a way that it would be difficult for others to continue where they left off.
  6. Learn from those who have done it before. If not, you are going to mess up big time, in many ways. Might be worth getting a consultant who has been successful with such projects. Another idea is to find someone who has connections "back home", and go there to see how some of the shops work.
  7. Turnover is really high in India/Bangladesh/ and so on. This is because jobs start at really low salaries (like $200 a month) and go upwards to like $3000 a month (comparable to working in Canada or USA). You will need to find a way to solve this problem. Somehow you will need to get them to commit that guys will not drop like flies. This is so important because there is always an upfront cost to learn an application, and it becomes more as the complexity and lines of code increase.
  8. Consider a cross-cultural learning program, you send some people there for a while, they come over here for a while. A lot of big companies do this. It's almost a must.
  9. For the team overseas, its important to spend your valuable time together in the beginning to ask lots of questions and understand the requirements as much as possible, in case there is a task that you run into questions, then leave it and work on something else.

Hamid, Axosoft CEO claims that Outsourcing is for Dummies. I think this isn't true in all cases, as I have been able to apply outsourcing successfully on some small projects. However, it all depends on the case, and for building complicated software with a (geographically) fragmented team, you may just end up proving his point.

  Sat, 05 Jul 2008 01:27:47 +0200
Last weekend was a bit of a disaster.  One of the servers I was maintaining was hacked, big time.  How did the (not so nice word) guys do it?  Well, first of all, I learned hackers think they are doing good deeds.  They did me a favor by hacking my server and by not "deleting all the files".  They only defaced some 30 something sites and caused me lots of misery and site cleanup.  Why do I say this?  Based on the hacker's signatory message - "Owned by nEtDeViL .. Just testing your Security .. Peace ! .. net_devil@.......com"

So Mr. hacker dude, if you really want to just "test" my security, why don't you send me a kind email stating that you found some security holes and how to fix them?  That would be a real gem of a good deed :)

Anyway, there is always light at the end of the tunnel, good always comes from bad, if you are patient and learn from your mistakes.

Here is what I learned - TURN ON PHP SAFE MODE!  The hacker exploited some old postNuke script in the albums folder uploaded some old Russian hack script called r57shell.php .  This script allowed him to install some rootkits which basically log everything you do on the server and all sorts of crap.  Which caused me to have to get a new server, yada yada.. :(

Now the first reason they managed to achieve this, is I didn't have php safe mode on.  I didn't want to inconvenience my buddies on the server (ya right, dumb move.)  So even if they managed to upload it, they can't do much with PHP safe mode on.  But with PHP safe mode off, well sorry buddy, even your own pals on the server can use this script to take over the server if you didn't give your friends full rights to run stuff on it and they get mad at you (you know what they say.... keep your friends close and your enemies ....)

Second thing, I went all out and installed Suhosin (grown out of what was known as PHP Hardening Patch).  I don't know how much this will help me, but at the least it didn't break anything on the server, so I'm leaving it there for good measure.

There is also Mod_Security for Apache but that's a bit difficult cuz it will slow down your server by checking every single request plus it will break a bunch of scripts so you will have to keep tweaking the regular expressions to get it to work nicely especially if you have tons of apps on the server.

Related reading - Forum Post: Tightening your PHP Security (just a few easy tips on how to tighten your security)

PS.. this server is running Microsoft Windows so don't even bother trying to hack it ;) -- okay don't laugh
Let's say you have CruiseControl.NET all set up nice and hunky dory.  Now you love the fact that it labels your each build, and you want to somehow show that from your project.  Here is how you can get your CruiseControl.NET project build number into your Web.Config.  This concept can be applied to update any file.
It’s super easy. You will need to add an exec block to your ccnet.config
 
<exec>
                         <!-- Auto increment web.config build number -->
                        <executable>E:\Userdata\CruiseControl\Tools\MergeWebConfigValues.exe (my custom tool)</executable>
                        <buildArgs>"E:\Program Files (x86)\CruiseControl.NET\server\Main.state" e:\userdata\cruisecontrol\Dev_Main\Web.config</buildArgs>
                        <baseDirectory>e:\userdata\cruisecontrol\Dev_Main</baseDirectory>
                        <buildTimeoutSeconds>15</buildTimeoutSeconds>
                  </exec>
 Now all you need to do is write the MergeWebConfigValues.exe
What does it do?
1. It reads the CCNET state file (provided by argument 1) and grabs the last label from there. (The state file is an XML file)
2. It then goes and writes to your Web.Config and updates the build number in there. (or writes to any specified file you like)
Lastly, update your code to read this value by adding some version or about page to read your Web.Config

You now instantly know what version your code is.
  Tue, 17 Jun 2008 16:25:05 +0200

If you are doing frequent work with regular expressions, check out this free tool - Regular Expression Designer by Rad Tools.  It's very nice and helps you with debugging those pesky statements with different input.

And just 2 reminders regarding naming of variables:

1. Short acronyms should be uppercase
http://msdn.microsoft.com/en-us/library/ms182256(VS.80).aspx

2. Identifiers should be cased correctly
 
http://msdn.microsoft.com/en-us/library/ms182240(VS.80).aspx

Hopefully I'll post some more stuff soon, been busy last week with personal stuff (selling my car, etc.)

  Fri, 23 May 2008 00:09:58 +0200

When unit testing on your database, you will run into a common problem.

Rolling back.

So you want to do some unit tests, and then you want to reset your database back to the nice squeaky clean version that doesn't have half failed unit tests.

So how can you do this?

There are many ways to achieve this.

The best way I found (requires Win XP SP2 or Windows Server 2003) is to use Roy's Unit Testing Rollback Attribute.  Simply inherit his class, add a "DataRollback" attribute, and you are good to go.  Using some complicated Interception logic and Enterprise Services (COM+) it rolls back all the database work that was done.  It's super easy to implement.  Here is some sample code that shows you just how easy it is.  You just have to download XtUnit (an extension to NUnit) to do this. (Full source code available)

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using TeamAgile.ApplicationBlocks.Interception.UnitTestExtensions;
using NUnit.Framework;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
 
namespace DBTest
{
    ///<summary>
    /// Test roll back functionality.
    ///</summary>
    [TestFixture]
    public class RollbackTest : ExtensibleFixture
    {
        [Test, DataRollBack]
        [Category("Database")]
        public void TestInsert()
        {
            //this method will be performed inside a COM+ transaction
            //this requires windows XP SP2 or better
            //Windows Server 2003 works as well.
 
            string strCnn = "your_conn_string";
            Guid random = Guid.NewGuid();
            string sqlI = string.Format(@"insert into log4net (message,date,thread,level,logger) values ('{0}',getdate(),'{1}','Debug','Test')", random.ToString(), System.Threading.Thread.CurrentThread.GetHashCode());
            SqlHelper.ExecuteNonQuery(strCnn, CommandType.Text, sqlI);
 
            string sqlS = string.Format(@"select count(*) from log4net where message='{0}'", random.ToString());
            int rowcount = (int)SqlHelper.ExecuteScalar(strCnn, CommandType.Text, sqlS);
            Assert.That(rowcount > 0, "Cannot find {0}", random.ToString());
        }
    }
}
This test passes successfully.  What does that mean? The insert and select worked perfectly fine.  After that, I did a query and found the database to be clean.  So the rollback worked too.
There are also other ways to skin this cat (i.e. to achieve this goal).  One is to use Spring Framework and extend their Unit Testing class (AbstractTransactionalSpringContextTests), and they will handle rolling back everything.  Here is an article on this topic, but unfortunately I was not able to make it work for me due to some odd reason.  Here's hoping you have better luck.  If you don't have any transactions, and your code is wired to use Spring, it's still also very easy, you just need to call TransactionManager.Rollback.
You can also try to achieve this using Nested Transactions if you have existing transactions implemented via Spring.  But then you have to set up checkpoints and stuff like that. 
I have some other ideas on how to achieve this that I will post later, God willing.
  Thu, 08 May 2008 23:42:05 +0200
This is a very shallow comparison of my experiences with PHP and ASP.NET
Don’t take this as a religious war or something, the idea is just some basic comparison.
 
Here is a summary: If you are choosing which technology to use to build an application, use .NET. You will get more bang for the buck. With the same effort you will be able to build a much more rich user interface. 
 
My Disclaimer: Keep in mind there are a lot of great libraries and tools for PHP which I never got to use, I just had a simple PSPad text editor and my handy PHP web site.  I really wanted some “Intellisense” style code completion but I could not get it to work with PHP since I couldn’t find a decent IDE (i.e. editor)
 
However, it all depends on your requirements. For example, if you are selling something that most of your customers will be on a shared linux hosting environment, then why would you use .NET ? A good example is the software Clipshare, which is a clone of Youtube. The sites purchasing this product are mainly shared hosting customers who have PHP but not .NET. And Mono (.NET port on Linux) is not yet stable or popular enough to use.
 
I did some PHP programming before I started doing .NET fulltime. Before then I couldn’t say much about it, but after working with .NET for a few years now, I have much to say.
.NET does a very good job in handling the whole life cycle. With PHP you have to do it manually.   For example, there is no such concept of “Postback” with PHP. This is such a basic thing that you can easily check with .NET to see if the page has been submitted and what button was pressed. For example if your “btnSubmit” was pressed, it will call btnSubmit_Click. With PHP, you have to do this manually. Not to mention how mish mashed your PHP page can be in terms of mixed code and style/HTML elements.

How about caching? I wanted to implement caching with PHP and I had a fun time, I had to check if the cached output file existed, and then if so, then check how old it is, and so on... Yeah okay again maybe there are some nice components already done for this, but I didn’t have to look very hard to do it with .NET, I simply added a CacheDependency on an XML file (or whatever the case was), and BOOM! It regenerated the file whenever necessary.
 
How about reusable components? With .NET you can create ASCX (Custom Controls) that you can place within a page that expose certain properties and the control itself maintains its state, can have buttons, etc, etc.

How about master pages (i.e. templates) in .NET? Again, super cool reusability! You can create pages with repeatable parts, with headers, footers, all sorts of fun stuff.

I can go on and on...  but in general, the more I use .NET, the more impressed I am with it. However, what makes it not-so-practical is how expensive Windows Server hosting is.  In summary .NET kicks butt!
 
Update Oct 8 2008
 
I wanted to add some more meat to this article based on the comments below

I mentioned that getting Windows Server hosting is more expensive.. However, lets look at this in perspective.  What's more expensive - server cost, or development cost?  Development cost in most cases far outweighs any particular savings of a Windows license.  What this means is even if your application takes two or three times as long to write, then you have lost any potential savings from running a "free" linux box. 

Also, I would like to hear about how to unit test with PHP. 

.NET offers unit testing via many different frameworks, NUnit probably being the most popular right now.   I would like to know how can I unit test in PHP?  There is also an extension for NUnit available called NUnitAsp that allows me to test my interface.  Another notable extension for Nunit is an automatic database rollback.  SWEET!  More details to come as time goes by.

Here's a security problem for you.

How do we stop people from using brute force attacks on our logon page?
Well, simple... just add a captcha.

Well, umm.. captcha is already broken.  Even if it isn't, they can hire someone overseas to sit there all day and crack away at it.. right ?
Well, umm... fine, so we'll set up this security scanner, and add that vulnerability protector, and automatically ban this and that, and let's do this.. and that, and this, and that, and so on, and so forth, until we have a fortress.

Tell you the truth.  Unless your site is heavily targetted, captcha is probably good enough.  In fact, my experiences is that you just put in 20% effort and you will stop 80% of the hackers (there's that 80/20 rule again...!).  For example, I had a web server that was getting daily hack attempts on the ssh port (port 21).   I had done lots of security tightening on it.  For example, I disabled root login, I added an automatic email that was sent to me on root logon, and so on... As well I had a software installed that would ban them after a certain number of failed logins, and would send me an email.   This software was called BFD (Brute Force Detection).  After getting these daily hack attempts, I decided I had enough, and I changed the port to a random value (say 561).   Since that day, I haven't received hardly one or two hack attempts.  Seems most hackers were the kiddy hackers that didn't really bother to try hard enough.  A simple port scan would have revealed my SSH port.  However.. by putting in that 20% effort, I got rid of 80% of the losers.

I eventually re-enabled direct root logon, since I realized this simple step was enough.

Now if your site is going to be targetted by hackers, no matter what you do, catpcha or no captcha, IP blocking or not, if they want to get in, they will get in.  The best way to stop those hackers is to hire some l33t hackers yourself to try to break their way in and then block it.  You will need to do some security audits and close any open holes you might have.

But in the end, the idea is, just put in a little extra security, don't just leave your login page open for brute force attacks, because you never know,....they might have already hacked your site (scary.. isn't it?)

Update - I found a good example of this in action - take a look at this quote from EmailSpoofer.NET:

Your Javascript sucks, I can decode it in 5min, why is it so easy to decode?

All javascript can be decoded. Its a matter of how much time/resources you want to devote to it. However, in this case, the javascript isn't meant to be difficult to be decoded by humans. It's meant to be difficult to be decoded by spambots. That being said, if you see some improvements I could make to the javascript routine, feel free to send them to me. I’d love to incorporate them into the control. However, please don't send me scripts that is someone else's work. Please send your original. Thanks!

 

Keep in mind that the 20% is always increasing. Hackers get smarter over time, and so you need to keep up with this minimum 20%. Take a look at how I was hacked in Server Security and PHP Safe mode

Spring is a popular framework available in Java.  It has also been published in .NET and is called Spring.NET

This framework is huge, but what I wanted to focus on is the section that deals with transaction management.

If you have ever worked with Transactions, (say SQLTransactions), you would realize how messy it can be when you have to keep your connection open and pass around a transaction to many different functions that are making updates or queries, and then you might make a small little change and find out you forgot to use the transaction object and you caused a deadlock!

How can you fix this?  By having a generic transaction/connection object?  Well, that's one way.. but how about using the Spring.NET framework to deal with the transactions?

Spring.NET allows you to specify when you need a transaction, and you would begin and end the transaction.  However, when you do the actual database calls, you would not pass any connection string, it would automatically use the transaction in process if there is one, or if not needed then it would use a regular connection and disconnect after the query is complete.

Here is a code snippet to demonstrate programmative transaction management, taken from the Spring.NET source code (yeah its open source!)

 

[Test]
        public void ExecuteTransactionManager()
        {
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.PropagationBehavior = TransactionPropagation.Required;

            //TODO change to property of name TransactionStatus...
            ITransactionStatus status = transactionManager.GetTransaction(def);
            
            int iCount = 0;
            try
            {
                iCount = (int)adoOperations.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM TestObjects");
                /*
                IAdoCommand cmd = new AdoCommand(dbProvider, CommandType.Text);
                cmd.CommandText = "SELECT COUNT(*) FROM TestObjects";
                iCount = (int)cmd.ExecuteScalar();
                */

                //other AdoCommands can be executed within same tx.
            } catch (Exception e)
            {
                transactionManager.Rollback(status);
                throw e;
            }
            transactionManager.Commit(status);
            Assert.AreEqual(2, iCount);

        }

 

As you can see from this code, the adoOperations.ExecuteScalar does not have any connection string passed to it.  Same thing with ExecuteDataSet, and so on. 

This actually saves you a lot of headache, as you just have to make sure you use the spring DataOperations object.  The easiest way to implement this on a ASP.NET site is to put these objects as a static variable and initialize them on Application_Load.  Just an idea but it should work. 

 If you want to do more digging, Spring.NET has tons of stuff, it seems to mostly focus on Dependency Injection and loose coupling of code from objects from the data layer.  I really like it and I recommend you give it a shot.

It's proven itself in Java and I think this framework is going to prove itself in .NET as well.  At the very least the source code is a prime example of a clean object oriented well designed application with full unit tests and sample code, XML documentation, thorough use of interfaces and inheritance, and even ORM (object relational mapping) using NHibernate (again a popular Java framework which has come into .NET)

 Update: I called this "declarative transaction management", actually its "programmative transaction management". - FIXED