Skip to content

Refactoring in reusing code, and getting the latest DateTime record from the Database

September 14, 2012

(This post had been posted on my other wordpress blog, its here now!!)

Today had been a fairly busy day yet again, and I will discuss reusing old code in more detail from the previous post, in that refactoring is a good thing. You can observe certain bits of code that are repeated in the lists of code you write, and it may be a good idea for future maintenance to get that bit of repeated code and place this in a method.
For example, the inner bit of code inside this method had been repeated, so I placed this outside into a method called getSessionCount which returns a long integer (Int64) which can then be reused over and over again, in particular for my toggle switch method which is discussed on another post: –

private long getSessionCount()
{
long sessionCount = 0;

if (Request.QueryString[“subscriber”] != null && Request.QueryString[“date”] != null)
{
sessionCount = PortalStats.GetAllSessionsCountByDateBySubscriberID(Request.QueryString[“date”].ToString(), Convert.ToInt64(Subscriber.FindSubscriberByUsername(Request.QueryString[“subscriber”]).SubscriberID));
}
else if (Request.QueryString[“date”] != null)
{
sessionCount = PortalStats.GetAllSessionsCountByDate(Request.QueryString[“date”].ToString());
}
else
{
sessionCount = PortalStats.GetAllSessionsCount();
}

return sessionCount;
}

This saves looking at these bits of code that may be a bit long and repeated, if you change one part of the repeated code, the rest has to be changed which may take longer than necessary when rewriting code. So this saves a lot of time!

Another thing about why refactoring is good is that having done this, it saves me time when maintaining pages of code, I have reused the whole .aspx code in other pages that generate these reports, so its a good foundation to code!

One last thing I would like to talk in detail is the generating very dynamic reporting based on dates for PDFs, see my previous post on generating PDFs earlier this year. The problem that I had found out is that if you have old records of stats that you need the last two weeks of, you need to get the last record of the table holding the stats if you don’t rely on dates. So far I hard coded DateTime.Today which checks today’s date then used DateTime.AddDays(-14) which may not get any data if your database table holds records two months back. You may think that this wouldn’t worry you but it may happen if your database is under maintenance and no stats are stored for days on end.

Here is code which may help you counter this: –

long sessionCount = getSessionCount();

DataTable dtAllSessions;

dtAllSessions = CreateDataForSessions(Convert.ToInt32(sessionCount) – 1);

string latestDateString = dtAllSessions.Rows[0][“Month”].ToString() + “/” + dtAllSessions.Rows[0][“Day”].ToString() + “/” + dtAllSessions.Rows[0][“Year”].ToString();

System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
provider = new System.Globalization.CultureInfo(“en-US”);

DateTime value;
DateTime latestDate;
if (DateTime.TryParseExact(latestDateString, “M/d/yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
{
latestDate = Convert.ToDateTime(latestDateString, provider);
}

Response.Redirect(“../reports/SessionsStatsReport.aspx?format=pdf&date=” + latestDate.AddDays(-days + 1).ToShortDateString());

Not wondering too much about the method CreateDataForSessions() which basically stores data into the DataTable, you can see the code is dynamic in checking that the very last record of the table based on the method CreateDataForSessions() and stores into the dtAllSessions which is a datatable.

string latestDateString = dtAllSessions.Rows[0][“Month”].ToString() + “/” + dtAllSessions.Rows[0][“Day”].ToString() + “/” + dtAllSessions.Rows[0][“Year”].ToString(); gets the month, day and year column of that last row, and does a parse of the date using TryParseExact. If you seen this before, its quite handling parsing dates on strings, and makes sure to use M/d/yyyy for the Regular Expression as MM/dd/yyyy is very strict in that you need 0′s in front of single values which is a pain!

Last but not least, you can add this:-

if (DateTime.TryParseExact(latestDateString, “M/d/yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
{
latestDate = Convert.ToDateTime(latestDateString, provider);
}
else
{
latestDate = DateTime.Today;
}

if (days == 0)
{
Response.Redirect(“../reports/SessionsStatsReport.aspx?format=pdf”);
}
else
{
Response.Redirect(“../reports/SessionsStatsReport.aspx?format=pdf&date=” + latestDate.AddDays(-days + 1).ToShortDateString());
}

This makes it flexible in that if the parsing fails you always can refer to the latest date! So it can always get a date!
Then you can use a days variable used for toggling between the set days to view, days is:-

private static int days = 0;

I realized that having a static integer for holding the days would be easier than relying on a value in the dropdown list which based on my code was not what I wanted. And when days = 0, you see all the records!!

Hope for any of you who wants to get the latest record and switch between the number of records stored in the DataTable can find it useful!

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: