Software Development

5 Tips to get the most out of your coding time

Trusted By

Welcome Back! I hope you enjoy the content on this site. If you have not done so already, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!

I remember seeing an add from Microsoft I believe for hiring programmers and the jist of it was “We give you an office with a door”.

image

Why you might wonder?

Well, it might take up to 20 minutes to refocus on the task at hand after you get distracted either by a phone call, by a coworker barging in or by a video someone posted on Facebook.

I will give you an example of a spiral I used to find myself in. I will be happily hacking at this new feature that we need to ship soon and an email notification shows up for an email that I was cc’ed in so I open the email read it and can’t remember what it  was about so I end up reading the whole thread just to remember. Then I switch to my browser to see if there is anything new in my RSS reader, oh wonder if someone sent me something on Facebook. Off to Facebook I go.

An hour later I am back to visual studio and completely lost the thread to what I was doing. And that’s when bad stuff happens, bugs introduced and things get forgotten.

These are a few tips I use now to keep me focused and get the most out of my work hours.

1. Close your internet browser

As hard as it might seem, learn to open your browser only if you need it to research something related to the task you are doing.

What I like to do is to dedicate a couple hours before I start  coding to research the references I need. So that when I get started it’s only coding and nothing else.

Try it for a week and see how much stuff you get done.

2. Close your mail client / instant messenger

Don’t worry, if something really urgent happens you would know about it. You don’t need to keep your mail client open at all times, and read each email as it arrives.

Think of how many emails you are CC’ed in just for the sake of it and to which you have no say in. And think of how  many hours you waste opening those emails and getting distracted by them and having to refocus on what you were doing before.

Set specific times at which you read your emails. I find just before my lunch break and at the end of the day the best time. I find emails a good way to unwind :). I also end up writing better quality emails instead of the quickly I have to get back to what I was doing mess I used to send to clients.

If you don’t want to close just turn off the notification sounds and status bar alerts.

3. Unhook your phone  (or put it in silent mode)

This follows on the no email theory. I ask all our clients that if something is really urgent to send me an SMS. They almost never do so I let the calls go to voice mail  and I can check it later.

This tip is also good for keeping your clients  happy and show your professionalism,  you wonder how? Well when they leave a voice mail your already know what they want to talk about when you call them back. Say the leave the following message:

Hey Hatim, I wanted to know what’s the status of feature N° 156 and if we are still on for the system update schedule by the end of the week.

What you can do is go find out what the status of that feature, check with your team that everything is good and ready to go for the system update.

The phone conversation will take less time as you won’t have to stall them and scramble while you open your tracking application or IM the person responsible for the feature or your team to see what’s going on.

4. Buy good noise canceling headphones

image

I have a pair of Bose® QuietComfort® 3 Acoustic Noise Cancelling® Headphones. These are great for listening to music and also shields you from all the distractions. Coworkers talking in the hallway, the guy talking loud on his phone, … . They also work I just put them on without anything playing.

A nice plus is that they have great sound quality!

Of course you don’t have to use noise canceling heaphones they are just nice to have, regular headphones will do too, specially with some loud music!! :D

5. Make small and regular breaks

When I am coding I like to have a 5 to 10 minutes break each hour and a half to 2 hours. I either go get a coffee,  talk to a coworker, check voice mail, walk in the hallway. The idea is when I get away from my  screen I can have a better spatial thinking and find new ideas or solutions more easily.

It’s also revigorating and gives you a mental boost when you are working.

Oh I can finish this new screen and have my break.

 

I hope this was helpful and would to would love to hear if you have any tricks and stratagems to keep your self focused.

Hatim

How to Drop All Relations in A Database

this is related to my earlier post on dropping all indexes from an sql database but this one is to delete all foreign key relations from a database.

set nocount on
 declare @statements cursor
 set @statements = cursor static for
 select  'alter table ' + quotename(ctu.table_schema) + '.' + quotename(ctu.table_name) +
         ' drop constraint ' + quotename(cc.constraint_name)
 from  INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS as cc
          join INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE as ctu
           on cc.constraint_catalog = ctu.constraint_catalog
              and cc.constraint_schema = ctu.constraint_schema
              and cc.constraint_name = ctu.constraint_name

 open @statements
 declare @statement nvarchar(1000)
 While  (1=1)
  begin
         fetch from @statements into @statement
                if @@fetch_status <> 0
                 break
                exec (@statement)
         end

 

Hope this was Helpful!

Hatim

How To Drop All Indexes From A Database

I was doing some performance tweaking of a batch job that was hanging and i was suspecting the indexes in the database to have something to do with it shocking up so I used this script to clear all indexes.

Ironically it was a missing index that caused the bottleneck. But here it is for anyone that might need it.

DECLARE @indexName VARCHAR(128)
DECLARE @tableName VARCHAR(128)

DECLARE [indexes] CURSOR FOR

    SELECT        [sysindexes].[name] AS [Index],
            [sysobjects].[name] AS [Table]

    FROM        [sysindexes]

    INNER JOIN    [sysobjects]
    ON        [sysindexes].[id] = [sysobjects].[id]

    WHERE        [sysindexes].[name] IS NOT NULL
    AND        [sysobjects].[type] = 'U'

OPEN [indexes]

FETCH NEXT FROM [indexes] INTO @indexName, @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'DROP INDEX [' + @indexName + '] ON [' + @tableName + ']'

    FETCH NEXT FROM [indexes] INTO @indexName, @tableName
END

CLOSE        [indexes]
DEALLOCATE    [indexes]
 
 

Hope this was helpful!

Hatim

6 Of My Favorite Visual Studio Shortcuts

These are some of my favorite and most used shortcuts in visual studio:

  1. Ctrl + - and the opposite Ctrl + Shift + -  To move the cursor back or forward to the last position without having to scroll or switch  files.
  2. Shift+Alt+Enter Switches to Full Screen Mode
  3. Ctrl+K, Ctrl+C Comment a block,   Ctrl+K, Ctrl+U Uncomment the block
  4. Shift + Alt + F10 then Enter expands the smart tag to insert a using statement or implement an Interface
  5. Ctrl+K, Ctrl+D Auto format the file (Source, xml or  html)
  6. Ctrl+M, Ctrl+ O Collapses all outlining to  definition and then Ctrl+M, Ctrl+M to toggle the current block to expanded or collapsed.

What about you what are your favorites. I would like this post to become a repository for the most used Visual Studio Shortcuts. So do share

Hope This Helps!

Hatim

Building Amazing Business Applications with Silverlight 4, RIA Services and Visual Studio 2010

A great tutorial by Brad Abrams about building business applications using Silverlight, RIA Services and Visual Studio 2010

10 Not So Well Known Keywords in C#

Ok before the flaming start let me state this. These are known to most hardcore programmers and not knowing them doesn’t make you less of a programmer either.

That said these keywords can come in handy and allow for better code quality and readability. Enjoy!

yield

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration.

example:

  public classList
 
{
       //using System.Collections;
     
public static IEnumerable Power(int number, int exponent)
       {
           int counter = 0;
           int result = 1;
           while(counter++ < exponent)
           {
               result = result * number;
               yield returnresult;
           }
       }

       static void Main()
       {
           // Display powers of 2 up to the exponent 8:
         
foreach (int i inPower(2, 8))
           {
               Console.Write("{0} ", i);
           }
       }
   }
   /*
   Output:
   2 4 8 16 32 64 128 256
   */

msdn reference: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

var

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

An application running on version 2.0 can also use the var keyword in their code as long as it’s compiled with 3.0 or up and set to output to 2.0.

example:

var i = 10; // implicitly typed

int i = 10; //explicitly typed

msdn reference: http://msdn.microsoft.com/en-us/library/bb383973.aspx

using()

Defines a scope, outside of which an object or objects will be disposed.

example:

using (C c = new C())

{

    c.UseLimitedResource();

}

msdn reference: http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx

readonly

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

msdn reference: http://msdn.microsoft.com/en-us/library/acdd6hb7%28VS.80%29.aspx

as

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. 

example:

class Base

   
{ public override string ToString()

        {

            return "Base";

        }

    }

    class Derived : Base

   
{ }

    class Program

   
{

        static void Main()

        {

            Derived d = new Derived();

            Base b = d as Base;

            if (b != null)

            {

                Console.WriteLine(b.ToString());

            }

        }

    }

msdn reference: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

is

Checks if an object is compatible with a given type.

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

The is operator cannot be overloaded.

example:

class Class1{ }

classClass2{ }

classClass3: Class2{ }

classIsTest

  
{

        static voidTest(objecto)

        {

            Class1a;

            Class2b;

            if(o isClass1)

            {

                Console.WriteLine("o is Class1");

                a = (Class1)o;

                // Do something with "a."

           
}

            else if (o is Class2)

            {

                Console.WriteLine("o is Class2");

                b = (Class2)o;

                // Do something with "b."

           
}

            else

           
{

                Console.WriteLine("o is neither Class1 nor Class2.");

            }

        }

        static void Main()

        {

            Class1 c1 = new Class1();

            Class2 c2 = new Class2();

            Class3 c3 = new Class3();

            Test(c1);

            Test(c2);

            Test(c3);

            Test("a string");

        }

    }

    /*

    Output:

    o is Class1

    o is Class2

    o is Class2

    o is neither Class1 nor Class2.

    */

msdn reference: http://msdn.microsoft.com/en-us/library/scekt9xw.aspx

default

    n generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

    • Whether T will be a reference type or a value type.

    • If T is a value type, whether it will be a numeric value or a struct.

    Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullabe<T>, which is initialized like any struct.

    example:

    T temp = default(T);

    msdn reference: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

    global

    The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed.

    example:

    class TestClass : global::TestApp { }

    msdn reference: http://msdn.microsoft.com/en-us/library/cc713620.aspx

    volatile

    The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

    msdn reference: http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.80%29.aspx

    extern alias

    It can sometimes be necessary to reference two versions of assemblies that have the same fully-qualified type names, for example when you need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.

    To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:

    /r:GridV1=grid.dll

    /r:GridV2=grid20.dll

    This creates the external aliases GridV1 and GridV2. To use these aliases from within a program, reference them using the extern keyword. For example:

    extern alias GridV1;

    extern alias GridV2;

    Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity using their fully qualified name, rooted in the appropriate namespace-alias

    In the above example, GridV1::Grid would be the grid control from grid.dll, and GridV2::Grid would be the grid control from grid20.dll.

    msdn reference: http://msdn.microsoft.com/en-us/library/ms173212%28VS.80%29.aspx

     

    Hope this helps!

    Hatim

    .NET RIA Services May 2009 Preview

    A new preview of .Net RIA Services is available for download with tons of bug fixes and other enhancements:

    Also added are the following samples. I am more intrigued by the XML Metadata Provider as this can probably offer some very flexible implementations, oh boy… I see some neat code generation tricks!!

    XML Metadata Provider

    This sample serves two purposes. First, it demonstrates how to create a custom metadata provider that can participate in the .NET RIA Services metadata pipeline. Secondly, the sample also provides a working solution to the existing problem of providing additional metadata for types that you don’t own or can’t modify.

    Click here to download: XML Metadata Provider

    Linq to SQL DomainService Sample

    This sample demonstrates how to create a .NET RIA Services DomainService base class for a particular data source or DAL (Data Access Layer). Two such providers are provided by the framework already – the LinqToSql and LinqToEntities DomainService base classes. All the APIs and functionality needed to create those DomainServices are public, which supports the creation of providers targeting other sources of data, for example NHibernate or other DALs, or an Amazon Web Services provider.

    Click here to download: Linq to SQL DomainService Sample

    Authentication Samples

    These two quick starts cover the default use cases of the UserService in May 2009 preview. The first is fully integrated with ASP.NET providers while the second is implemented using Entity Framework contexts. “Quick Start” comments have been included in the source to highlight and explain the implementation.

    Click here to download: Authentication Samples

    SilverlightStore SEO Example (CSharp)

    This simple application demonstrates the use of XML data and a POCO (plain old CLR object) DomainService. The server-side use of the DomainDataSource control is used to render content as well as a XML sitemap—all indexable by search engines. The down-level content is only visible to clients viewing the site without the required version of Silverlight installed (or JavaScript disabled).

    Click here to download: SilverlightStore SEO Example (CSharp)

    For more examples check out Brad Abrams blog and http://code.msdn.microsoft.com/RIAServices

    Hope this helps!

    Hatim

    7 Valuable Visual Studio Hidden Features

    Visual Studio is a very powerful IDE and I have yet to find another IDE that comes close to all the features it offers. Yet they are some hidden gems that can make our every day tasks a little bit easier.

    1. Under “HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor” Create a String called “Guides” with the value “RGB(255,0,0), 80″ to have a red line at column 80 in the text editor.
    2. Pressing ALT during selection, selects a square of text instead of whole lines.
    3. Ctrl++ [Control, Plus] or Ctrl+- [Control, Minus] to navigate to previous position of the cursor and back
    4. Ctrl+Shift+V to cycle through the Clipboard history. Visual Studio keeps a history of data in the clipboard
    5. Ctrl+U and Ctrl+Shift+U to uppercase or lower case selected text.
    6. Ctrl+L Deletes the current line.
    7. Shift+F9 to bring the variable in QuickWatch

    Hope this Helps.

    Hatim

    11 Optimization Tips For Visual Studio

    Sometimes ago I compiled this list for myself and our team to help get things done faster and deal with visual studio quirks.

    Remember if you mess things up you can always reset your Visual Studio Settings (Tools->Import and Export Settings->Reset All Settings)

    Visual Studio Optimization Tips:

    1. Disable F1. (Tools->Options->Environment->Keyboard) (I always end up hitting it by mistake when reaching for the escape key)
    2. Disable "Animate environment tools" (Tools->Options->Environment->General)
    3. Disable Start Page (Tools->Options->Environment->Startup)
    4. Disable "Track Active Item in Solution Explorer" (Projects and Solutions).
    5. Disable Navigation Bar (Tools->Options->Text Editor->C#)
    6. Set "AutoToolboxPopulate" to false (Tools->Options->Windows Forms Designer).
    7. Turn off Track Changes. (Tools->Options->Text Editor->Track changes)
    8. Bind Ctrl+Shift+k to Edit.LineDelete
    9. Bind Shift+Enter to Edit.LineOpenBelow
    10. Bind CTRL+SHIFT+ALT+Z to Attach To Process
    11. (Ctrl+K, Ctrl+D) to reformat the code when things get messy

    If you have some tips on your own please share in the comments!

    Hope this helps!

    Hatim

    How To Change Numbers Format in Reporting Services

    This one had me spinning for a while, so I am sure someone else would get some value out of this post.

    Our client had a French version of Microsoft SQL Server 2005 and Reporting Services but on their reports the numbers format was using a comma as the thousands separator and the point as the decimal separator. They wanted it to use the French number formatting which is the space as the thousands separator and the comma as the decimal separator.

    I started by looking at the Reporting Services Options and then SQL Server options but I couldn’t find anything to set the locale or number formatting.

    So I started looking at the report properties in Visual Studio and there it was:

    Reporting Services Language Setting

    You can change it to French or whichever language you are using and the number format would follow.

    Hope this helps.

    Hatim