UZUN .NET
Cruising in .NET

Change DB Access to Interface

Thursday, 1 May 2008 04:03 by volkanuzun

As i mentioned in my previous posting, i am trying to seperate the modules in my projects so i can test every single code. I am new to TDD so i meet a lot of challenges during the adoptation. One of them is the database access, how will i unit test a class or a function where these is a database dependency.  i decided to create a generic database access class, which implements an interface that could be mock out.

In the database side, i always use stored procedures to do actions, and my stored procedures either returns an integer value (if it doesnt return anything like delete from..., consider it returns 1),  or a DataTable such as select * from table. So i can easily write an interface such as:

[code:c#]
public interface IExecuteProcedure
    {
        DataTable GetDataTable(string StoredProcedureName, List<SqlParameter> Parameters);
        int ExecuteStoreProcedure(string StoredProcedureName, List<SqlParameter> Parameters);
    }
[/code]

So GetDataTable runs a stored procedure with a list of parameters given , and returns a DataTable, ExecuteStoreProcedure returns int.  A database access class could follow a pattern like below to implement this interface:

[code:c#]
public class DatabaseAccess:IExecuteProcedure
    {
        private readonly string ConnectionString_;

       
        public DatabaseAccess(string ConnectionString)
        {
            this.ConnectionString_ = ConnectionString;
        }
       
        public DataTable GetDataTable(string StoredProcedureName, List<SqlParameter> Parameters)
        {
            SqlConnection conn = new SqlConnection(ConnectionString_);
            SqlCommand cmd = new SqlCommand(StoredProcedureName, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter param in Parameters)
            {
                cmd.Parameters.Add(param);
            }
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            try
            {
                da.Fill(dt);
            }
            catch (Exception)
            {
                dt.Clear();
            }

            return dt;
        }

        #region IExecuteProcedure Members

        public int ExecuteStoreProcedure(string StoredProcedureName, List<SqlParameter> Parameters)
        {
            SqlConnection conn = new SqlConnection(ConnectionString_);
            SqlCommand cmd = new SqlCommand(StoredProcedureName, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter param in Parameters)
            {
                cmd.Parameters.Add(param);
            }
            int iReturn = 0;
            try
            {
                conn.Open();
                cmd.ExecuteScalar();

                for (int i = 0; i < Parameters.Count; i++)
                {
                    if (Parameters[i].Direction == ParameterDirection.Output)
                    {
                        Parameters[i].Value = cmd.Parameters[Parameters[i].ParameterName].Value;
                        iReturn = Int32.Parse(Parameters[i].Value.ToString());
                    }
                }
            }
            catch(Exception ex)
            {
                iReturn = Int32.MinValue;
            }
            finally
            {
                conn.Dispose();
            }
            return iReturn;
        }

        #endregion

       
    }
[/code]

So the database access class implements the interface, and returns the appropriate values. Now in my next posting we will see how we can use this class to access the database, but also we will see how we can inject some code, and change the behaviour without changing the structure.

 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C# | TDD
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

TDD, Rhino.Mocks

Wednesday, 30 April 2008 04:22 by volkanuzun

I am pretty new to testing your codes using nunit and rhino.mocks. i am having lots of problems and thank to Tom Opgenorth, i solve each of these slowly. From today, i will be sharing the difficulties i have in my TDD world. I am pretty new to testing, so a

To test every single function in your code, the whole programming paradigm has to change. you have to break your code into smallest available pieces that allows to you to write test functions. It seemed to me at the beginning that you lose some performance doing so but with today's hardware, you concentration should be on maintable, working, bug free, tested code. So in the next posting, i will share one of my simple class, and how i used nunit to test simple things.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   TDD
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Google's inaccurate search results

Monday, 21 April 2008 02:57 by volkanuzun

I am writing a search page for our campus using google search applicance. Within my application i called a httprequest to google's mini machine, and parse the returning xml file. Depending on the number of results returned from google (it is a parameter in the xml file) i am creating the pagination. However it wasnt working, i was debugging my code, and reading google's documentation. Guess what, google never tells you how many search results there are, it just guesses the number of search result but as soon as you click on other pages, you might get nothing :), and different estimation. I tried this with google, search anything at google, and note down the number of results , and click page 2; the number of results are changed right :)

waoov so they are just guessing baby...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Lots of things going on

Sunday, 20 April 2008 16:51 by volkanuzun

I am kinda busy in the last few weeks. Lots of things happening at the same time :). I've started teaching asp.net ( a free class ) every saturday at California State University, San Bernardino. This class keeps me kinda busy, also i adopted a new hobby : baking bread :)). I really enjoy it, and every week i try to bake 3 different types of bread. Below are some photos :)

 



This week,it was my 4th of class. At the first class, there was a lot of people, nearly 25 people, but the more advanced classes become the less people show up. So at the last class, it was between 8-10 people now :). Dramatic change ha !!  I try to post the agenda, questions, assignments in the forum : http://www.iedotnetug.org.  By the way this is a really good user group, if you live around san bernardino, redlands, riverside etc, please join our meetings.  By the way, let me upload some more photos :) below is two photos from my classes :

 



hopefully i will be writing more ...

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Silverlight

Wednesday, 2 April 2008 09:21 by volkanuzun

I was writing a simple silverlight application to test my basic understandings of silverlight. My app will make get http request to a page, and lists the items on the silverlight listbox component. Of course it didnt work :), cause i used HttpWebRequest which is synchronous. Microsoft removed the synchronous web request from silverlight 2.0, and i have no idea why :)

so, what i did is, created a simple aspx page, which does the webrequest , and silverlight makes the request to my aspx file. So i dont to deal with crossdomain.xml files on the other hosts and things become easier :)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

LINQ queries are deferred :)

Friday, 28 March 2008 02:52 by volkanuzun

Ok, probably we all heard that linq queries are deferred, so be careful bla bla.

Why is it deferred ? i think for performance, and resource use. By what makes linq queries less resource dependent ?
Let's have a quick look at the Where extension method.

[code:c#]
public static IEnumerable<source>Where<source>(this IEnumerable<source> sourcelist, Func<source>, Boolen>predicate)
{
    foreach(source element in sourcelist)
    {
         if(predicate(element) yield return element;
    }
}
[/code]
 

We can see that Where is an extension method (the first parameter is marked with "this" and it is a static function) of any IEnumerable object. 
What basically it does is to iterate through each element in the collection (IEnumerable collection), calling the function predicate for each element,
and if the element returns true in the predicate function; return the element. But it is smart enough not to return all the elements in once,
in stead it uses yield. yield retuns the current element and waits for the next call to return the next element, this makes it more effecient.
Also where method returns an IEnumerable object which means the result can be appended to Select, Where etc etc.

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   Linq
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Resharper is GREAT

Friday, 21 March 2008 11:42 by volkanuzun

Since i installed resharper ( few days ago ), i enjoy using vs 2008 more. Not only it helps me to write fast code, it also teaches me better coding :)

You wonder how ? When i have a data representing class, i always overload ==,!=, Equals, GetHashCode() functions, such as:

    public override string ToString()
        {
            return Name;
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            if(obj == null)
                return false;
            Branch temp = (Branch) obj;
            return temp.Name.ToLowerInvariant().Equals(this.Name.ToLowerInvariant());
        }

        public static bool operator==(Branch d1, Branch d2)
        {
            object o1 = (object) d1;
            object o2 = (object) d2;
            if( (o1== null) ||(o2==null))
                return false;

            return d1.Equals(d2);
        }

        public static bool operator !=(Branch d1, Branch d2)
        {
            return !(d1 == d2);
        }

[/code]

 

Today while i was doing the same thing for another class, right before i was going to overload, resharper's yellow icon poped up, i hit insert enter, and resharper asked me if i want to overload members, i click sure go ahead, here is the resharper code which is a lot smarter than mine:

public bool Equals(Counselor counselor)
        {
            if (counselor == null) return false;
            return Equals(Email, counselor.Email);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as Counselor);
        }

        public override int GetHashCode()
        {
            return Email != null ? Email.GetHashCode() : 0;
        }

 

[/code]

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Twitter

Thursday, 20 March 2008 04:16 by volkanuzun

I signed up for this mini blogging site with one of my friend's invitation. At first i said, why i am gonna use this at all.

Now i find it fun, and usefull :). u can track who/where/what/when/whom/how kinda things 

Be there, add me : volkanuzun 

http://www.twitter.com 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Visual Studio 2008, Sql Server 2008 Launch Event

Tuesday, 18 March 2008 03:35 by volkanuzun

We've finished our launch event, We were the first in southern california i guess :). I think it was pretty good, there are some stuff that we have to work on, but we ll get better i promise :)

You can see some of the photos here : http://www.flickr.com/photos/iedotnetug/

James summarized the event as :


George Ande – ASP.NET Ajax with .NET 3.5
Sean Dorsett – Visual Studio 2008 Tips and Tricks
Volkan Uzun – New features of C# 3.0
Steve O’Brien – LINQ
Matt Penner – GIS and Spatial Analysis in SQL 2008
Cigdem Uzun – Silverlight 2.0
 
While the attendance was not as much as I had thought, based on the VS 2005 Launch at ITT Technical Institute (overloaded with tech students), here are some details:
 
RSVP’s:  36
Actual Attendance: 34 (a IEDOTNETUG Record!)
Non RSVP Attendees: 8
First Time Attendees: 11 (each one came to me, stating they would be back)
Total Raffle Ticket Sales: 364 (oh my!)
Number of software licenses (VSTS 2008, SQL 2008, WS 2008, telerik, CodeSmith, ReSharper, Infragistics) won: 38
Number of books (O’Reilly, Wrox, Pearson) won: 22 (jeez, I just got those too)
Number of job offers mentioned after break: 4
Pizza slices left over: 1

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

operator== overloading and null check problem

Sunday, 16 March 2008 07:44 by volkanuzun

For a project i am working on, i wrote a WebSite class, which will hold information about a web site. In the database the web sites should be unique, and by business rules uniquness is defined as, no same name web site shall exist twice, no same urls shall exist twice; so in my website class i overloaded == sign to check for these two properties such as :

public static  bool operator == (WebSite site1,WebSite site2)
{
   return site1.Equals(site2);
}

public override bool Equals(object obj)
{
    WebSite temp = (WebSite)obj;
    if(this.Name==temp.Name) return true;
    if(this.Url==temp.Url) return true;
    return false;

}
[/code]

 

At the first glance, the code seemed right to me; however what is WebSite2 is null, so we should check it right ? i changed the code as below:

and... my code broke. Himm where was the problem ? there is a recursive call in the null check :) so i  have to typecast upto object before  i do the null check, or before typecasting it to website i have to do the null check such as :

 

By the way i catch this error with unit testing :)) 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed