Displaying articles with tag .net

.Net Source Code

Posted by gabriel, Sat Oct 04 15:30:00 UTC 2008

Have you ever wondered what’s behind all the classes you use in the .Net framework? Now that Microsoft opened the code you can have a pick at it.

I think that the looking at this code is a great way to learn and also be a better programmer since you will understand what happens behind the scenes. If you have a doubt if some API or control is the source of a performance problem you can take a look for yourself.

VisualStudio let’s you download the code as needed during debug but there’s a great tool called NetMassDownloader that will allow you to download all the code at once. The total size of the source code is about 170 MB.

There’s also a good post on the CodeProject site that will show how to set it up with VisualStudio: http://www.codeproject.com/KB/dotnet/netmassdownloader.aspx.

Have fun.

0 comments | Filed Under: | Tags: .net

Set a property of a server tag dynamically

Posted by gabriel, Sun Sep 28 11:49:00 UTC 2008

Setting a property of a server tag is pretty standard stuff:


<asp:TextBox ID="TextBox1" runat="server" Text="My name is Gabriel" />

Now, what if you want to use a class to set the value?


<asp:TextBox ID="TextBox1" runat="server" Text='<%= DateTime.Now %>' />

This will give you an error like this:

Server tags cannot contain <% ... %> constructs

If you ever need to solve this kind of problem I found a very interesting solution in the Infinites Loop Blog

It’s a very clever solution to use the Expression Builders, introduced in the Asp.Net 2.0 feature, to let you execute your custom code within the server tags.

0 comments | Filed Under: | Tags: .net

Passed 70-529 today

Posted by gabriel, Thu Aug 21 08:32:00 UTC 2008

I just passed the 70-529 exam and now I’m a MCTS Web and Distributed Applications. For those that are still thinking of taking this exam here are a few tips.

Usually I use Microsoft preparation books to study for certifications. This time I started using a book from the same collection:

MCTS Self-Paced Training Kit (Exam 70-529): Microsoft .NET Framework 2.0 Distributed Application Development

I have to say that I didn’t like this book. I didn’t think that the content was well approached and the writing style was also not for me. I still followed the book to the end but I had to complement it with two other books, one the had a good web services section and another that had a good remoting section. These books are:

Pro ASP.NET 2.0 in C# 2005 (This one complements the web services part)

Pro C# 2005 and the .NET 2.0 Platform (This one complements the remoting part)

Also a good starting point is the articles on the 4 Guys from Rolla that will give you a pretty good introduction to web services and it’s best if read before you read any of the books above.

Next week I’ll go on vacation and when I come back I’ll start my studies towards the MCPD Web Developer certification. I should take the test by the end of November. I’ll let you know how this goes.

2 comments | Filed Under: News | Tags: .net

LINQ: OrderBy with nullable columns in TypedDataSets

Posted by gabriel, Mon Aug 11 12:24:00 UTC 2008

This article shows a tip on how you can do sorting using the LINQ OrderBy with Typed DataSets.

For our example I’ll use the the Northwind Database and it’s Customers table.

I’ll use two columns in this table. One is the ContactName which doesn’t have any null values and the Region column which has null values.

First lets populate the DataTable we want to query using TableAdapter I had previously generated in the DataSet.


CustomersTableAdapter ta = new CustomersTableAdapter();
DataSetNorthwind.CustomersDataTable dt = ta.GetData();

I want to use LINQ select all values ordering them by the Region column (which may be null). So here is the initial idea:


            var query = from r in dt.AsEnumerable()
                        orderby r.Region
                        select r;

Ok, no compilation errors but when you run the query you will get an error:

The value for column ‘Region’ in table ‘Customers’ is DBNull. -> System.InvalidCastException: ...

If you think about it this is expected. The nullable columns in the DataSet all have an IsNull method to check if the column is null or not and avoid this kind of error. We are going to use the IsRegionNull() method in our favor to help us solve the problem:


var query = from r in dt.AsEnumerable()
        orderby (r.IsRegionNull() ? "" : r.Region)
        select r;

I used the ternary operator to check if the column region is null or not. If it is then I’ll use an empty string as the value, if it’s not null I can call the Region property to get the value.

To see the ending result you can print all the values:


foreach (DataSetNorthwind.CustomersRow row in query)
{
     Console.WriteLine("{0} - {1}", row.ContactName, 
          row.IsRegionNull() ? "" : row.Region);
}

Of course you could have filtered out the rows with null regions, but the goal here is to show what you can do to order the rows when you have a column with values that may be null.

1 comment | Filed Under: Tips and Tutorials | Tags: .net

Get the number of business days between two dates

Posted by gabriel, Wed Aug 06 22:57:00 UTC 2008

Here’s a simple way of getting the number of business days between two dates using C#.


            DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) && (dtBegin.DayOfWeek != DayOfWeek.Sunday))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }

You can enhance this method consulting a list of holidays to check if the current date is indeed a business day. For this you have to have the list of holidays somewhere. In our example I’ll create a fake method that will provide the holidays list.


        public static void CalculateNumberOfWeekdays()
        {
            DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);
            List<DateTime> holidays = GetHolidays();

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) 
                    && (dtBegin.DayOfWeek != DayOfWeek.Sunday)
                    && (!holidays.Contains(dtBegin)))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }
            Console.WriteLine(dayCount);
        }

        public static List<DateTime> GetHolidays()
        {
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(2008, 8, 7));
            return holidays;
        }            

See you next time.

1 comment | Filed Under: Tips and Tutorials | Tags: .net

DataSet Designer (Editor) Missing

Posted by gabriel, Sat Jun 14 15:03:00 UTC 2008

This week one of my co-workers had a strange problem with his VisualStudio 2008. All the sudden he couldn’t view the DataSet designer in any applications. When the DataSet file was clicked all that it showed was the XML file, no sign of the Designer.

We don’t know what happened but as I tried to figure out the problem I found that there’s very few information about this problem on the Internet, so I decide to blog about it so that it might help someone in distress.

If you’re having this problem you might first try to right click the DataSet file and then select the Open With… option. A list of editors will show, if you don’t see the DataSet Editor then you you have the same problem we did.

I have found a few posts about it, here are the solutions proposed:
  • Run the following command in the VisualStudio prompt: devenv /resetsettings
  • Run the following command in the VisualStudio prompt: devenv /setup
  • With Visual Studio setup disc select the Repair option.
  • Re-install Visual Studio.
All these are valid solutions and I found people on the web who claimed that this helped them but for my unfortunate teammate it didn’t help. The only thing that did it for us was:
  1. Remove VisualStudio
  2. Delete any folder left from VS installation
  3. Install VisualStudio

Finally, problem solved! I know this is not an optimal solution, far from it but at the end of the day it works. Nothing else did. I hope this post helps some else.

1 comment | Filed Under: | Tags: .net

Problem with FormView inside UpdatePanel

Posted by gabriel, Fri Jun 06 00:11:00 UTC 2008

Today I struggled for a while with a FormView that for no apparent reason wasn’t updating some of my fields to the database. After sometime I noticed that the fields that were not getting inserted into the database where the ones I had wrapped inside an UpdatePanel. Coincidence? I don’t think so…

I did a few tests and noticed that that was the problem indeed. I can’t say exactly what is the problem but it seems like that the FormView doesn’t like to have it’s fields inside an UpdatePanel.

The way I found to get around this issue is to populate the parameters manually in the events of the ObjectDataSource (ODS). So if you’re trying to insert a record you might using the Inserting event of the ODS to populate the problematic paramters:


    protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        e.InputParameters["FirstName"] = ((TextBox)FormView1.FindContro("TextBoxFirstName")).Text;
        e.InputParameters["LastName"] = ((TextBox)FormView1.FindContro("TextBoxLastName")).Text;
        e.InputParameters["City"] = ((TextBox)FormView1.FindContro("TextBoxCity")).Text;
    }

In the Inserting event of the ODS the InputParamters have already been populated (at least the ones outside the UpdatePanel) but the record hasn’t been inserted yet, so you are intercepting the parameters, adjusting it’s values and then letting it continue with the insertion.

I hope this code spares someone to have to go through the tests I had to do.

0 comments | Filed Under: Tips and Tutorials | Tags: .net

GridView: Select last inserted record

Posted by gabriel, Tue May 06 14:09:00 UTC 2008

The other day a responded a post on the asp.net forums about this so I think it might be useful to others.

Imagine if you have a GridView using pagination. When you insert a new record using a DetailsView or a FormView you want this new record to be automatically selected on the GridView, even if it’s not at the same page (of the GridView) that you currently have selected.


//returns a collection of records, including the one you just inserted
DataRowCollection drc = Dal.GetData();

//RecordID is the id of the record you just inserted, 
//you need to store this somewhere when you insert the record
DataRow dr = drc.Find(RecordID);

//having found the datarow of the record you need to know it's position(index) in the results
int index = drc.IndexOf(dr);

//Get the page the record will appear on
int page = index / GridView1.PageSize;

//If you're not already on the right page, set the PageIndex to the correct page
if (GridView1.PageIndex != page)
{
     GridView1.PageIndex = page;
}

 //gets the index of the record in the page
GridView1.SelectedIndex = index - (page* GridView1.PageSize);

0 comments | Filed Under: Tips and Tutorials | Tags: .net

Cache using Dynamic LINQ and Generics

Posted by gabriel, Sat May 03 09:27:00 UTC 2008

You know those tables in your systems that are almost static (never change) by are consulted thousands of times a day? Well, the other day at work some asked me if we could avoid all this trips to the database.

The solution I came up with creates a cache at our BLL (Business Logic Layer) avoiding DAL layer to be called. First of all our base architecture is based on the principles on the asp.net tutorial Creating a Business Logic Layer. This article basically creates something very similar to a proxy pattern before the DAL which gives me the perfect place to intercept any calls to the DAL and consult my cache.

To avoid the trip to the database, when the BLL is instantiated I do one query to the database which returns all the records in the table. The resulting DataTable is stored in my cache class which is declared as static in the class. This will make possible that the cache is populated only once. All subsequent queries will fetch the results from the Cache instead of making a trip to the database.

The cache table is very simple. It stores a DataTable and performs filters in it using LINQ syntax. I had other options but since I was starting to work with LINQ at the time it seemed like a good choice. For this code I use the Dynamic LINQ which I mentioned in my previous post.

In order to work with TypedDataSets (which was a requirement for me) I create the Cache class to accept the DataTable and DataRow types.


    public class CacheDataTable<T, S>  where T : DataTable where S : DataRow
    {
        private T cacheDataTable;

        //stores the DataTable that will be used for future consults
        public CacheDataTable(T dataTable)
        {
            this.cacheDataTable = dataTable;
        }

        //returns a DataTable filtered by the expression
        public T GetData(string expression, params object[] values)
        {
            IEnumerable<S> tmp = ((IEnumerable<S>)cacheDataTable).AsQueryable().Where(expression, values);
            return getDataTablePopulated(tmp);
        }

        //returns all the records
        public T GetData()
        {
            return getDataTablePopulated((IEnumerable<S>)cacheDataTable);
        }

        //takes an enumeration and creates a new DataTable
        private T getDataTablePopulated(IEnumerable<S> rows)
        {
            T dt = Activator.CreateInstance<T>();
            foreach (S row in rows)
            {
                dt.ImportRow(row);
            }
            return dt;
        }
    }

After having the Cache class defined you can use it in the BLL like this:


public class CountryBLL
{
        CountryDAL dal;

        //the cache is static so that it is shared among all instances from the CountryBLL class
        private static CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow> cache;

        public TBG_CountryBLL()
        {
            dal = new CountryDAL();
            //tests if the cache class has not been created yet. Only happens at the first access
            if (cache == null)
            {
                cache = new CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow>(dal.GetData());
            }
        }

        public DataSet1.CountryDataTable GetData()
        {
            //gets all records from the cache
            return cache.GetData();
        }

        public DataSet1.CountryDataTable GetDataByPK(decimal id)
        {
            return cache.GetData("id == @0", id);
        }
}

Coded like this the CountryBLL will only cause a database connection at its first instantiation. This approach should only be used with tables which are static (or almost). If one record is inserted in this table it would demand the application to be restarted so that the static cache variable would be unloaded and created again. There are ways around this but it is not the objective of this post.

Hope this will help someone :-)

0 comments | Filed Under: Tips and Tutorials | Tags: .net