Friday, July 22, 2011

Check for open connections on SQL Server

Wonder how many open connections you have?  Run this:


SELECT DB_NAME(dbid) as 'Database', COUNT(dbid) as 'Open Connections' from master.dbo.sysprocesses with (nolock)
GROUP BY dbid

Results are:

Database Open Connections
SomeDBName 1

Wednesday, July 20, 2011

UnknownHostException in Android

Following the last post, if you get UnknownHostException when calling your web service from Android verify that your element is set under your manifest and not as an attribute in your element.

NetworkOnMainThreadException in Android

Something that used to work in Android 2.2 but stopped working in Android 3.0+ (Honeycomb) is executing long running processes (Http calls for example) from the main thread.  The exception you get is NetworkOnMainThreadException.  To fix this either utilize AsyncTask OR Handler patterns.

The following is my example for AsyncTask:

... this is inside an activity ...
   
    public void onCallService(View v){
        ServiceTask task = new ServiceTask();
        task.execute(new String[]{"http://www.ultimateworkoutdiary.com/BestStocksService.svc/10/DAY/1/ACTUAL"});
    }
   
    private class ServiceTask extends AsyncTask {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse execute = client.execute(httpGet);
                    InputStream content = execute.getEntity().getContent();

                    BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null) {
                        response += s;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.d("output", result);
        }
    }

Monday, July 18, 2011

WCF - Authentication Scheme error

So your wcf service works locally but not on IIS and the error you get is a combination

IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used.

What does this mean?
IIS by default selects a number of authentication schemes.  For me, the defaults were Anonymous and Windows.  WCF binding only supports specification for one scheme.

What to do?

Go to your Authentication settings in IIS and uncheck all but one scheme (I left anonymous on since I don't care about securing my specific service).

Tuesday, July 27, 2010

C# Tip - 7/26/2010

Make use of declarative programming when able to (use judiciously).  It will save time and allow for a clearer representation of your logic.

What is declarative programing?  It's when you define the behavior of the class using declarations instead of writing code.

Example:
[WebMethod]
public string HelloWorld()
{
  return "Hello World";
}

[WebMethod] <<< declarative programming

Another example is lambdas.  In the following example, retrieve all records that begin with "test":




            List lis = new List() { "test", "tests","unit","load" };
            List filteredList = lis.Where(l => l.StartsWith("test")).ToList();


Imperative example would be:

            List filteredList2 = new List();
            foreach (string list in lis)
                if (list.StartsWith("test"))
                    filteredList2.Add(list);


Monday, July 26, 2010

C# Tip - 7/25/2010

I am falling in love with events.

Events are implemented via delegates and are used for objects that communicate with multiple clients when a particular action occurs.

Scenario:  there's a soccer game between England and Mexico.  Both countries need to be informed when a goal was scored. 

Step 1: create a class for goal event data.

public class GoalEventArgs : EventArgs

{
  public readonly string Country;
  public readonly string Player;
  public readonly int minute;

  public GoalEventArgs(string country, string player, int minute)
  {
    this.Country = country;
    this.Player = player;
    this.minute = minute;
  }
}

Step 2: create a delegate for the event handler.
 
public delegate void AddGoalEventHandler(object sender, GoalEventArgs e);


Step 3: create the game class that will handle the event (make it static since only one game can be played at a time).

class Game
{
  public event AddGoalEventHandler GoalEventHandler;
  private static Game _instance = null;
  static Game()
  {
    _instance = new Game();
  }

  private Game() { }

  public static Game Singleton
  {
    get
    {
      return _instance;
    }
  }

  public void GoalScored(string country, string player, int minute)
  {
    AddGoalEventHandler g = GoalEventHandler;
    if (g != null)
      g(null, new GoalEventArgs(country, player, minute));
  }
}

Step 4: create a class for the Mexicans.
 
class Mexico
{
  private static Game game;

  public Mexico(Game g)
  {
    game = g;
    game.GoalEventHandler += new AddGoalEventHandler(game_GoalEventHandler);
  }
 
  void game_GoalEventHandler(object sender, GoalEventArgs e)
  {
    if (e.Country.ToUpper().Equals("ENGLAND"))
      Console.WriteLine("Ohh NO!!! ENGLAND JUST SCORED!!! That bastardo " + e.Player + " scored on minute " + e.minute.ToString());
    else
      Console.WriteLine("GOOOOAAAAALLLL!! VIVA MEXICO!!! " + e.Player + " has done it once again on minute " + e.minute.ToString());
  }
}

Step 5: create a class for the English.

class England
{
  private static Game game;

  public England(Game g)
  {
    game = g;
    game.GoalEventHandler += new AddGoalEventHandler(game_GoalEventHandler);
  }

  void game_GoalEventHandler(object sender, GoalEventArgs e)
  {
    if (e.Country.ToUpper().Equals("ENGLAND"))
      Console.WriteLine("ENGLAND JUST SCORED!!! That hero" + e.Player + " scored on minute " + e.minute.ToString());
    else
      Console.WriteLine("NOOOOO!!! " + e.Player + " has done the unthinkable and scored on minute " + e.minute.ToString());
  }
}

To test, add the following to your main method:

Game g = Game.Singleton;

Mexico mexico = new Mexico(g);
England england = new England(g);
g.GoalScored("england", "owen", 15);
g.GoalScored("mexico", "hernandez", 25);

Your console output will be the following after line 4 gets executed:
Your console output will be the following after line 5 gets executed:

As you can see, the possibilities with events are limitless!

Sunday, July 25, 2010

C# tip 7/25/2010

Implement interfaces versus overriding functions:

 
interface IBase
{
  void method();
}

 
class Base : IBase
{
  public void method()
  {
    Console.WriteLine("base implementation of method()");
  }
}

 
Console.WriteLine("first implementation:");
Console.WriteLine("call base");
Base b = new Base();
b.method();
Console.WriteLine("call ibase");
IBase i = b;
i.method();

 
This yields:
 
So far so good.  But what if you wanted to override the base method?

adding a new class throws a compiler error(class is below):

class Derived : Base
{
  public void method()
  {
    Console.WriteLine("derived implementation of method()");
  }
}

 
The error (actually a warning but you should treat all warnings as errors), is the following:

Error 1 Warning as Error: 'TipTester.Derived.method()' hides inherited member 'TipTester.Base.method()'. Use the new keyword if hiding was intended.


Solution is to add the new keyword to the derived method.
public new void method()

{
  Console.WriteLine("derived implementation of method()");
}

 
Modifying the main method to read the following:
Console.WriteLine("first implementation:");

Console.WriteLine("call derived");
Derived d = new Derived();
d.method();
Console.WriteLine("call base");
Base b = d;
b.method();
Console.WriteLine("call ibase");
IBase i = d;
i.method();
 

Yields the following:

Problem:  when calling the derived method directly, the right method is called; however, when casting the derived class to the base class or to the interface, the base class implementation is called.  This is because the class is not really inherited.

Solution:

1. For the interface: make the derived class implement the interface directly (this is going to get clumsy fast).  This solution also does not fix the base class problem.

2, Make the base class method virtual and the derived method override the base method.  This implementation fixes all the inheritance issues.  The new implementation of base and derived methods are the following:

                   public virtual void method()

                   {
                     Console.WriteLine("base implementation of method()");
                   }

 

                   public override void method()
                   {
                     Console.WriteLine("derivedbase implementation of method()");
                   } 

3. Best implementation, however, would be to make the base method abstract and force the derived methods to implement it. This might not be optimal for those situations where you might not want to implement the abstract method every time.

Labels