Creating objects that know when they have changed - using IsDirty and custom PropertyChangedEvent's

by Dominic Zukiewicz 9. October 2008 10:57
When working on a project recently, the data saved back to the database was huge. We are talking well over 100 properties. After talking to my Java buddy, he said that one way is to create an IsDirty method that returns if the object has changed state. The IsDirty() method is used to query the state of an object - if it has been modified or not. The implementation is up to the developer, but ultimately it's use can save you a trip to the data source. I have split this example into 3 stages: First attempt Refactored Event Handled N.B. This article helps someone in (archaic) .NE... [More]

Tags:

Framework

StreamReader.BaseStream.Position isn't changing after calling StreamReader.ReadLine()

by Dominic Zukiewicz 5. September 2008 13:28
I was trying to parse a file which was divided into numerous parts - each one 12 lines long. For debugging, I was interested in how fast the file was being read and processed and therefore looked at the StreamReader.BaseStream.Position property. Here is an example of what I was trying to do: class Program{ static void Main(string[] args) { string filename = @"C:\windows\windowsupdate.log"; string filenameBackup = filename + ".bac"; File.Copy(filename, filenameBackup); FileStream fs = new FileStream(filenameBackup, FileMode.Open, FileAccess.Read); Str... [More]

Tags:

Framework

Choosing the best way to compare text to empty strings

by Dominic Zukiewicz 3. July 2008 09:45
I don’t know about you, but when I’ve seen some string comparisons, some people use: string text = GetStringFromDB()   if( text != string.Empty ) DoThis(); This looks good, but its actually quite a long running process, as the CLR has to compare both strings character by character. It is much better to use String.IsNullOrEmpty to cater for this, or use .Length == 0 property, as this never changes and is computed when assigned. Here is what the String.IsNullOrEmpty method looks like: public static bool IsNullOrEmpty(string value) { if (value != null) { ... [More]

Tags:

Framework | Good practices

Making decisions easier for null values with the ?? (null coalescing) operator

by Dominic Zukiewicz 1. July 2008 15:50
When catering for null values, I use the ternary operator ?, which is used to do an inline IF statement. For example: public void CheckText(string text) { if(String.IsNullOrEmpty(text)) { throw new ArgumentException("Parameter is " + (text==null ? "null." : "empty.")); } //Other code here } This would allow you to cater for 2 exception cases: When the parameter is null, the exception message states "Parameter is null."; When the parameter is "", the exception message states "Parameter is empty."; Since testing for null is a fairly... [More]

Tags:

Framework

Retrieve the time elapsed in C# with the StopWatch class

by Dominic Zukiewicz 5. June 2008 09:57
When doing some performance testing, I used to use the DateTime and TimeSpan classes to retrieve the time elapsed - similar to this example: public static void PerformLongOperation(){ DateTime start = DateTime.Now;   //Long running operation Thread.Sleep(1500);   DateTime end = DateTime.Now; TimeSpan elapsedTime = end - start; Console.WriteLine("Operation took {0:F2} seconds to complete.", elapsedTime.TotalSeconds);} Okay, so its not THAT bad is it really. So lets just check what happens when the measurement is very minute:   public static void P... [More]

Tags:

Framework

Can my private methods be accessed from outside my assembly?

by Dominic Zukiewicz 26. March 2008 09:13
What happens if you try and access a private method in a class? Understandibly, the compiler will kick up a fuss because this breaks the laws of encapsulation. But is it still accessible? Well, the answer is YES, you can still access it from outside the class!! So lets look at what happens in the naive sense: class PrivateMethods { private int ReturnNumber() { return 5; } }   class Program { static void Main(string[] args) { PrivateMethods p = new PrivateMethods(); p.Retu... [More]

Tags:

Framework

MCPD Enterprise Application Developer

by Dominic Zukiewicz 20. March 2008 11:05
Last week, I passed my MCPD Enterprise Application Developer exam, covering: TS Application Development Framework MCTS Web Development MCTS Windows Development MCTS Distributed Applications MCPD Designing & Developing Enterprise Applications The Microsoft Certification route is an excellent qualification scheme that I heavily recommend to any developer wishing to extend their knowledge in any field of application development.

Tags:

Framework

What are Predicates and Actions?

by Dominic Zukiewicz 12. March 2008 07:46
.Net Framework 2.0 brought us a cleaner way to deal with multiple items in an Collection. Sometimes the code can be cluttered up with trivial statements, printing information, or selecting certain items because their properties signify the object is useful in some way. Predicates are a way of processing an array of values using a method call. The method call would process a single value (being called once for each index) and then returning a result. Depending on that result, will depend on if the processing continues or exits as the result may have been found. Actions are similar to pr... [More]

Tags:

Framework

Using delegates to simulate WaitHandle.WaitAll() calls for web service - Part 1

by Dominic Zukiewicz 7. February 2008 14:14
This article is part 1 of 2 articles. Wouldn't it be great if you could call a web service hundreds, if not thousands of times, and then just wait until the results come back, rather than doing it one at a time? The System.Threading namespace created WaitHandle.WaitAll(), but this is only useful for threads - how do you call lots of web services asynchronously, and then continue once they have all returned? Well, one could argue why don't you just call them synchronously? Good idea, but it just means that those extra seconds of time taken waiting, could be put to use by another web se... [More]

Tags:

Framework | Misc

DataSet.Merge() didn't merge tables correctly.

by Dominic Zukiewicz 1. February 2008 09:54
I was using DataSet.Merge() to merge rows returned by a SqlDataAdapter into one of the tables. The scenario was that I was enquiring a specific order/product in the database, and it would Fill() a temporary DataSet with the results. If there were no results, then I just continued. The code was something like: internal AuditableProduct[] GetAuditableProducts(int[] productIds){ DataSet allStatuses = new DataSet(); foreach(int product in productIds) { DataSet tempStatus = new DataSet(); SqlConn... SqlComm..... SqlDataAdapter da...... ... [More]

Tags:

Framework

What size is the System.Boolean data type? Is it 4 bytes?

by Dominic Zukiewicz 23. January 2008 14:25
A simple question. The bool values are true or false. Easy yes? How many bytes does it occupy? 4 bytes? 2 bytes? 1 byte? The actual answer is 1 byte, which you may expect, but the MCTS Application Development Framework exam states that the width of this field is 4 bytes! So how do we settle it? Even easier. Console.WriteLine("bool is {0} byte(s) long.", sizeof(bool)); //bool is 1 byte(s) long. Console.WriteLine("System.Boolean is {0} byte(s) long.", sizeof(System.Boolean)); //System.Boolean is 1 byte(s) long.

Tags:

Framework

GZipStream and DeflateStream does not decompress?

by Dominic Zukiewicz 31. October 2007 12:18
I spent hours looking over 4 or 5 lines of code concerning these compression/decompression streams to find out why it was compressing and not decompressing. The problem resulted in the decompression stream returning a zero length byte array for the resulting data. The problem also replicated itself as being too long. What went wrong? This works! //Decompress private static string Uncompress(byte[] compressedData) { MemoryStream ms = new MemoryStream(compressedData); MemoryStream uncompressedStream = new MemoryStream(); GZipStream gZip = new GZipStream(ms,... [More]

Tags:

Framework

Environment.CurrentDirectory isn't working for Windows Services

by Dominic Zukiewicz 18. October 2007 10:06
The admin's decided to run my Windows Service under the NetworkService account to improve security. The problem is that where I thought I was saving temporary files to the directory of my application using Environment.CurrentDirectory , it was retrieving C:\windows\system32 ???? I therefore had to change the way I retrieved the local directory to: string directory = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; This means that any logging files that used to be xxx.log, now have to give their full path.

Tags:

Framework | Windows Services

Connecting to Access databases in .NET.

by Dominic Zukiewicz 24. August 2007 13:05
Accessing Microsoft Access from .NET fairly straight forward through the OleDb adapters and connections. I haven't found a problem connecting to it through a Windows Application. When you try and connect to it from a website or web service, you might find some unhelpful E_NOINTERFACE errors. The reason is that Access was never designed to be accessed from a multi-threaded environment. Although Windows Applications can potentially be multi-threaded, the initial running process has the [STAThread] attribute, indicating that the process, as far as COM is concerned, is single threaded. Th... [More]

Tags:

Framework

Transactions over multiple databases

by Dominic Zukiewicz 21. August 2007 11:57
Updating multiple databases (maybe on different servers), but in a "all-or-nothing" fashion. Its something that you will come across at least once in your professional career. But how do you do it in .NET? Transactions work great if there's just one connection to one database at a time. But what happens if you want to update several databases? Microsoft thought of that too, using something called DTC (Distributed Transaction Co-ordinator). But that's in the COM/COM+ world and we don't want to touch that do we?? No! is the answer. Digging through the documentation (or Google :-P) you can... [More]

Tags:

Framework

Nullable types - useful for databases?

by Dominic Zukiewicz 21. August 2007 11:34
Overview Before .NET 2.0, if you wanted to choose a value that represented null, you had to fall back on the xxx.MinValue or xxx.MaxValue and then convert this value to NULL once the information was hitting the database. In order to make it easier, Microsoft thought that it was helpful to allow value types to be assigned null and therefore just plonk the value straight into database - correct!? Well ..... sort of. Conversion I've found nullable types aren't all "that". Lets take a quick example to see how they can be a handful to use: int? input = null; string strInput = Console.... [More]

Tags:

Framework

Loading your XmlDocuments correctly.

by Dominic Zukiewicz 27. April 2007 15:28
Considering how much XML is used and the amount of code I've written to read/write XML, I still make a common mistake! If you ever get this error: System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1. Make sure you are using the correct method for the XmlDocument class. For example: string xml = @"<xml version=""1.0""?><node><innerNode/></node>"; string filename = @"C:\\temp.xml"; StreamWriter sw = new StreamWriter(filename); sw.Write(xml); sw.Close(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(filename);  /... [More]

Tags:

Framework | Xml

Microsoft FxCop - Code Analysis

by Dominic Zukiewicz 19. April 2007 17:05
You may love it, you may hate it .... you may not know what it is! Its worth knowing about in any case and may help you become a better, consistent and able developer. You can read my article on it here: http://blogs.bdnet.co.uk/dominicz/archive/2007/04/19/FxCop---what-is-it.aspx

Tags:

Framework

Efficient string concatenation

by Dominic Zukiewicz 17. April 2007 12:41
Its always a good thing to know how to get the very best out of .NET. One area that is always overlooked is string concatenation. You have several ways to do this including: string x = "HELLO" + " " + "THERE"; string x = "HELLO "; x = x + "THERE"; string x = "HELLO "; x += "THERE"; string x = String.Concat("HELLO"," ","THERE"); Although these are syntactically correct, they eat memory up faster than a buffet lunch at a fat fighters convention! This is the process that is carried out by the application: string text = text + otherText; Allocates temporary memory large en... [More]

Tags:

Framework

Passing objects by value!?

by Dominic Zukiewicz 12. April 2007 13:09
Its one thing to pass objects by reference, but by value? Can you copy objects? Have a read of this to get a better understanding of how objects work, and what passing by reference is: http://blogs.bdnet.co.uk/dominicz/archive/2007/04/19/Passing-objects-by-value---is-it-possible.aspx

Tags:

Framework

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar