XML documents can reference optional documents that specify how the XML documents should be structured. These optional documents called Documents Type Definitions (DTDs) and Schemas.
There are two kinds of definition for schemas currently:
1. Microsoft XML Schema It uses the extension .xdr (XML-Data Reduced) you can check the attached files for the this Schema syntax, it is an xml document, but has special elements and attributes.
2. W3C XML Schema It uses the extension .xsd (XML Schema Definitions) also it is an XML Document with special elements.
The second approach, XSD Schema, has been
supported by Microsoft .NET Framework and is the best approach for .NET
developers. Schema files are a special kind of XML file that define the
structure of an XML file via some pre-defined elements and attributes.
Using this Schema file you can validate your XML file to
make sure it fits to your application's needs and validate the inputs in order to prevent any exception in your
code. The .Net framework gives you all the tools you need so that you can build XSD schemas and also validate them. First, let's see how can we create a schema using XSD.exe file (It comes with Visual Studio): The
XML Schema Definition tool generates XML schema or common language
runtime classes from XDR, XML, and XSD files, or from classes in a
runtime assembly. The following command generates an XML schema from myFile.xml and saves it to the specified directory xsd myFile.xml /outputdir:myOutputDir Consider that we have the following xml data file EmployeeList.xml: <EmployeeList> <Company ID="1"> <Employee>Employee11Employee> <Employee>Employee12Employee> <Employee>Employee13Employee> Company> <Company ID="2"> <Employee>Employee21Employee> <Employee>Employee22Employee> <Employee>Employee23Employee> Company> <Company ID="3"> <Employee>Employee31Employee> <Employee>Employee32Employee> <Employee>Employee33Employee> <Employee>Employee34Employee> Company> EmployeeList>
Now, execute XSD.exe on the xml data file: > XSD EmployeeList.xmlThe result xsd file EmployeeList.xsd will be : xml version="1.0" encoding="utf-8"? ><xs:schema id="EmployeeList" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="EmployeeList" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Company"> <xs:complexType> <xs:sequence> <xs:element name="Employee" nillable="true" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:simpleContent msdata:ColumnName="Employee_Text" msdata:Ordinal="0"> <xs:extension base="xs:string"> xs:extension> xs:simpleContent> xs:complexType> xs:element> xs:sequence> <xs:attribute name="ID" type="xs:string" /> xs:complexType> xs:element> xs:choice> xs:complexType> xs:element>xs:schema>
Second, now that we have our Schema let's see the steps that we need to do in order to validate against our schema (.NET 2.0): 1.
Read the XML file content as Stream, TextReader or XmlReader. 2.
Read the Schema file content as Stream, TextReader or XmlReader. 3.
Create a new instance of XmlSchema object. 4.
Set XmlSchema object by calling XmlSchema.Read() method and passing the
content of Schema file and ValidationEventHandler method address to it. 5.
Create a new instance of XmlReaderSettings object. 6.
Set ValidationType for XmlReaderSettings object to Schema. 7.
Add your XmlSchema object to XmlReaderSettings Schemas collection by
calling its Schemas.Add() method. 8.
Add your ValidationEventHandler method address to XmlValidationReader's
ValidationEventHandler handler. 9.
Create a new instance of XmlReader object and pass your XML file content
(as Stream or a Reader object) and XmlReaderSettings object to it. 10. Call
Read() method of the Reader or Stream object to contain your XML file content
in a loop to parse and validate it completely. 11. Add
your logic to ValidationEventHandler method you created to implement what you
want to be done in the validation process.
Here is the code to accomplish this: private void ValidatingProcess(string XSDPath, string XMLPath) { try { // 1- Read XML file content this.Reader = new XmlTextReader(XMLPath); // 2- Read Schema file content StreamReader SR = new StreamReader(XSDPath); // 3- Create a new instance of XmlSchema object XmlSchema Schema = new XmlSchema(); // 4- Set Schema object by calling XmlSchema.Read() method Schema = XmlSchema.Read(SR, new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); // 5- Create a new instance of XmlReaderSettings object XmlReaderSettings ReaderSettings = new XmlReaderSettings(); // 6- Set ValidationType for XmlReaderSettings object ReaderSettings.ValidationType = ValidationType.Schema; // 7- Add Schema to XmlReaderSettings Schemas collection ReaderSettings.Schemas.Add(Schema); // 8- Add your ValidationEventHandler address to // XmlReaderSettings ValidationEventHandler ReaderSettings.ValidationEventHandler += new ValidationEventHandler(ReaderSettings_ValidationEventHandler); // 9- Create a new instance of XmlReader object XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings); // 10- Read XML content in a loop while (objXmlReader.Read()) { /*Empty loop*/} }//try // Handle exceptions if you want catch (UnauthorizedAccessException AccessEx) { throw AccessEx; }//catch catch (Exception Ex) { throw Ex; }//catch } private void ReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs args) { // 11- Implement your logic for each validation iteration string strTemp; strTemp = "Line: " + this.Reader.LineNumber + " - Position: " + this.Reader.LinePosition + " - " + args.Message; this.Results.Add(strTemp); }
This article explains how you can extract all Tables, including Data, to an Excel file. Every Table will have it's own worksheet. The code does need an excel application installed on the server, while it's using Office Interop.
To get this code to work, you need to add a reference to Excel.dll by using Add Reference on the project and selecting Microsoft Excel 9.0 (or 10.0) Object Library from the COM tab on the Add Reference dialog.
And then import the following namespace:
Imports System.Runtime.InteropServices.Marshal
Now add the following class to your project:
Private Sub create(ByVal sDatabaseName As String) Dim dsTables As DataSet = New DataSet
'Get all Tables from database dsTables = getAllTables(sDatabaseName) 'Create Excel Application, Workbook, and WorkSheets Dim xlExcel As New Excel.Application Dim xlBooks As Excel.Workbooks Dim xlBook As Excel.Workbook Dim tblSheet As Excel.Worksheet Dim xlCells As Excel.Range Dim sFile As String
'File name for the excel file sFile = Server.MapPath("~\Sheets\" & sDatabaseName & "_data.xls")
xlExcel.Visible = False : xlExcel.DisplayAlerts = False xlBooks = xlExcel.Workbooks xlBook = xlBooks.Add
For i As Integer = 0 To dsTables.Tables.Count - 1 tblSheet = xlBook.Worksheets.Add tblSheet.Name = dsTables.Tables(i).TableName xlCells = tblSheet.Cells 'Fill all cells with data GenerateExcelFile(dsTables.Tables(i), xlCells) Next
'Remove initial excel sheets. Within a try catch because the database 'could be empty (a workbook without worksheets is not allowed) Try Dim SheetCount As Integer = xlExcel.Sheets.Count CType(xlExcel.Sheets(SheetCount - 0), Excel.Worksheet).Delete() CType(xlExcel.Sheets(SheetCount - 1), Excel.Worksheet).Delete() CType(xlExcel.Sheets(SheetCount - 2), Excel.Worksheet).Delete() Catch ex As Exception
End Try
'Save the excel file xlBook.SaveAs(sFile)
'Make sure all objects are disposed xlBook.Close() xlExcel.Quit() ReleaseComObject(xlCells) ReleaseComObject(tblSheet) ReleaseComObject(xlBook) ReleaseComObject(xlBooks) ReleaseComObject(xlExcel) xlExcel = Nothing xlBooks = Nothing xlBook = Nothing tblSheet = Nothing xlCells = Nothing 'Let the Garbage Collector know it can get to work GC.Collect()
'Export Excel for download Try HttpContext.Current.Response.ContentType = "application/octet-stream" HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(sFile)) HttpContext.Current.Response.Clear() HttpContext.Current.Response.WriteFile(sFile) HttpContext.Current.Response.End() Catch ex As Exception 'An exception will be thrown, but can just be ignored End Try
End Sub
To generate the individual sheets, the following Sub is used:
Private Sub GenerateExcelFile(ByRef table As DataTable, ByVal xlCells As Excel.Range) Dim dr As DataRow, ary() As Object Dim iRow As Integer, iCol As Integer
'Output Column Headers For iCol = 0 To table.Columns.Count - 1 xlCells(1, iCol + 1) = table.Columns(iCol).ToString xlCells(1).EntireRow.Font.Bold = True Next
'Output Data For iRow = 0 To table.Rows.Count - 1 dr = table.Rows.Item(iRow) ary = dr.ItemArray For iCol = 0 To UBound(ary) xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString Response.Write(ary(iCol).ToString & vbTab) Next Next xlCells.Columns.AutoFit() End Sub
And now the trick to getting all tables and data from a database:
Public database as String
Public ReadOnly Property getAllTables(ByVal sDB As String) As DataSet Get database = sDB Dim m_dshelp As DataSet = New DataSet getRequestedAllTables(m_dshelp) Return m_dshelp End Get End Property
Private Function getRequestedAllTables(ByRef p_dataset As DataSet) As Boolean
'Retrieve all tablenames from the database: Dim sSQL As String Dim dsTables As DataSet = New DataSet sSQL = "SELECT [TableName] = so.name, [RowCount] = MAX(si.rows) " & _ "FROM sysobjects so, sysindexes si " & _ "WHERE so.xtype = 'U' AND si.id = OBJECT_ID(so.name) AND si.rows > 0 " & _ "GROUP BY so.name " & _ "ORDER BY 2 DESC"
getData(sSQL, "Tables", dsTables)
'Loop thrue all tables and do a SELECT *. Then add them to the dataset For i As Integer = 0 To dsTables.Tables(0).Rows.Count - 1 sSQL = "SELECT * FROM " & dsTables.Tables(0).Rows(i).Item(0) getData(sSQL, dsTables.Tables(0).Rows(i).Item(0), p_dataset) Next End Function
Private Function getData(ByVal p_sql As String, ByVal p_table As String, ByRef pdataset As DataSet) As Boolean
Dim objDataAdapter As SqlDataAdapter Dim objcommand As SqlCommand objcommand = New SqlCommand(p_sql, getConnection) objDataAdapter = New SqlDataAdapter(objcommand) objDataAdapter.Fill(pdataset, p_table) End Function
Private Function getConnection() As SqlConnection If (ConfigurationManager.AppSettings("SQLPW") <> "") Then getConnection = New SqlConnection("Server=" & _ ConfigurationManager.AppSettings("SQLserver") & ";password=" & _ ConfigurationManager.AppSettings("SQLPW") & "; user=" & _ ConfigurationManager.AppSettings("SQLUser") & ";database=" & database) Else getConnection = New SqlConnection("Data Source=" & _ ConfigurationManager.AppSettings("SQLserver") & ";Initial Catalog=" & _ database & ";Integrated Security=True") End If End Function
It was all going so smoothly. Jason Whittington, Mark Smith and I were teaching the big DevelopMentor event here in Los Angeles (Guerrilla.NET) when my presentation on the ThreadPool took a nose dive. It started with a great joke involving Wilson (the volleyball from Cast Away).
Wilson and I built an application to compute a multiplication table where each computation was (artificially) slow. To speed it up we threw it at the thread pool using delegate.BeginInvoke. We figured that the ThreadPool would allocate 25 or so threads and the table would display quickly. Here's the expected output - pretty much the same thing we've seen since about .NET 1.0:
Each color represents the thread that did that computation.
For the last 7 years, the behavior has been that as the ThreadPool was overloaded, it would steadily start up new threads at the rate of one every 500 milliseconds until it hits its upper limit (typically). Using Performance Monitor (perfmon) we can watch the thread pool adding threads. It usually looks something like this:
Much to our surprise we saw completely different behavior. The thread pool added the first 15 or so threads quickly (as expected) but then stalled. New threads were not created every 500ms, instead they were added at increasingly long intervals. My demo took almost twice as long to run as it had the last time I did this demo a few months ago.
Jason, Mark, and I took this code, ported it back to .NET 1.1 and ran it side-by-side with .NET 3.5 and here's what we saw (blue = 3.5, red = 1.1):
As of .NET 3.5 the upper limit of the ThreadPool was increased: Knew that.
But, it appears that v3.5 of the CLR changes the policy for adding threads to the thread pool. Rather than adding threads regularly when under load the thread pool uses a logarithmic backoff. My colleague Jason Whittington remarked that this behavior looked similar to the behavior of the thread pool in "Rotor" (the shared-source version of the CLR). We speculated that this backoff algorithm makes sense given the new 250-thread per CPU maximum - it would take a long time to reach that if the runtime waits longer and longer to start a new thread. The 250-thread limits makes it less likely that your application will deadlock the thread pool, and the exponential backoff algorithm keeps the thread pool from creating too many threads too quickly.
Why should you care? Usually you won't, but it could have dramatic impact if you count on that behavior. For example, in our contrived case, .NET 1.1 ran about twice as fast as .NET 3.5 ( ! ):
Here's the program and source code (trimmed down to run in both .NET 1.1 and 3.5).
Math.zip (6.38 KB)
I'm sure everyone's tired of hearing about C# 3.0 features like lambda expressions, extension methods, anonymous types and so on. Before you fall in love with the new features, there are a few oldies-but-goodies that revolve around the "?" character. I use a couple of these to stump interviewees who proclaim themselves to be C# experts. These question marks can provide a much cleaner, terser syntax for some fairly common C# usage patterns.
Conditional operator
This one can be easy to abuse, but it provides a nice terseness to code that has conditional assignments: if (hoursTraveled > 0)
speed = distanceInMiles / hoursTraveled;
else
speed = 0;
I'm trying to calculate speed, but clearly I don't want to get DivideByZeroException. Sometimes these types of assignments can add up, so I like to condense them down with the C# conditional operator: speed = hoursTraveled > 0 ? distanceInMiles / hoursTraveled : 0;
Now the conditional assignment can be written on a single line.
I don't see this feature used very often, so there is a tradeoff in familiarity. If the conditional or assignment statements grow too large, it can start to hurt readability, so just use your best judgement on this one.
Nullable types
The release of the .NET Framework 2.0 brought along a little struct type that solved a whole heap of problems. Value types (structs) can be used to represent types that don't care about referential identity. For example, if I have the number 2, and you have the number 2, they're the same number no matter how many times we create it.
Value types have another interesting aspect, they can never have a null value. The details behind this are exciting if you like things Jeffrey Richter style, full of heap and stack knowledge, but in the end you just need to know that C# structs can never be null. This line does not compile: int i = null;
But not every system in the world that deals with "int" recognizes this rule. Databases and XML schemas are two examples where "int" values can be null. To handle the impedance mismatch of real-world nulls and CLR-land value types, the Nullable<T> generic value type was introduced. By declaring a variable to be Nullable<int>, I can now do this: Nullable<int> i;
i = null;
Assert.That(i.HasValue, Is.False);
i = 3;
Assert.That(i.HasValue, Is.True);
Assert.That(i.Value, Is.EqualTo(3));
Assert.That(i, Is.EqualTo(3));
Note that I have no problems assigning int values to the Nullable<int> type, as the appropriate cast operators have been defined. Declaring a nullable type is fairly ugly using the full generic notation, so C# has a nice shortcut: int? i;
i = null;
There's our friend the question mark. It's telling us "I think this variable is an int, but I'm not sure?". This is just another compiler trick C# uses, just like extension methods. At compile time, "int?" is replaced with "Nullable<int>", so it's really just a shorthand way of expressing nullable types.
Before nullable types, I had to use a bunch of dirty tricks to represent nulls in my entities, usually with magic numbers and values like "Double.NaN" or "DateTime.MinValue". Nullable types let me bridge the gap between the nullable and non-nullable worlds.
Null coalescing operator
This is the one I love to stump the self-proclaimed experts with. I draw this on the whiteboard:
??
And ask them, "what does this operator do in C#?" Usually I get the crickets, but the special few can tell me about the null coalescing operator. The null coalescing operator is very similar to the conditional operator, but with the conditional built-in. I find myself doing this quite a lot with nulls: if (category.Description == null)
output = "<Empty>";
else
output = category.Description;
I have a value that could potentially be null, in this case the description of a category, but I need to output that value to a friendly format. Unfortunately, nulls aren't always too friendly to end-users. Let's try the conditional operator to see how that cleans things up: output = category.Description != null ? category.Description : "<Empty>";
But these conditionals can get ugly, so I can use the "??" operator to provide an even terser syntax: output = category.Description ?? "<Empty>";
All of these representations are equivalent, but I like the short and sweet syntax the "??" operator provides. Someone not familiar with this operator might not have any clue what the code does, so there is some level of risk involved.
But I generally don't like to let a lack of knowledge with a built-in language feature deter me from using it, especially if it can provide a much cleaner syntax.
And as always...
If the syntax and usage these little question marks provide don't provide better readability (solubility?), then don't put them in. These features are there to help, not to satisfy technical fetishes. As always, keep in mind that your end goal is better readability and better maintainability, not a checklist of features used.

A long awaited Prototype cheat sheet - a full reference to a bleeding edge 1.6.0.2 is finally here. I had no experience creating something like this before, so any bugs or suggestions are very much appreciated. Couple of notes about notations:
- Modules are sorted in a somewhat logical order - those commonly used are mostly in the left/center area, while deprecated/utility methods are all the way to the right
- Method can be recognized by parentheses following it (anything that doesn’t have ones is a property)
- Deprecated items are marked red and have NO parentheses/arguments specified
- Prototype extends quite few native objects’ prototypes with a set of convenient methods. In such cases there’s an explicit note about it next to a module name - i.g.
stripScripts() method from “String (String.prototype)” can be called as 'foo'.stripScripts()
- When a module is also a class, there’s a “(constructor)” note next to it - i.g. “Hash (constructor)” means that it should be called as
new Hash()
- There are few bonus items (such as those from Prototype.Browser) which are not yet included in documentation
Download and Enjoy!
Update:
I have managed to choose the most retarded format for the cheat sheet - almost squared - which was impossible to print or navigate. Sincere apologies.
There is an updated version at the same address which also fixes few other annoyances:
- Ajax.Responders is now a separate section
- Added missing Event.fire
- Added Prototype.BrowserFeatures.XPath
- Added simple “Dimensions/Offsets” diagram
- Minor rearrangements
If you are like me, you hate hand editing HTML and XML! But unfortunately, as a .NET Developer you often find yourself doing it, and if for no other reason, you have to do it for parts of the Web.Config and Application.Config files. Last night, I was googling for something, and just found this tool from ASPhere by luck. It's really easy, nice, and looks great :)
Here you are the URL : http://asphere.aspweb.cz/default.aspx
Under the category of "you learn something new every day": While watching dnrTV this morning, I saw something that I've never seen done in C# before.
I knew that it was possible to make an "alias" for a namespace in C#. For example, if you have a complex namespace like MadProps.Windows.Controls (a contrived example) that you don't want to add to your "using" list, but you don't want to have to retype every time, you can use code like this to "alias" it: using MPControls = MadProps.Windows.Controls;
That means that instead of typing "MadProps.Windows.Controls.TextBox" all through your code, you can just type "MPControls.TextBox". Nice.
What I learned this morning, however, is that you can do the same thing with types! If you have a type name that's really complex (think generic types) you can create an alias for them, too! using MyDict = System.Collections.Generic.Dictionary<int, MyLongClassName>;
Now I can just declare a variable as type "MyDict" in code instead of retyping the full dictionary definition!
Granted the uses are limited. Unless it's a particularly nasty type name I think your code readability would be best served by avoiding these sorts of aliases. However, it's great to know that the feature exists.
For a long time I have been looking for a really easy way to create a cryptographically random string in c#. I knew it had to be simple but I just had not spend the time to dig one up. Specifically I was looking for a quick and easy way to get a string that was acceptable for use as a Token for session use.
using System; using System.Security.Cryptography;
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { byte[] random = new Byte[128]; //Tell it how long you want it to be RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(random); // The array is now filled with cryptographically strong random bytes.
Console.WriteLine(System.Convert.ToBase64String(random)); Console.ReadKey(); } } }
If you are looking for a ASP.NET Google Map Control, your search is now over.
Jacob Reimers from http://www.reimers.dk/ offers a great asp.net control in 2 flavors.
The free version which lets you easily display a map with markers and/or lines and a licensed version which gives you the full power of Google Maps.
Download the free control, unzip it to your Bin folder in your web app and add a reference to it.
This is a sample asp.net page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="GoogleMap" Namespace="Reimers.Map" TagPrefix="Reimers" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Google Map test</title> </head> <body> <form id="form1" runat="server"> <div> <reimers:googlemap id="GMap" runat="server" width="349" height="354" onmarkerclick="GMap_MarkerClick" /> </div> </form> </body> </html>
and the code behind:
using System;
using System.Web.UI;
using Reimers.Map;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
GMap.GoogleKey = "Your API Code here";
GMap.MapType = MapType.Map;
GMap.TypeControl = MapTypeControl.None;
GMap.MapControl = ControlType.Small;
GoogleMarker testMarker = new GoogleMarker("newMarker", new GoogleLatLng(43.611611, -88.952931));
testMarker.MarkerText = "Test Marker";
GMap.Markers.Add(testMarker);
GMap.Latitude = testMarker.Latitude;
GMap.Longitude = testMarker.Longitude;
GMap.Zoom = 10;
}
protected void GMap_MarkerClick(GoogleMap GMap, GoogleMarker Marker, ref String MapCommand)
{
MapCommand = Marker.OpenInfoWindowHTML(GMap, Marker.MarkerText);
}
}
Sometimes we need to make some write to logs, trace, and maybe limit some features during debug. It's good to know that in debug mode we have precompiler identifier DEBUG is set. So, first of all you can try #if #endif construction. In my opinion, it's not very good to use #if directive, especialy if there is something better.
Conditional attribute. It can be applied to any method that returns void. Why void? Because the method call ignored if the condition is not fulfilled. The method can be static or not. [Conditional("DEBUG")]
static void DebugMethod()
{
}
So, this is the best way to make some job in DEBUG configuration. Also, it can be used to make different build configurations.
In 2007 I've worked with NUnitForms. It contains all major controls testers and you can easily create your own ones for e.g. a Data Grid or a 3rd party control. I had to create one for Janus GridEx and it wasn't really that hard.
A little reflection went a long way :) Lately, the whole project was at a standstill for some time but now it seems it's revitalizing nicely with new people on board. So if you haven't yet go take look. This is just one open source GUI testing platform and I'm sure there are others... I haven't checked them out though.
Now to the big question: Is it worth it? It depends...
I'm not a hardcore TDD practitioner but I like having repeatable unit tests. But having automated GUI unit tests is in my opinion a waste of time.
Why? It simply isn't worth spending time writing them. You should have enough code coverage with non GUI tests to find any bugs long before hitting the GUI. You might want to be tempted to unit test control positions or visibility or some other property... don't bother.
You'll spend your time better if you write more non GUI unit tests and check your GUI by hand (eye).
So what are they useful for? Well... I've used them for acceptance and integration testing with great success.
Integration Tests...
... test how different parts of your application work together. These kinds of GUI tests proved to be VERY useful and they are worth investing time in. They have a great ROI (return on investment) once they're written. For example we had a large workflow based application that was completely async in nature. It had a windows forms client that could be deployed on multiple computers, all those clients connected to a single server that hosted a few webservices for data modifications, retrieval and some other stuff.
The whole app was also connected to Sharepoint server, Exchange Server, SQL Server, used InfoPath and a 3rd party software to export data from and into it. With one single GUI integration test we could easily see if everything worked together as it should. We mocked the InfoPath and 3rd party software but everything else ran great.
The point of using GUI tests here is to see how and if your whole application works with all parts integrated together from GUI interaction to Exchange connectivity. Even the best non GUI integration tests simply don't do that.
Acceptance Tests...
... test if your software is up to some specs usually defined by the business process. They're in essence a black box test. You don't care what goes on inside the software you just want to see if the output is correct for a certain input. In workflow based processes this can be very useful since you know what the input and output parameters are for your workflow.
For example you start the workflow in your app via NUnitForms, pressing "move in workflow" buttons until the workflow end and then check if the output parameters have the correct values. You can check for various different GUI parameters in this test along the way but as I said above don't go overboard. I usually just check for visibility of certain panels or grids... simple things like that.
When I first started with GUI testing I thought it was a really big waste of time. And to tell you the truth if you don't draw the line somewhere it is. I even had a moment when I thought it was a good idea to test everything only with GUI tests. That was so far over line I couldn't even see it anymore. Luckily that moment passed pretty fast. Don't make the same mistake. If used wisely automated GUI tests are a big benefit.
Partial methods are a new feature available in C# 3.0 that don't seem to get enough credit. I think there was a lot of confusion early on about what partial methods were and how they were used.
Partial methods are intended to solve a major problem that is not only caused by code-generation tools and also affects those same tools. For instance, you are writing a code-generation tool but want to provide a way for the developers that are using your generated classes to hook in to specific areas of the code. As such, you don't want them editing your generated code since those customizations will be lost the next time the tool runs. On the flip side of this scenario is the developer who needs to write the code that hooks into those specific areas and doesn't want that code being lost the next time the tool runs.
Delegates are one solution to this type of problem. In the generated code, you declare a delegate method that you then call at the appropriate areas. If no one has implemented a concrete version of the delegate, the call will not do anything. However, if someone has implemented am instance of that delegate then the call will run the code in that instance. This sounds like a pretty good solution, and, until partial methods it really was the only solution. The drawback is that the code for the delegate is always compiled in to the runtime of your application and add to the runtime overhead of application (granted, that overhead is minimal but it's still there).
Partial classes helped with this problem by allowing the code-generation tools to isolate the generated code in a partial class. This allowed the developer to add their own methods to the class without fear that they would be overwritten the next time the tool ran. However, it only helped partially. In order to accomplish our scenario, you still needed to provide a delegate to allow the developer to hook into your process.
If we take this a step further and look at partial methods, you will start to see how they work and what the benefit is of using them. The following rules govern how partials methods can be declared and used:
- Must be declared inside a partial class.
- Must be declared as a void return type.
- Must be declared with the partial.
- Cannot be marked as extern.
- Can be marked static or unsafe.
- Can be generic.
- Can have ref but not out parameters.
- Cannot be referenced as a delegate until they are implemented
- Cannot have access modifiers such as public, private or internal.
- Cannot be declared as virtual.
Partial methods are implicitly marked as private. This means they cannot be called from outside the partial class.
Now that we have the rules out of the way, let's take a look at an example. This is a completely contrived example, as you typically wouldn't declare both portions of the partial class yourself.
1: // This is the class that would normally have been autogenerated. 2: public partial class CustomTypedCollection 3: { 4: partial void BeforeAddingElement(CustomElement element); 5: 6: public void AddElement(CustomElement element) 7: { 8: BeforeAddingElement(); 9: } 10: } 11: 12: public partial class CustomTypedCollection 13: { 14: partial void BeforeAddingElement(CustomElement element) 15: { 16: Console.WriteLine("Element " + element + " is being added."); 17: } 18: } 19: 20: class Program 21: { 22: static void Main(string[] args) 23: { 24: CustomTypedCollection c = new CustomTypedCollection(); 25: c.AddElemeent(new CustomElement()); 26: } 27: }
In this example, the code-generation tool declares a partial method BeforeAddingElement. It is declared as just a function prototype with no implementation. Effectively, this tells the developer that if they want to hook in to the AddElement process, they can do so by declaring an implementation of the BeforeAddingElement method. If an implementation is declared, the implementation and the call inside AddElement will be compiled in to the runtime code. However, if no implementation is declared the call will be optimized by the compiler and it will be entirely eliminated in the runtime code.
This mechanism provides a lot of the same flexibility as delegates without the runtime overhead. It also allows the developer to work with a much smaller implementation of their portion of the partial class that contains only the few partial methods that have been implemented.
Which .NET Framework Data Provider to Use?
To achieve the best performance for your application, use the .NET Framework data provider that is most appropriate for your data source. There are a number of data provider options for use in your applications. The following table provides information about the available data providers and which data sources a data provider is most appropriate for.
|
Provider |
Details |
|
SQL Server .NET Data Provider |
Found in the System.Data.SqlClient namespace.
Recommended for middle-tier applications using Microsoft SQL Server version 7.0 or later.
Recommended for single-tier applications using the Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later. |
|
OLE DB .NET Data Provider |
Found in the System.Data.OleDb namespace.
Recommended for middle-tier applications using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider that supports the OLE DB interfaces listed in OLE DB Interfaces Used by the OLE DB .NET Data Provider in the .NET Framework SDK.
For Microsoft SQL Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended.
Recommended for single-tier applications using a Microsoft® Access database. Use of an Access database for a middle-tier application is not recommended. |
|
ODBC .NET Data Provider |
Found in the Microsoft.Data.Odbc namespace.
The ODBC .NET Data Provider is available for download.
Provides access to data sources that are connected to using an ODBC driver. |
|
Oracle .NET Data Provider |
Found in the System.Data.OracleClient namespace.
The .NET Framework Data Provider for Oracle, unlike the Microsoft OLE DB provider for Oracle, also supports new Oracle 9i datatypes, as well as ref cursors (useful for running Oracle stored procedures that return result sets). This provider, System.Data.OracleClient, is similar to the .NET Framework Data Provider for SQL Server, System.Data.SqlClient.
The Oracle .NET Data Provider is available for download |
The fastest database read mechanism will be ADO.NET Data Readers, as opposed to Data Sets.
Today, Google released their Chart API. Basically, the Google Chart API allows you to dynamically generate charts for use in your web applications. All you do is pass your data in the querystring and an image is returned. This isn't really a service to get too excited about, but it is pretty simple to use and it's Free.
Here is a bit about this:
The Google Chart API lets you dynamically generate charts. To see the Chart API in action, open up a browser window and copy the following URL into it:
http://chart.apis.google.com/chart?cht=p3&chd=s:hW&chs=250x100&chl=Hello|World
Press the Enter or Return key and - presto! - you should see the following image:

I decided to code up a small ASP.NET Server Control that uses the Google Chart API to put simple line graph charts on a page.
How to use this control:
Put the Chart control on the page:
<GoogleAPI:Chart runat="server" id="Chart1" Width="200" Height="150" LineColor="ff0000" BackgroundColor="efefef" ToolTip="Hello World"> </GoogleAPI:Chart>
In the page load event define the values to be charted:
Chart1.MaxValue = 60;
Chart1.Values.Clear();
Chart1.Values.Add("Jan", 10); Chart1.Values.Add("Feb", 20); Chart1.Values.Add("Mar", 30); Chart1.Values.Add("Apr", 50); Chart1.Values.Add("May", 5); Chart1.YAxisLabels.Add("0 Kb"); Chart1.YAxisLabels.Add("25+ Kb"); Chart1.YAxisLabels.Add("50+ Kb");
And, that's all you have to do to put a Chart on your page using the control.
The result is this:

Download the example / source code here: GoogleChartAPI.rar (3.33 KB)
Last week (december 5th) Microsoft announced the Volta technology preview, a developer toolset for building multi-tier web applications using existing and familiar tools, techniques and patterns.
Volta’s declarative tier-splitting enables developers to postpone architectural decisions about distribution until the last possible responsible moment. Also, thanks to a shared programming model across multiple-tiers, Volta enables new end-to-end profiling and testing for higher levels of application performance, robustness, and reliability. In effect, Volta extends the .NET platform to further enable the development of software+services applications, using existing and familiar tools and techniques.
You architect and build your application as a .NET client application, assigning the portions of the application that run on the server tier and client tier late in the development process.
After tier assignments, Volta's deep integration with Visual Studio debugger and testing infrastructure dramatically improves the deployment experience for developers.
- Volta automatically creates communication, serialization, and remoting code. Developers simply write custom attributes on classes or methods to tell Volta the tier on which to run them.
- Developers may base tier assignments on any criteria, such as load management, performance, or location of critical assets and capabilities. Because Volta automates the hidden plumbing code, it is easy for developers to experiment with varying assignments of classes and methods to tiers.
- Developers can use all the .NET languages, libraries, and tools they already know, including debuggers, profilers, test generators, refactoring, and code analysis tools.
Volta offers deep integration with Visual Studio 2008, including debuggers, profilers, and testing frameworks. Developers can step through code seamlessly from one tier to another, can set breakpoints on any tier, and trace flows of control across distributed systems.
What do you need to use Volta?
The Volta developer toolset requires Visual Studio 2008 and the .NET Framework 3.5 for writing and building applications. Volta applications run virtually anywhere, even where an MSIL runtime is not available. A Volta client-side application can run in most standards-compliant browsers, but can also be targetted also take advantage of MSIL runtimes like the .NET CLR.
All this sounds great, except the requirements that are trying to enforce the developers to use Visual Studio 2008 and the new .NET Framework 3.5.
I wonder why the long wait for this release? And why it does not compatible with .NET Framework 2.0?
BTW, It is just me or the Volta logo reminds firefox logo a bit:
<- VS -> 
This is one of those "Yeah I've always seen people use it differently but I don't know why!" questions.
Re-throwing exceptions can be misused, although it may not cause any harm to your application - there are multiple ways of re-throwing an exception, most likely for the purpose of bubbling it up to a higher level.
Lets look at how many ways we can use throw:
- throw
- throw ex
- throw new Exception();
You should not use #3 except if you are throwing a specific exception other that the one that was fired such as a custom exception. To re-throw an exception in .NET your best option is #1 instead of #2 and that is simply because of how they stack up in the stack trace. Lets take a look at the stack trace for both instances using the following snippet.
protected void Page_Load(object sender, EventArgs e)
{
try
{
DoMath();
}
catch(Exception ex)
{
throw ex;
}
}
/// <summary>
/// A method that simply calls another method.
/// </summary>
/// <remarks>
/// Just a helper to show stack trace
/// </remarks>
private void DoMath()
{
MethodWithError();
}
/// <summary>
/// This method will throw an error
/// </summary>
private void MethodWithError()
{
throw new Exception("Generic exception");
}
The stack trace looks like this: [Exception: Generic exception]
throwerror.Page_Load(Object sender, EventArgs e) in d:\My Websites\demoweb\throwerror.aspx.cs:22
System.Web.Util.CalliHelper.EventArgFunctionCaller (IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback (Object sender, EventArgs e) +34
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
However, if I replace "throw ex;" with just "throw;", here is the new stack trace.
[Exception: Generic exception] throwerror.MethodWithError() in d:\My Websites\demoweb\throwerror.aspx.cs:42 throwerror.DoMath() in d:\My Websites\demoweb\throwerror.aspx.cs:34 throwerror.Page_Load(Object sender, EventArgs e) in d:\My Websites\demoweb\throwerror.aspx.cs:22 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
Its all about the details. Obviously, using just "throw;" gives us much more details - so use "throw" to re-throw an error.
Now that the .NET Framework 3.5 has been released, this version includes logic to detect the presence of the .NET Framework 3.5 and also .NET Framework 3.0 service packs, which was missing from previous versions of this sample code.
You can download updated versions of the sample code at the following locations:
For reference, the registry locations used in this sample code to detect the .NET Framework 3.0 service pack level and the .NET Framework 3.5 are listed below.
To detect the .NET Framework 3.0 service pack level:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0] SP = <value>
Note - this SP value will not exist at all if you only have the original release of the .NET Framework 3.0. This value was added starting in the .NET Framework 3.0 SP1 and will be updated for future service packs.
To detect the .NET Framework 3.5 final release:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5] Install = 1 Version = 3.5.21022.08
To detect the .NET Framework 3.5 service pack level:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5] SP = <value>
Note - this SP value does exist in the final release of the .NET Framework 3.5, and will be set to 0. Future service packs will increment this value as appropriate.
|