Monday 8 December 2008

Free subversion hosting

Found this cool website that allows you host up to 5 svn repositories, and supports xp agile project management.

The site is http://www.xp-dev.com

Thursday 27 November 2008

Convert XML to a DataSet and visa versa in C#

Simple... but for my own reference:

/// 
/// Convert the xml string into a DataSet object
/// 
/// The xml string to convert
/// The DataSet instance
public DataSet ConvertXmlToDataSet(string xml)
{
using (StringReader reader = new StringReader(xml))
{
using (XmlTextReader xmlReader = new XmlTextReader(reader))
{
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlReader);
return dataSet;
}
}
}

/// 
/// Converts a DataSet into an xml string representation
/// 
/// The DataSet to convert
/// The xml string representation of the DataSet
public string ConvertDataSetToXml(DataSet dataSet)
{
using (StringWriter writer = new StringWriter())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(writer))
{
dataSet.WriteXml(xmlTextWriter);
return writer.ToString();
}
}
}

Friday 7 November 2008

JQuery and ASP.NET Ajax ready and pageLoad Solution

I had a problem the other day with the JQuery ready function not firing on an Aspc post back. I found this useful article

The problem seems to be that the jQuery ready function is not called on an async postback. The pageLoad() ASP.NET ajax method is called however.

It seems that ASP.NET ajax and jQuery don’t get along together when it comes to the DOM load event, and ASP.NET ajax takes preference to the jQuery ready function.

So in short replace all jQuery: $(document).ready() instances in your code with function pageLoad(). This I think is a more elegant solution then intercepting the end_request event and altering the master page.

Wednesday 5 November 2008

Generic function to obtain data from a DataRow

Sometimes it may be useful to have one generic function that can parse data from a DataRow column into the type you require.

For example: Perhaps you have an Employee object with the properties Id, Name and Salary, of types int, string and decimal.

Here is an example of some code to populate a list of Employee objects using a generic function.

public void LoadData()
{
IList employees = new List();
DataTable result = // Get data from SP
foreach (DataRow row in result.Rows)
{
Employee employee = new Employee();
employee.Id = GetColumnData<int>("EMP_ID", row, null);
employee.Name = GetColumnData<string>("EMP_NAME", row, "Unknown");
employee.Salary = GetColumnData<decimal>("EMP_SALARY", row, null);
employees.Add(employee);
}
}

/// 
/// Gets data from a column checks it can convert it correctly if no data or invalid casting the default
/// value is returned
/// 
/// The type of data to convert too
/// The name of the column in the row
/// The row containing the data
/// The default value
/// The data or the default value
public static T GetColumnData<T>(string columnName, DataRow row, object defaultValue)
{
if (row.Table.Columns.Contains(columnName) && row[columnName] != DBNull.Value)
{
string value = row[columnName].ToString();
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
object result = converter.ConvertFromString(value);
try
{
return (T)result;
}
catch (InvalidCastException)
{
return (T)defaultValue;
}
}
else
{
return (T)defaultValue;
}
}

Monday 3 November 2008

TryParse functionality on Generic objects

John Liu has a nice code snippet on implementing the TryParse functionality on generic objects.

Friday 31 October 2008

Using JavaScript or C# to calculate feet and inches to metres and visa versa

Here are some code snippets for JavaScript and C# that show how to convert from say for example 26' 5" into metres 8.05m. The snippets also show converting metres to foot and inches.;

HTML:
<input id="feet" type="text" onkeyup="calculate 'feet')" /> '
<input id="inches" type="text" onkeyup="calculate('inches')" /> "
<input id="metres" type="text" onkeyup="calculate('metres')" />

JavaScript:
<script type="text/javascript">
function calculate(src) {
switch (src) {
case feetCtrl:
calculateFeetAndInchesToMetres();
break;
case inchesCtrl:
calculateFeetAndInchesToMetres();
break;
case metresCtrl:
calculateMetresToFeetAndInches();
break;
}
}

function calculateFeetAndInchesToMetres() {
var feet = $get("feet").value;
var inches = $get("inches").value;
var totalInches = feet * 12;
totalInches = totalInches + (inches * 1);
var cm = totalInches * 2.54;
var metres = cm / 100;
$get("metres").value = metres.toFixed(2);
}

function calculateMetresToFeetAndInches() {
var metres = $get("metres").value;
var metreInches = metres * 39.370078740157477;
$get("feet").value = Math.floor(metreInches / 12);
$get("inches").value = Math.floor(metreInches % 12);
}
</script>

Same functionality in C#
/// 
/// Gets the feet and inches representation of a metric value
/// 
/// The metres to use
/// The correct display string
public static string GetFeetAndInches(double metres)
{
Hashtable values = GetFeetAndInchesValues(metres);
double feet = (double)values["Feet"];
int inches = (int)values["Inches"];
StringBuilder result = new StringBuilder();
string feetText = feet.ToString();
string[] data = feetText.Split('.');
if (data.Length > 0)
{
feetText = data[0];
}
result.Append(feetText);
result.Append("'");
if (inches > 0)
{
result.Append(" ");
result.Append(inches);
result.Append("\"");
}

return result.ToString();
}

/// 
/// Gets the feet and inches of a metric value
/// 
/// The metres to use
/// An array of feet, inches
public static Hashtable GetFeetAndInchesValues(double metres)
{
Hashtable result = new Hashtable();
double metreInches = metres * MetreToInchesRatio;
double feet = metreInches / 12;
int inches = Convert.ToInt32(metreInches % 12);
result.Add("Feet", feet);
result.Add("Inches", inches);

return result;
}

/// 
/// Gets the metre equivalent of feet and inches combination
/// 
/// The foot value
/// The inches value
/// The metre value
public static double GetMetresFromFeetAndInches(double feet, int inches)
{
// Sourced from: http://sg.answers.yahoo.com/question/index?qid=20070403095853AA3FKJZ
double totalInches = feet * 12;
totalInches += inches;
double cm = totalInches * 2.54;
double metres = cm / 100;

return metres;
}

Wednesday 8 October 2008

Got this error: syntax error. _getAbbrMonthIndex using auto complete extender

All the solutions I searched for suggested there was an error with my JavaScript or code. They were right!

My problem rose because I had a control on a page which had a script manager proxy control and a bunch of autocompleteextender control's, these extender controls used a scriptpath that pointed to a static web method (page method) on the page that retrieved the nessacary data.

The error arose becuase I was adding to my script manager proxy class a reference to the same page method programtically in the page load method. Anyway removing the programatic inclusion to the script manager solved the problem.

Thought this may help others debug any similar scenarios.

Wednesday 1 October 2008

Export to Excel using ASP.NET

I wanted to create a very simple excel export, from an asp.net 2.0 web application, that would take data and display it somewhat like this:



I used the following C# code. Which can be place within a LinkButton, or Button click event handler:

byte[] data = Encoding.UTF8.GetBytes("
Column 1Column 2
Data 1Data 2
Data 3Data 4
"); Response.Clear(); Response.ClearHeaders(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "filename=test.xls"); Response.BinaryWrite(data); Response.End();


As you can see I've used an HTML table as the source of the data. You can also style this and Excel will display it correctly using any CSS you provide.

The name of the file is also set to "test.xls" using the header content-disposition.

Friday 12 September 2008

Scrapping data using C#

Found an interesting article about screen scrapping here. Didn't think it was that easy. Here is some C# code that gets google's homepage data.

WebClient webClient = new WebClient();
string url = "http://www.google.com";
byte[] dataArray = webClient.DownloadData(url);
UTF8Encoding encoding = new UTF8Encoding();
string data = encoding.GetString(dataArray);


Once you have the data string you can do your own parsing to use the data.

TFS 2005 to TFS 2008 upgrade

Ran into a bit of an issue today when upgrading to TFS 2008. What we did was create an identical copy of TFS 2005 server (the live machine) to a new cloned server.

I then started to follow the directions laid out by Mathias here (Very useful)

The problem is I began to uninstall on the "clone" server and all of a sudden our live TFS server started to report errors. I found a useful post here detailing the error and the reasons.

Basically what it boils down to is the TFS clone server has the original live server's name configured as the database tier. So as I uninstalled it on the clone server it was actually removing stored procedures on the live server. Not good!!!

We resolved this my reverting back to the previous nights backup.

So be aware of this when installing TFS 2008 on a cloned machine.

Thursday 11 September 2008

CS0433: The type {0} exists in both Temporary ASP.NET Files dlls

I ran into this bug today and found a really simple solution that worked for me. Hopefully it can help others.

Bug:
CS0433: The type 'ASCX' exists in both '..Temporary ASP.NET Files\{0}.dll' and '..Temporary ASP.NET Files\{1}.dll'

Solution:
In your Visual Studio solution. Clean the entire solution. Then rebuild the entire solution.

Wednesday 10 September 2008

Simple example how to resize images using C#

The other day I needed to resize images with a width greater than 500px to a new width of 250px, but also keeping the height in proportion to the width. Below is a snippet of code I used to achieve this.

using System.Drawing;
using System.Drawing.Drawing2D;

string targetPath = "C:\\TestImage.jpg";
string destinationPath = "C:\\TestImage_New.jpg";
int newWidth = 200;
Image image = Image.FromFile(targetPath );
if (image.Width > 500)
{
    float percent = (float)newWidth / (float)image.Width;
int newHeight = (int)(image.Height * percent);
Bitmap bitmap = new Bitmap(newWidth, newHeight);
Graphics graphics = Graphics.FromImage((Image)bitmap);
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
graphics.Dispose();
image.Save(destinationPath);
} 

Tuesday 15 July 2008

Oracle date function to add or subtract days, years, months, minutes, hours or seconds

Hi

I recently created this function to calculate the date result when adding or subtracting two dates in oracle. May be useful to others so here it is:

CREATE OR REPLACE Function FOCUSTEST.DateADD(
v_datePart  VARCHAR2
, v_value     NUMBER
, v_date      TIMESTAMP)
RETURN TIMESTAMP
AS
v_result    TIMESTAMP;
BEGIN

IF (UPPER(v_datePart) = 'YY') THEN
v_result := ADD_MONTHS(v_date, (v_value * 12));
END IF;
IF (UPPER(v_datePart) = 'MM') THEN
v_result := ADD_MONTHS(v_date, v_value);
END IF;
IF (UPPER(v_datePart) = 'DD') THEN
v_result := v_date + v_value;
END IF;
IF (UPPER(v_datePart) = 'HH') THEN
v_result := v_date + (v_value / 24);
END IF;
IF (UPPER(v_datePart) = 'MI') THEN
v_result := v_date + (v_value / (24 * 60));
END IF;
IF (UPPER(v_datePart) = 'SS') THEN
v_result := v_date + (v_value / (24 * 60 * 60));
END IF;

DBMS_OUTPUT.PUT_LINE(v_result);
RETURN v_result;

END;

Wednesday 13 February 2008

Obtaining generic list item instances using reflection

I've decided to use my blog as a space to share what I think may be useful links, code examples, and information about ASP.NET, C# and general software engineering tips or workaround's I may have come upon.

So let me begin with a simple bit of code that may prove useful to some people.

I had a problem where I was using reflection that required a method to be invoked. This method returned a generic list of items. The problem was that using reflection the type that was returned from the method was "System.Collections.Generic.List`1[T]", and I needed a way to loop through the actual items in the list, in order to check types and property values.

The solution is pretty straightforward. There is a method in a generic list object that allows you to retrieve a single item based on it's index. The method name is "get_Item". Below is a small section of C# code that will show you how it works:

// Create an instance of the type you require
Type myType = "AssemblyName.TypeName, AssemblyName";
object instance = Activator.CreateInstance(typeof(myType));
// Invoke the method
MethodInfo method = myType.GetType().GetMethod("MethodName");
// The list object is of type "System.Collections.Generic.List`1[T]"
object list = method.Invoke(instance, null);
// Get the list item count
int listCount = (int)list.GetType().GetProperty("Count").GetValue(list, null);
// Loop though generic list
for (int index = 0; index <= listCount; index++)
{
// Get an instance of the item in the list
object item = list.GetType().GetMethod("getItem").Invoke(list, new object[] { index });
// Now you have an instance of the item in the generic list
//....
// TODO: Place additional code here/
//....
}

Hope that may help some of you out there. :)