.NET, Javascript, jQuery, and you
October 8, 2010 § 5 Comments
I’ve been doing a lot of Sharepoint development recently. Now Sharepoint presents several challenges, not the least of which is that you don’t have access to the familiar code behind functionality in most cases. Custom development in Sharepoint consists of master pages and page layouts that contain web parts. Web parts have code behind files, but the pages don’t, and it’s unwieldy to develop custom Sharepoint applications with the familiar ASP.NET forms-based development model.
As such, I’ve relied pretty heavily on client side code to accomplish much of the functionality that I’ve needed. My friend Ted Hughes introduced me to some of these concepts when we were working together at Curtis 1000. He was working primarily with the ASP.NET MVC framework, which I had played around with, but hadn’t used extensively up to that point.
One of the things that surprised me so much was just how pervasive the jQuery framework was used within that MVC development paradigm. Coming from a background of traditional ASP.NET forms development, I thought I was being progressive by using the ASP.NET Ajax framework, but Microsoft quite quickly dropped the framework in favor of jQuery. This article by Dave Ward goes into some detail about why.
So, obviously I was aware of jQuery, and had used it in some limited capacity, but if you’re not using it regularly, you should begin doing so. Depending on your background, you may view javascript as a subpar tool for developing web applications. At one point, I would probably have agreed with you, but javascript is a real language – really! The productivity increase from using jQuery properly and intelligently is excellent.
Here’s another article by Dave Ward to give you just a little jQuery introduction. If you’re a book learner, I can recommend jQuery in Action, which I thought was thorough as well as quick and easy to read. Also, a simple web search for “jQuery” + “whatever you want to do” almost always yields a quick result. Or if you can’t figure it out, ask me.
Manos de Mano
September 26, 2010 § Leave a comment
I ran across this the other day, and thought it was very cool. I’ve been deep in the bowels of Sharepoint, Active Directory, and WCF for the last couple of weeks, so when I happened across a simple, straightforward, to-the-point framework for building web applications in .NET, I thought that sounded just great.
What is Manos de Mano?
Manos is an easy to use, easy to test, high performance web application framework that stays out of your way and makes your life ridiculously simple.
Check out some of the features:
- A scalable non-blocking HTTP server. Manos includes its own high performance web server based on friendfeed’s tornado web server (http://tornadoweb.org). Having an integrated server simplifies deployment and allows the underlying server to be customized to meet the needs of the higher level framework.
- An HTTP “pipes” system, that allows you to hook into and process all http requests and responses before/after they get to the main routing framework.
- Simple routing. There are a number of easy ways you can route requests to methods in Manos. Using properties to route to other modules, convention based method signatures to implicitly add methods, attributes on methods to explicitly route to them or by using the HTTP methods to add a delegate for a route. All these routes can be defined with string matching, regular expressions or a simple named group matching syntax that looks like this: “/Articles/{title}/{page}/”.
- Named parameter conversion on methods. If you create a method Foo (IManosContext ctx, string bar, int idx). Manos will find those parameters in the request data and automatically type convert them for you.
- HTML5 Boilerplate. When you create a new Manos project you get a layout based on the HTML5 boilerplate project (http://html5boilerplate.com/). This gives you a rock solid place to start for your front end development.
- A wicked fast, html-centric template engine. The Manos template engine is designed to be designer and developer friendly. You can easily edit the template files without the help of an IDE and if a designer sends you html files, you can easily convert them into templates. To maximize performance the templates are compiled, not interpretted but they can still be generated at runtime.
- A simple command line tool for creating, building and hosting your apps. No IDE needed. Creating a new project is as simple as typing manos -init.
- Reusability: The success of todays popular web application frameworks is not just in their API or performance, its in the wealth of community developed libraries that can be easily plugged into your application. To facilate this, Manos is designed with shareable modules in mind. The framework is designed to encourage modular systems design and code reuse.
I’m going to have to find some time to play with the framework – it looks excellent. Many thanks to Jackson Harper for putting the time into this.
F# Tutorial
November 3, 2009 § Leave a comment
Here’s a great tutorial on F# written from the perspective of a developer already comfortable with C#. I’m just starting to play around with some functional development, and as this is a great jumping off point for someone that wants a quick introduction to F#, I thought I’d share.
.NET Web Services, Objects, WSDL.exe, and Reference.cs
October 15, 2009 § Leave a comment
This problem is annoying.
If you make a .NET web service and you add the web reference to another project, Visual Studio runs WSDL.exe in the background to create a Reference.cs file – which is awesome (sort of). The Reference.cs file gives you the ability to call your web service just as if it were any other .NET class you have a reference to, which again, is awesome (sort of).
The problem arises when you have a class defined that is accepted as a parameter to, or returned from, a method in your web service. WSDL.exe generates a class definition for this class in the Reference.cs file, which is great if you don’t want to reference the actual class.
The standard solution to this problem is much as Bruce Johnson describes, which is to hand-edit the Reference.cs file to remove the generated class, and add a “using” statement or fully qualify the class name to point to the correct (the original) namespace.
Unfortunately, this means that every time you need to update the web reference, and the Reference.cs file is regenerated, you need to hand edit the Reference.cs file, which is a huge waste of time and kind of a pain in the butt.
There is apparently a way to use SchemaImporterExtensions to affect the way that WSDL.exe generates the Reference.cs file, but to be honest, it looked really confusing and also difficult to maintain. I didn’t really attempt to do it, though, so maybe it’s easier than it looks.
So, after having to deal with this on a project I’m working with currently, I decided that it would make sense to automate this annoying problem. I built an executable that accepts, on the command line, the path to a dll, and the path to a Reference.cs file. The executable looks for any public classes or enums that are defined in both the dll and the Reference.cs file, removes the class declaration from the Reference.cs file, and fully qualifies the class references.
I then changed the project properties (in the project that contains the web references) to add several pre-build commands. The commands call the executable with whatever combination of dll’s and Reference.cs files. This way, you can update the web reference as often as necessary, and before the project builds, the executable will run and fix all the issues in the Reference.cs file.
This code is kind of hacked together, but I really had a hard time justifying spending much time on polishing it, so I’m just going to post it as is. It’ll only work on C#, and as far as I know, there aren’t any bugs, although you might have some. If you use it and find anything wrong with it, leave a comment, and I’ll update the code.
Anyway, here’s the code – I’m kind of surprised I couldn’t find something to do this already, so hopefully it’ll help you.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
namespace WebServiceReferenceResolver
{
class Program
{
/// <summary>
/// Mains the specified args.
/// </summary>
/// <param name=”args”>The args.</param>
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine(“Correct Usage: WebServiceReferenceResolver [ASSEMBLYNAME] [REFERENCE.CS]”);
return;
}
try
{
string assemblyName = new FileInfo(args[0]).FullName;
string referenceCsName = new FileInfo(args[1]).FullName;
List<Type> classList = GetPublicClasses(assemblyName);
StreamReader sr = new StreamReader(referenceCsName);
string referenceCsSource = sr.ReadToEnd();
sr.Close();
// remove class definitions
for (int i = classList.Count – 1; i >= 0; i–)
{
bool typeFound = false;
referenceCsSource = RemoveClassDeclaration(referenceCsSource, classList[i], ref typeFound);
if (!typeFound)
{
classList.RemoveAt(i);
}
}
// properly resolve class references
foreach (Type t in classList)
{
referenceCsSource = ResolveClassReference(referenceCsSource, t);
}
StreamWriter sw = new StreamWriter(referenceCsName, false);
sw.Write(referenceCsSource);
sw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// Gets the public classes.
/// </summary>
/// <param name=”assemblyName”>Name of the assembly.</param>
/// <returns></returns>
private static List<Type> GetPublicClasses(string assemblyName)
{
Assembly assembly = Assembly.LoadFile(assemblyName);
Type[] types = new Type[0];
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException rtle)
{
types = rtle.Types;
}
List<Type> returnList= new List<Type>();
foreach(Type t in types)
{
if (t != null && t.IsPublic)
{
returnList.Add(t);
}
}
return returnList;
}
/// <summary>
/// Removes the class declaration.
/// </summary>
/// <param name=”referenceCsSource”>The reference cs source.</param>
/// <param name=”t”>The t.</param>
/// <param name=”typeFound”>if set to <c>true</c> [type found].</param>
/// <returns></returns>
private static string RemoveClassDeclaration(string referenceCsSource, Type t, ref bool typeFound)
{
int startIndex = -1;
typeFound = false;
Regex r = new Regex(“(class|enum) “ + t.Name + ” ({|:)”);
Match m = r.Match(referenceCsSource);
if (m != null && m.Index != 0)
{
startIndex = m.Index;
}
if (startIndex != -1)
{
int firstBracketIndex = referenceCsSource.IndexOf(“{“, startIndex);
int lastBracketIndex = referenceCsSource.LastIndexOf(“}”, startIndex) + 1;
int lastSemicolonIndex = referenceCsSource.LastIndexOf(“;”, startIndex) + 1;
if (lastBracketIndex > lastSemicolonIndex)
{
startIndex = lastBracketIndex;
}
else
{
startIndex = lastSemicolonIndex;
}
int characterIndex = firstBracketIndex + 1;
int bracketIndexCount = 1;
while (characterIndex < referenceCsSource.Length && bracketIndexCount > 0)
{
if (referenceCsSource[characterIndex] == ‘{‘)
{
bracketIndexCount++;
}
else if (referenceCsSource[characterIndex] == ‘}’)
{
bracketIndexCount–;
}
characterIndex++;
}
if (characterIndex < referenceCsSource.Length)
{
// remove it
typeFound = true;
referenceCsSource = referenceCsSource.Remove(startIndex, characterIndex – startIndex);
}
}
return referenceCsSource;
}
/// <summary>
/// Resolves the class reference.
/// </summary>
/// <param name=”referenceCsSource”>The reference cs source.</param>
/// <param name=”t”>The t.</param>
/// <returns></returns>
private static string ResolveClassReference(string referenceCsSource, Type t)
{
// yeah, this is tacky, but whatever
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(” {0} “, t.Name));
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(” {0}[“, t.Name));
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(” {0}(“, t.Name));
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(“({0} “, t.Name));
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(“({0}[“, t.Name));
referenceCsSource = ResolveClassReference(referenceCsSource, t, string.Format(“({0})”, t.Name));
return referenceCsSource;
}
/// <summary>
/// Resolves the class reference.
/// </summary>
/// <param name=”referenceCsSource”>The reference cs source.</param>
/// <param name=”t”>The t.</param>
/// <param name=”matchString”>The match string.</param>
/// <returns></returns>
private static string ResolveClassReference(string referenceCsSource, Type t, string matchString)
{
int index = 0;
while (index != -1)
{
index = referenceCsSource.IndexOf(matchString, index);
if (index != -1)
{
referenceCsSource = referenceCsSource.Insert(index + 1, string.Format(“{0}.”, t.Namespace));
index += t.Namespace.Length + matchString.Length;
}
}
return referenceCsSource;
}
}
}
.NET Exceptions – common exceptions and usage guidelines
August 9, 2009 § Leave a comment
My earlier post containing a list of all .NET exceptions gets a lot of traffic. It’s a great reference, but it’s also a really large list and doesn’t give much guidance regarding how to use them. This post will try to give some guidance regarding the more commonly used exceptions and in what circumstances they should be used.
Generally speaking, if you need to throw an exception purposefully, you should probably define a custom exception for that (read the bit about ApplicationException below). There are only a few of the built-in .NET exceptions that you’ll ever want to throw. Here’s my top 5 or so.
System
The exception that is thrown when a non-fatal application error occurs.
The ApplicationException was originally intended as a base class for application specific exceptions. In other words, you’d derive from ApplicationException rather than Exception for any application specific exception types you needed to define. In practice, most developers don’t seem to do this. Honestly, I don’t know if it’s because they aren’t aware of it, or because it doesn’t really convey any particular benefits.The obvious benefit of using this class is that if you have multiple application specific exceptions you want to define, and you do derive them all from ApplicationException, you can just catch the base class upstream and handle it. If you’re using a construct like the Microsoft Enterprise Library Exception Handling Application Block, this can come in very handy.
The exception that is thrown when one of the arguments provided to a method is not valid.
This is a really handy exception that I use all the time. However, you should preferentially use one of the below exceptions. In other words, don’t do something likethrow new ArgumentException("parameter1 is null.");when you could do something like
throw new ArgumentNullException("parameter1");The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
The exception that is thrown when a requested method or operation is not implemented.
This is a great exception that seems to hardly ever get used. Even some of the stuff that Visual Studio will generate automatically will do something likethrow new Exception("Method is not yet implemented.");instead of
throw new NotImplementedException();
This obviously isn’t all of them, but it’s a start. The few exceptions I listed above, in combination with custom application-specific exceptions, account for about 90% of the exceptions I ever have to throw.
.NET Exceptions – source code
July 21, 2009 § 6 Comments
I promised I’d post the source code for generating the list of .NET exceptions that I posted earlier. Here it is finally. This just outputs an XML structure to the console. You can redirect the output to a file then use an XSLT transform on it (or do whatever else you want with it).
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Text.RegularExpressions;
using System.Design;
using System.Xml;
using System.IO;
namespace ExceptionList
{
class Program
{
static void Main(string[] args)
{
ReflectionSearch(".*exception$");
Console.ReadKey();
}
static public void ReflectionSearch(string strPattern)
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
AssemblyName[] assemblyNames = thisAssembly.GetReferencedAssemblies();
// Force the load of various assemblies
LoadAssemblies();
Regex regex = new Regex(@"^(?<path>.*)\.(?<exc>.*?)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
foreach (var assemblyName in assemblyNames)
{
// iterate over all of the modules referenced by this assembly
Assembly assembly = Assembly.Load(assemblyName);
foreach (Module module in assembly.GetModules())
{
SortedList<string, string> moduleList = new SortedList<string, string>();
foreach (Type t in module.GetTypes())
{
// if there is a class of type Exception in this module
// add it to the sorted list
if (t.IsSubclassOf(typeof(Exception)))
{
// the funky key is so that the output will be sorted
// the way a human would want it to be
moduleList.Add(t.Namespace + ".1" + t.Name, t.FullName);
}
}
// as long as we found some exceptions in this module
if (moduleList.Count > 0)
{
string lastPath = "";
Console.WriteLine(string.Format("<module name=\"{0}\">", module.Name));
// get the XML file containing the XML comments for the .NET objects
// As far as I can tell, the 2.0 framework comes with these files
// but the 3.0 and 3.5 framework does not. I'm sure the XML files
// exist, but I don't have them
string xmlFileName = string.Format(
@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\en\{0}.xml",
module.Name.Substring(0, module.Name.Length - 4));
XmlDocument xd = null;
if (File.Exists(xmlFileName))
{
xd = new XmlDocument();
xd.Load(xmlFileName);
}
// iterate over each exception in this module
foreach (string excName in moduleList.Values)
{
Match match = regex.Match(excName);
if (match.Success)
{
string path = match.Groups["path"].Value;
// keep track of when we're switching to a new module
if (path != lastPath)
{
if (!string.IsNullOrEmpty(lastPath))
{
Console.WriteLine("</namespace>");
}
lastPath = path;
Console.WriteLine(string.Format("<namespace name=\"{0}\">", path));
}
// get the full class name including the namespace
string fullClassName = string.Format("{0}.{1}", path, match.Groups["exc"].Value);
Console.WriteLine(string.Format("<exception name=\"{0}\">", fullClassName));
// output the MSDN reference link
Console.WriteLine(string.Format(
"<a href=\"http://msdn.microsoft.com/en-us/library/{0}.aspx\">{1}</a>",
fullClassName.ToLower(),
match.Groups["exc"].Value));
// if there is XML documentation for this exception
// and there is a summary node, write it out
if (xd != null)
{
XmlNode xnd = xd.SelectSingleNode(string.Format("//member[@name='T:{0}']/summary", fullClassName));
if (xnd != null)
{
Console.WriteLine(string.Format("<summary>{0}</summary>", xnd.InnerText.Trim()));
}
}
Console.WriteLine("</exception>");
}
else
{
Console.WriteLine("Whoops...\t" + excName);
}
}
Console.WriteLine("</module>");
} // end if
} // end foreach
} // end foreach
}
private static void LoadAssemblies()
{
new System.AddIn.Hosting.InvalidPipelineStoreException();
new System.Configuration.Provider.ProviderException();
new System.Configuration.Install.InstallException();
new System.Data.DataException();
new System.Drawing.Color();
new System.Drawing.Design.UITypeEditor();
new System.DirectoryServices.DirectoryEntry();
new System.Management.ConnectionOptions();
new System.Messaging.AccessControlList();
new System.Runtime.Remoting.RemotingException();
new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
new System.Security.HostProtectionException();
new System.ServiceProcess.TimeoutException();
new System.Web.HttpCompileException();
new System.Windows.Forms.Form();
new System.Windows.Forms.Design.AnchorEditor();
new System.Xml.XmlDocument();
}
}
}
You’ll need to add the following references:
System.AddIn
System.Xonfiguration
System.Configuration.Install
System.Core
System.Data
System.Design
System.DirectoryService
System.Drawing
System.Management
System.Messaging
System.RunTimeRemoting
System.Security
System.ServiceProcess
System.Web
System.Windows.Forms
System.Xml
System.Xml.Linq
.NET Exceptions (all of them)
July 8, 2009 § 19 Comments
I wanted a list of .NET exceptions. I went looking and couldn’t really find what I was looking for. This post on codinghorror.com helped me get started (especially the work Paul Cotter did), but didn’t really answer the whole question for me. I hacked up the source code that was posted on the site, referenced the XML file generated from the XML comments in the .NET assemblies, linked the exceptions to the MSDN documentation, and generated the following list.
Some of these links are broken (they don’t seem to be documented exceptions). I will probably update this post at some point to remove the links for the exceptions that aren’t documented. I will also post the source code I used to generate the list once all the embarrassing hacks are cleaned up. Check back in a day or two. You can find the source code here.
This list is based on the 3.5 framework.
mscorlib.dll
System
The exception that is thrown when there is an attempt to read or write protected memory.
The exception that is thrown when an attempt is made to access an unloaded application domain.
The exception that is thrown when a non-fatal application error occurs.
The exception that is thrown when one of the arguments provided to a method is not valid.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
The exception that is thrown for errors in an arithmetic, casting, or conversion operation.
The exception that is thrown when an attempt is made to store an element of the wrong type within an array.
ASSERT
BadImageFormatExceptionThe exception that is thrown when the file image of a DLL or an executable program is invalid.
CannotUnloadAppDomainException
The exception that is thrown when an attempt to unload an application domain fails.
The exception that is thrown when an attempt to marshal an object across a context boundary fails.
The exception that is thrown when a unit of data is read from or written to an address that is not a multiple of the data size. This class cannot be inherited.
The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.
The exception that is thrown when a DLL specified in a DLL import cannot be found.
The exception that is thrown when an object appears more than once in an array of synchronization objects.
The exception that is thrown when an attempt to load a class fails due to the absence of an entry method.
The exception that is thrown when there is an internal error in the execution engine of the common language runtime. This class cannot be inherited.
The exception that is thrown when there is an invalid attempt to access a private or protected field inside a class.
The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.
The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited.
The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited.
The exception that is thrown for invalid casting or explicit conversion.
The exception that is thrown when a method call is invalid for the object’s current state.
The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program.
The exception that is thrown when an attempt to access a class member fails.
The exception that is thrown when there is an invalid attempt to access a private or protected method inside a class.
The exception that is thrown when there is an attempt to dynamically access a field that does not exist.
The exception that is thrown when there is an attempt to dynamically access a class member that does not exist.
The exception that is thrown when there is an attempt to dynamically access a method that does not exist.
MulticastNotSupportedException
The exception that is thrown when there is an attempt to combine two delegates based on the type instead of the type. This class cannot be inherited.
The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN).
The exception that is thrown when a requested method or operation is not implemented.
The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
The exception that is thrown when there is an attempt to dereference a null object reference.
The exception that is thrown when an operation is performed on a disposed object.
The exception that is thrown in a thread upon cancellation of an operation that the thread was executing.
The exception that is thrown when there is not enough memory to continue the execution of a program.
The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.
The exception that is thrown when a feature does not run on a particular platform.
The exception that is thrown when an array with the wrong number of dimensions is passed to a method.
The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.
Defines the base class for predefined exceptions in the namespace.
The exception that is thrown when the time allotted for a process or operation has expired.
The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
The exception that is thrown when type-loading failures occur.
The exception that is thrown when there is an attempt to access an unloaded class.
The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
System.Collections.Generic
The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.
System.IO
The exception that is thrown when part of a file or directory cannot be found.
The exception that is thrown when trying to access a drive or share that is not available.
The exception that is thrown when reading is attempted past the end of a stream.
The exception that is thrown when a managed assembly is found but cannot be loaded.
The exception that is thrown when an attempt to access a file that does not exist on disk fails.
The exception that is thrown when an I/O error occurs.
The exception that is thrown when a pathname or filename is longer than the system-defined maximum length.
System.IO.IsolatedStorage
The exception that is thrown when an operation in isolated storage fails.
System.Reflection
The exception that is thrown when binding to a member results in more than one member matching the binding criteria. This class cannot be inherited.
CustomAttributeFormatException
The exception that is thrown when the binary format of a custom attribute is invalid.
InvalidFilterCriteriaException
The exception that is thrown in when the filter criteria is not valid for the type of filter you are using.
MetadataException
ReflectionTypeLoadExceptionThe exception that is thrown by the method if any of the classes in a module cannot be loaded. This class cannot be inherited.
Represents the exception that is thrown when an attempt is made to invoke an invalid target.
The exception that is thrown by methods invoked through reflection. This class cannot be inherited.
The exception that is thrown when the number of parameters for an invocation does not match the number expected. This class cannot be inherited.
System.Resources
MissingManifestResourceException
The exception thrown if the main assembly does not contain the resources for the neutral culture, and they are required because of a missing appropriate satellite assembly.
MissingSatelliteAssemblyException
The exception that is thrown when the satellite assembly for the resources of the neutral culture is missing.
System.Runtime.CompilerServices
Wraps an exception that does not derive from the class. This class cannot be inherited.
System.Runtime.InteropServices
The exception that is thrown when an unrecognized HRESULT is returned from a COM method call.
The base exception type for all COM interop exceptions and structured exception handling (SEH) exceptions.
The exception thrown when an invalid COM object is used.
InvalidOleVariantTypeException
The exception thrown by the marshaler when it encounters an argument of a variant type that can not be marshaled to managed code.
The exception that is thrown by the marshaler when it encounters a it does not support.
SafeArrayRankMismatchException
The exception thrown when the rank of an incoming SAFEARRAY does not match the rank specified in the managed signature.
SafeArrayTypeMismatchException
The exception thrown when the type of the incoming SAFEARRAY does not match the type specified in the managed signature.
Represents Structured Exception Handler (SEH) errors.
System.Runtime.Remoting
The exception that is thrown when something has gone wrong during remoting.
The exception that is thrown when the server or the client cannot be reached for a previously specified period of time.
The exception that is thrown to communicate errors to the client when the client connects to non-.NET Framework applications that cannot throw exceptions.
System.Runtime.Serialization
The exception thrown when an error occurs during serialization or deserialization.
System.Security
The exception that is thrown when a denied host resource is detected.
The exception that is thrown when a security error is detected.
The exception that is thrown when the security policy requires code to be type safe and the verification process is unable to verify that the code is type safe.
The exception that is thrown when there is a syntax error in XML parsing. This class cannot be inherited.
System.Security.AccessControl
The exception that is thrown when a method in the namespace attempts to enable a privilege that it does not have.
System.Security.Cryptography
The exception that is thrown when an error occurs during a cryptographic operation.
CryptographicUnexpectedOperationException
The exception that is thrown when an unexpected operation occurs during a cryptographic operation.
System.Security.Policy
The exception that is thrown when policy forbids code to run.
System.Security.Principal
Represents an exception for a principal whose identity could not be mapped to a known identity.
System.Text
The exception that is thrown when a decoder fallback operation fails. This class cannot be inherited.
The exception that is thrown when an encoder fallback operation fails. This class cannot be inherited.
System.Threading
The exception that is thrown when one thread acquires a object that another thread has abandoned by exiting without releasing it.
The exception that is thrown when a method requires the caller to own the lock on a given Monitor, and the method is invoked by a caller that does not own that lock.
The exception that is thrown when a call is made to the method. This class cannot be inherited.
The exception that is thrown when a is interrupted while it is in a waiting state.
The exception that is thrown when a failure occurs in a managed thread after the underlying operating system thread has been started, but before the thread is ready to execute user code.
The exception that is thrown when a is in an invalid for the method call.
WaitHandleCannotBeOpenedException
The exception that is thrown when an attempt is made to open a system mutex or semaphore that does not exist.
System.AddIn.dll
Microsoft.Contracts
Contract+AssertionException
Contract+AssumptionException
Contract+InvariantException
Contract+PostconditionException
Contract+PreconditionExceptionSystem.AddIn.Hosting
AddInBaseInAddInFolderException
AddInSegmentDirectoryNotFoundException
InvalidPipelineStoreExceptionSystem.AddIn.MiniReflection
System.Configuration.dll
System.Configuration
The current value is not one of the values.
System.Configuration.Provider
The exception that is thrown when a configuration provider error has occurred. This exception class is also used by providers to throw exceptions when internal errors occur within the provider that do not map to other pre-existing exception classes.
System.Configuration.Install.dll
System.Configuration.Install
The exception that is thrown when an error occurs during the commit, rollback, or uninstall phase of an installation.
System.Data.dll
<CrtImplementationDetails>
Microsoft.SqlServer.Server
Thrown when SQL Server or the ADO.NET provider detects an invalid user-defined type (UDT).
System.Data
Represents the exception that is thrown when attempting an action that violates a constraint.
Represents the exception that is thrown when errors are generated using ADO.NET components.
The exception that is thrown by the during an insert, update, or delete operation if the number of rows affected equals zero.
DeletedRowInaccessibleException
Represents the exception that is thrown when an action is tried on a that has been deleted.
Represents the exception that is thrown when a duplicate database object name is encountered during an add operation in a -related object.
Represents the exception that is thrown when the property of a cannot be evaluated.
Represents the exception that is thrown when you call the method within the event.
Represents the exception that is thrown when incorrectly trying to create or access a relation.
Represents the exception that is thrown when you try to add a that contains an invalid to a .
Represents the exception that is thrown when you try to access a row in a table that has no primary key.
Represents the exception that is thrown when you try to insert a null value into a column where is set to false.
This exception is thrown when an ongoing operation is aborted by the user.
Represents the exception that is thrown when you try to change the value of a read-only column.
Represents the exception that is thrown when you try to perform an operation on a that is not in a .
The exception that is thrown by a strongly typed when the user accesses a DBNull value.
Represents the exception that is thrown when the property of a contains a syntax error.
TypedDataSetGeneratorException
The exception that is thrown when a name conflict occurs while generating a strongly typed .
Represents the exception that is thrown when you try to return a version of a that has been deleted.
System.Data.Common
The base class for all exceptions thrown on behalf of the data source.
System.Data.Odbc
The exception that is generated when a warning or error is returned by an ODBC data source. This class cannot be inherited.
System.Data.OleDb
The exception that is thrown when the underlying provider returns a warning or error for an OLE DB data source. This class cannot be inherited.
System.Data.SqlClient
The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited.
System.Data.SqlTypes
The class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.
The class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.
The exception that is thrown when the Value property of a structure is set to null.
The exception that is thrown when you set a value into a structure would truncate that value.
The base exception class for the .
System.Drawing.dll
System.Drawing.Printing
Represents the exception that is thrown when you try to access a printer using printer settings that are not valid.
System.DirectoryServices.dll
System.DirectoryServices
Contains extended error information about an error that occurred when the method is called.
System.DirectoryServices.ActiveDirectory
ActiveDirectoryObjectExistsException
The class exception is thrown when an Active Directory Domain Services object is created and that object already exists in the underlying directory store.
ActiveDirectoryObjectNotFoundException
The class exception is thrown when a requested object is not found in the underlying directory store.
ActiveDirectoryOperationException
The class exception is thrown when an underlying directory operation fails.
ActiveDirectoryServerDownException
The class exception is thrown when a server is unavailable to respond to a service request.
The class exception is thrown when a trust collision occurs during a trust relationship management request.
SyncFromAllServersOperationException
The exception is thrown when the request to synchronize from all servers fails.
System.Management.dll
System.Management
Represents management exceptions.
System.Messaging.dll
System.Messaging
The exception that is thrown if a Microsoft Message Queuing internal error occurs.
System.ServiceProcess.dll
System.ServiceProcess
The exception that is thrown when a specified timeout has expired.
System.Web.dll
System.Web
The exception that is thrown when a compiler error occurs.
Describes an exception that occurred during the processing of HTTP requests.
The exception that is thrown when a parse error occurs.
HttpRequestValidationException
The exception that is thrown when a potentially malicious input string is received from the client as part of the request data. This class cannot be inherited.
The exception that is thrown when a generic exception occurs.
System.Web.Caching
DatabaseNotEnabledForNotificationException
The exception that is thrown when a SQL Server database is not enabled to support dependencies associated with the class. This class cannot be inherited.
TableNotEnabledForNotificationException
The exception that is thrown when a class is used against a database table that is not enabled for change notifications.
System.Web.Hosting
System.Web.Management
Defines a class for SQL execution exceptions in the namespace.
System.Web.Security
The exception that is thrown when a user is not successfully created by a membership provider.
The exception that is thrown when a password cannot be retrieved from the password store.
System.Web.UI
Represents the exception that is thrown when the view state cannot be loaded or validated. This class cannot be inherited.
System.Windows.Forms.dll
System.Windows.Forms
System.Design.dll
System.ComponentModel.Design
Represents the collection of exceptions.
System.ComponentModel.Design.Serialization
The exception that is thrown when line number information is available for a serialization error.
System.Data.Design
DataSourceGeneratorException
DataSourceSerializationException
InternalException
NameValidationException
TypedDataSetGeneratorExceptionThe exception that is thrown when a name conflict occurs while a strongly typed is being generated.
System.Xml.dll
System.Xml
Returns detailed information about the last exception.
System.Xml.Schema
UpaException
XmlSchemaExceptionReturns detailed information about the schema exception.
Returns information about errors encountered by the class while inferring a schema from an XML document.
Represents the exception thrown when XML Schema Definition Language (XSD) schema validation errors and warnings are encountered in an XML document being validated.
System.Xml.XPath
Provides the exception thrown when an error occurs while processing an XPath expression.
System.Xml.Xsl
The exception that is thrown by the Load method when an error is found in the XSLT style sheet.
The exception that is thrown when an error occurs while processing an XSLT transformation.
System.dll
System
The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.
System.ComponentModel
InvalidAsynchronousStateException
Thrown when a thread on which an operation should execute no longer exists or has no message loop.
The exception thrown when using invalid arguments that are enumerators.
Represents the exception thrown when a component cannot be granted a license.
Specifies an exception that is handled as a warning instead of an error.
Throws an exception for a Win32 error code.
System.ComponentModel.Design
The exception that is thrown when an attempt to check out a file that is checked into a source code management program is canceled or fails.
System.Configuration
The exception that is thrown when a configuration system error has occurred.
SettingsPropertyIsReadOnlyException
Provides an exception for read-only objects.
SettingsPropertyNotFoundException
Provides an exception for objects that are not found.
SettingsPropertyWrongTypeException
Provides an exception that is thrown when an invalid type is used with a object.
System.IO
InternalBufferOverflowException
The exception thrown when the internal buffer overflows.
The exception that is thrown when a data stream is in an invalid format.
System.Net
The exception that is thrown when an error is made adding a to a .
The exception that is thrown when an error occurs processing an HTTP request.
InternalException
ProtocolViolationExceptionThe exception that is thrown when an error is made while using a network protocol.
The exception that is thrown when an error occurs while accessing the network through a pluggable protocol.
System.Net.Mail
Represents the exception that is thrown when the is not able to complete a or operation.
Represents the exception that is thrown when the is not able to complete a or operation to a particular recipient.
The exception that is thrown when e-mail is sent using an and cannot be delivered to all recipients.
System.Net.NetworkInformation
The exception that is thrown when an error occurs while retrieving network information.
The exception that is thrown when a or method calls a method that throws an exception.
System.Net.Sockets
The exception that is thrown when a socket error occurs.
System.Security.Authentication
The exception that is thrown when authentication fails for an authentication stream.
The exception that is thrown when authentication fails for an authentication stream and cannot be retried.
System.Threading
The exception that is thrown when the method is called on a semaphore whose count is already at the maximum.
Validating against XSD’s
February 27, 2009 § 2 Comments
The last post about creating XSD’s won’t help you much if you can’t figure out how to validate your XML against an XSD. Obviously, you can put the reference to the XSD into the XML file like this:
<SEASON xmlns="http://www.jamware.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jamware.net/baseball.xsd">
This’ll work fine, obviously, but what if you aren’t in control of the XML file? For instance, you may be getting the file from a third party (customer or vendor) and can’t modify it, yet you still want to verify it against an XSD.
Here’s a utility class you can add to your toolbox. Give the Validate function your XML as a string and your XSD as a string. It could probably use some function overrides to read directly from files, but I’ll leave that as an exercise for the reader. This was enough for my needs.
/// <summary>
/// validates xml
/// </summary>
public class ValidateXml
{
private List<Exception> validationExceptions;
/// <summary>
/// Gets or sets the validation exceptions.
/// </summary>
/// <value>The validation exceptions.</value>
public List<Exception> ValidationExceptions
{
get { return validationExceptions; }
}
/// <summary>
/// Validates the specified XML.
/// </summary>
/// <param name="xml">The XML.</param>
/// <param name="xsd">The XSD.</param>
public bool Validate(string xml, string xsd)
{
validationExceptions = new List<Exception>();
XmlParserContext context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);
XmlTextReader xmlReader = new XmlTextReader(xml, XmlNodeType.Document, context);
XmlTextReader xsdReader = new XmlTextReader(xsd, XmlNodeType.Document, context);
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas.Add("", xsdReader);
readerSettings.ConformanceLevel = ConformanceLevel.Auto;
XmlReader objValidator = XmlReader.Create(xmlReader, readerSettings);
try
{
while (objValidator.Read()) { }
}
catch (Exception ex)
{
validationExceptions.Add(ex);
}
finally
{
objValidator.Close();
xmlReader.Close();
xsdReader.Close();
}
return (validationExceptions.Count == 0);
}
}
Creating XSD’s
February 27, 2009 § 1 Comment
XSD’s are nice, but they’re kind of a pain to define. You wind up having to look up the syntax every time you need to create one, because you don’t do it often enough to remember it when you need (or at least, I don’t remember it). Well, I had to define an XSD recently, and I thought that maybe there’s a better way to handle it.
I find it much easier to create an XML document than to create an XSD, and frequently, I even already have an XML document. So here is a little function for your toolbox that helps a ton with that. Just pass it the filename to your XML file, and give it another filename to write the XSD to.
public XmlDocument CreateXSD(string xmlFileName, string xsdFileName)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlFileName);
XmlSchemaInference inference = new XmlSchemaInference();
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(xml.InnerXml));
XmlTextReader reader = new XmlTextReader(stream);
XmlSchemaSet schemaSet = inference.InferSchema(reader);
foreach (XmlSchema schema in schemaSet.Schemas())
{
TextWriter target = new StringWriter();
schema.Write(target);
target.Close();
StreamWriter sw = new StreamWriter(xsdFileName);
sw.Write(target.ToString());
sw.Close();
}
return xml;
}
So if we take a sample XML file (I used this one on cafeonleche.org), we get an XSD that looks like this:
<?xml version="1.0" encoding="utf-16"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="SEASON">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="YEAR" type="xs:unsignedShort" />
<xs:element maxOccurs="unbounded" name="LEAGUE">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="LEAGUE_NAME" type="xs:string" />
<xs:element maxOccurs="unbounded" name="DIVISION">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="DIVISION_NAME" type="xs:string" />
<xs:element maxOccurs="unbounded" name="TEAM">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="TEAM_CITY" type="xs:string" />
<xs:element name="TEAM_NAME" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="unbounded" name="PLAYER">
<xs:complexType>
<xs:sequence>
<xs:element name="SURNAME" type="xs:string" />
<xs:element name="GIVEN_NAME" type="xs:string" />
<xs:element name="POSITION" type="xs:string" />
<xs:element minOccurs="0" name="WINS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="LOSSES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="SAVES" type="xs:unsignedByte" />
<xs:element name="GAMES" type="xs:unsignedByte" />
<xs:element name="GAMES_STARTED" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="COMPLETE_GAMES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="SHUT_OUTS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="ERA" type="xs:decimal" />
<xs:element minOccurs="0" name="INNINGS" type="xs:decimal" />
<xs:element minOccurs="0" name="HITS_AGAINST" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="HOME_RUNS_AGAINST" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="RUNS_AGAINST" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="EARNED_RUNS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="HIT_BATTER" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="WILD_PITCHES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="BALK" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="WALKED_BATTER" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="STRUCK_OUT_BATTER" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="AT_BATS" type="xs:unsignedShort" />
<xs:element minOccurs="0" name="RUNS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="HITS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="DOUBLES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="TRIPLES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="HOME_RUNS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="RBI" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="STEALS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="CAUGHT_STEALING" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="SACRIFICE_HITS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="SACRIFICE_FLIES" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="ERRORS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="WALKS" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="STRUCK_OUT" type="xs:unsignedByte" />
<xs:element minOccurs="0" name="HIT_BY_PITCH" type="xs:unsignedByte" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Neat, huh?
things that make you go hmm (part 2)
February 27, 2009 § Leave a comment
I stared at this for probably 5 minutes straight in an attempt to figure out what I was missing.
public int Compare(PropertyBag p1, PropertyBag p2)
{
int retval = p1.NavigateOrder.CompareTo(p2.NavigateOrder);
if (retval != 0)
{
//if the navigate orders are not equal, the higher is later
return retval;
}
else
{
//if the navigate orders are equal, sort them together
return p1.NavigateOrder.CompareTo(p2.NavigateOrder);
}
}//End Compare