Get WeekDays in a Month (C# 3.0)

var weekends = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };


DateTime calendarMonth = DateTime.Parse(“10/1/2008”);


int totalDays = DateTime.DaysInMonth(DateTime.Now.Year, calendarMonth.Month);


IEnumerable<int> businessDays = Enumerable.Range(1, totalDays)

.Where(d => 

!weekends.Contains(new DateTime(DateTime.Now.Year, calendarMonth.Month, d).DayOfWeek)




//loop through businessDays or get a count…

Safari Windows Beta

If you haven’t checked it out yet already, I highly suggest downloading the Safari 3 Public Beta.  Obviously this makes testing easier (especially when you don’t have a Mac to test on).  It’s also blazingly fast.  I have noticed a significant speed difference when loading pages compared to IE7 or Firefox (especially with extra plugins) or Opera.  The font rendering is a direct emulation of OS X, which is definitely strange at first.  For larger fonts its great, but ClearType looks superior (to me at least) for smaller sizes…

Ajax.NET Professional with Mootools (part 2)

This is an update to my original post.  That version was a preliminary attempt and should not be used in production.

The MootoolsTypeJavaScriptProvider is a compatibility layer between AjaxPro and Mootools

The provider now supports most of the native AjaxPro javascript functionality.  The idea is to maintain as much compatibility as possible with the original AjaxPro javascript library to eliminate the need for changes to existing code.

Download Version 1.6 Binaries
Download Source Project

Tested on Internet Explorer 6 & 7, Firefox 1.5 & 2.0, Opera 9.

Working AjaxPro javascript options:

  • Fully compatible method signature for invoking calls from script: MyServerClass.Method(<arguments…>, callback, context, onError);
  • Synchronous requests (no change in syntax)
  • Compatible with most Global AjaxPro options & event handlers:
    • AjaxPro.onLoading
    • AjaxPro.onError
    • AjaxPro.onTimeout
    • AjaxPro.onStateChanged
    • AjaxPro.timeoutPeriod

Not working:

  • Support for any IE version less than 6 (this is a requirement for Mootools in general)
  • Tokens (they are implemented on the client, but when you set AjaxPro to RenderJsonCompliant, it stops emitting/checking the token data required.  An modified build of AjaxPro is required to fix this)
  • AjaxPro.cryptProvider
  • AjaxPro.queue (see below)
  • Using IFrames instead of XmlHttpRequest

Additions / Breaking Changes from default AjaxPro javascript lib:

  • AjaxPro.toJSON simply references Mootools Json.toString.  The resulting JSON string may be different.
  • AjaxPro.queue does not work, however you can toggle request queuing by using the AjaxPro.queueRequests flag I’ve added (defaults to true).  This is just a wrapper for Mootools autoCancel property which handles the actual request queue.
  • Aborting asynchronous requests uses different syntax.  To abort a request, use the following:
    var req = MyServerClass.Method(...); req.cancel();

    This is using the native cancel function from the Mootools XHR class.


  • Copy the mootools-core.js file into your project
  • Reference the Ifw.AjaxNet.dll assembly in your project
  • Adjust the AjaxPro web.config options in ajaxNet/ajaxSettings:
<scriptReplacements> <file name="core" path="~/res/js/ajaxpro/mootools-core.js"/> <file name="prototype" path=""/> <file name="converter" path=""/> </scriptReplacements> <providers> <typeJavaScriptProvider type="Ifw.AjaxNet.MootoolsTypeJavaScriptProvider, Ifw.AjaxNet"/> </providers> <oldStyle> <renderJsonCompliant/> <renderDateTimeAsString/> </oldStyle>

More AjaxPro Serialization Problems with NHibernate Entities

Edit: It seems that disabling lazy loading with NHibernate/ActiveRecord will keep properties from being overridden (and therefore AjaxPro will still see the base property AjaxNonSerializable attributes).  This can still have a negative effect on performance and I would like to fix the actual cause, but at least I can use this solution in the interim.

In my previous post, I mentioned how the bidirectional object references that manage parent-child relationships for a domain model intended for use with NHibernate causes AjaxPro’s JSON serializer to crash with an infinite loop.  The answer to this was to mark the “parent” properties of all child objects with an [AjaxNonSerializable] attribute.  In my initial tests, this worked great.  However, when actually using NHibernate to retrieve objects from the database, I’m back to my original crashing problem.

The crash is occurring because of how NHibernate creates new instances of objects from the database.  It is actually inheriting from your base object and returning an instance of that instead.  So instead of getting a Blog object, you are getting an instance of the Blog_NHibernate_proxy class which derives from Blog (that is not the actual naming convention, but illustrates the point).

The [AjaxNonSerializable] attribute doesn’t affect derived types, only the type you actually mark with it.  This creates a problem, since the NHibernate proxy types are generated at runtime via reflection.  There is no way that I know of to tell NHibernate to copy over attributes from the base class.  There is no way to tell AjaxPro to check base types for the attributes either.

I hope I am wrong about this.  Here is a simple test case to show that the AjaxPro serialization attributes only affect the defined type:

using System; using System.Text; using AjaxPro; using NUnit.Framework; namespace Ifw.Cgd.Tests.AjaxPro { public class Foo { public virtual string Name { get { return _test; } set { _test = value; } } [AjaxNonSerializable] public virtual string Name2 { get { return _test2; } set { _test2 = value; } } private string _test = ""; private string _test2 = ""; } public class Bar : Foo { public override string Name2 { get { return "overriden"; } set { base.Name2 = value; } } public virtual string Name3 { get { return _test3; } set { _test3 = value; } } private string _test3 = ""; } [TestFixture] public class AjaxProJsonTests { public string ajaxSerialize(object o) { StringBuilder sb = new StringBuilder(); JavaScriptSerializer.Serialize(o, sb); return sb.ToString(); } [Test] public void CanSerializeBaseObject() { Foo x = new Foo(); x.Name = "test"; x.Name2 = "test2"; //should be ignored by AjaxPro string js = ajaxSerialize(x); Console.WriteLine("Foo JSON: " + js); Foo abc = JavaScriptDeserializer.DeserializeFromJson<Foo>(js); Assert.AreEqual("test", abc.Name, "Foo.Name not set properly"); Assert.AreNotEqual("test2", abc.Name2, "Foo.Name2 should not be serialized"); } [Test] public void CanSerializeInheritedObject() { Bar x = new Bar(); x.Name = "test"; x.Name2 = "test2"; //should be ignored by AjaxPro x.Name3 = "test3"; string js = ajaxSerialize(x); Console.WriteLine("Bar JSON: " + js); Bar abc = JavaScriptDeserializer.DeserializeFromJson<Bar>(js); Assert.AreEqual("test", abc.Name, "Foo.Name not set properly"); Assert.AreEqual("test3", abc.Name3, "Foo.Name3 not set properly"); Assert.AreNotEqual("test2", abc.Name2, "Foo.Name2 should not be serialized"); } } }

Here is the output:

Foo JSON: {“Name”:”test”}
Bar JSON: {“Name2″:”overriden”,”Name3″:”test3″,”Name”:”test”}

If anyone knows a way around this, I would LOVE to hear it.  Thanks.

AjaxPro + NHibernate = Crash

The Problem

I’m currently using Castle ActiveRecord (which builds on NHibernate) for a web project. One problem I was having was pretty annoying when trying to access NHibernate-generated entities as JavaScript objects via Ajax.NET Professional. ASP.NET would hang for a while and then crash completely with the dreaded “Application Unavailable” error from IIS (or something like that).

With no error messages or stack trace, I immediately blamed the NHibernate proxy objects as the reason why this was happening. On this assumption, I started considering what would be involved to use DTOs instead of the actual domain objects. These would be simpler and hopefully, serializable. After going down that path and getting frustrated by the added effort required to make that solution work, I decided to come back to the AjaxPro serialization issue and see if I could figure out what the problem was.

The Cause

After writing some serialization tests using manually created instances of my domain models (not proxies that were generated from the NHibernate repository), I found that I had the same problem. Great, I thought, my class hierarchy is just too complex for the serializer to handle…

Actually, after considering what is happening in the JSON conversion process, it started to make sense. When using ActiveRecord (or NHibernate) you need bidirectional references with any collections (or else you lose a lot of functionality). So the Post object needs to have a Blog property referencing its parent object (which has a collection of Posts as well). Hence the reason for the crash: an infinite loop.

The Solution

Any circular references in your class relationships need to be excluded from serialization by marking those properties with [AjaxPro.AjaxNonSerializable] (in this case, the Blog property of the Post object). If you are a DDD purist, you may not like the idea of tacking attributes all over your domain model, but I already bit that bullet when going with ActiveRecord over pure NHibernate anyway.

Keep in mind that if you are passing JavaScript proxy objects back to the server for deserialization, you will need to reconnect the parent-child associations or NHibernate won’t be able to save them correctly. It is a little work, but much less than using DTOs with a ton of duplicated properties.


    using System;
    using System.Collections;

    using Castle.ActiveRecord;

    public class Blog : ActiveRecordBase

        private IList posts = new ArrayList();

        [HasMany(typeof(Post), Inverse=true)]
        public IList Posts
            get { return posts; }
            set { posts = value; }

The Post class:

    public class Post : ActiveRecordBase

        private Blog blog;

        public Blog Blog
            get { return blog; }
            set { blog = value; }

I think that it would be helpful if AjaxPro would check for these kinds of things and throw an Exception instead of just crashing, but the rest of it works quite well so I won’t complain too much there. It would also be nice if you didn’t have to wire up bidirectional associations to make NHibernate work. I suppose we have to work with the tools we are given though…

Ajax.NET Professional with Mootools

Edit: Do not use this.  See the updated post here.

Edit: I posted this pretty quickly without trying to pass back serialized types from the client to AjaxPro. Mootools Json.Remote prepends “json=” to the JSON string and AjaxPro’s deserializer doesn’t like that. To work around it, I have created Json.AjaxPro which removes this: 

Json.AjaxPro = XHR.extend({ initialize: function(url, options){ this.url = url; this.addEvent('onSuccess', this.onComplete); this.parent(options); this.setHeader('X-Request', 'JSON'); }, send: function(obj){ return this.parent(this.url, Json.toString(obj)); }, onComplete: function(){ this.fireEvent('onComplete', Json.evaluate(this.response.text,; } });

See also updated assembly and source code below

I have been meaning to start a blog for a while, if only so I can Google my own thoughts later on… I have been using the Ajax.NET library for JSON-RPC with ASP.NET for the last couple of years on various projects. It has always been the easiest way to get an AJAX app going quickly for me. In order to allow easier use with third party libraries like Mootools, the latest AjaxPro beta release adds the ability to alter JSON output to be strictly JSON-compliant (string date formatting mostly) and allows using a custom TypeJavaScriptProvider which renders the client script proxies for your server calls. It also adds the jQueryTypeJavaScriptProvider which generates jQuery-compatible proxy functions, eliminating the need to include the default AjaxPro “core”, “prototype core” and “converter” files. In addition to saving bandwidth, this eliminates potential conflicts with other libraries. Since Mootools already has XHR and JSON handling in the form of JSON.Remote, I took a look a the AjaxPro source to see if I could implement a Mootools provider. It is still a little rough and not every native feature of AjaxPro’s lib is implemented, but it will work for most cases I think. It supports callback, context and onerror arguments (no changes are required to existing javascript code). Tokens and the global AjaxPro.onError aren’t working yet, but I will take a look at it when I have more time. If anyone wants to improve on it, that would be helpful. To use this, download and reference this assembly. You will need the appropriate ajaxNet/ajaxSettings in your web.config 

<scriptReplacements> <file name="core" path=""/> <file name="prototype" path=""/> <file name="converter" path=""/> </scriptReplacements> <providers> <typeJavaScriptProvider type="Ifw.AjaxNet.MootoolsTypeJavaScriptProvider, Ifw.AjaxNet"/> </providers> <oldStyle> <renderJsonCompliant/> <renderDateTimeAsString/> </oldStyle>

Here is the VS2005 Project and a quick look at the (simple) source:  

using System; using System.Reflection; using System.Text; using AjaxPro; namespace Ifw.AjaxNet { public class MootoolsTypeJavaScriptProvider : TypeJavaScriptProvider { public MootoolsTypeJavaScriptProvider(Type type, string url, StringBuilder sb) : base(type, url, sb) {} public override void RenderClassBegin() { string clientNS = GetClientNamespace(); sb.Append("\r\n").Append(clientNS).Append("_class = new Class({\r\n"); sb.Append("AjaxUrl : '" + m_URL + "',\r\n"); } public override void RenderClassEnd() { string clientNS = GetClientNamespace(); sb.Append(@"AjaxProCB : function(response, onsuccess, context, onfailure) { var o = null; eval(""o = "" + response + "";""); if(o != null) { if(typeof o.value != ""undefined"" && typeof onsuccess == ""function"") { o.context = context; onsuccess(o); return; } else if(typeof o.error != ""undefined"" && typeof onfailure == ""function"") { onfailure(o.error); return; } } if(typeof onfailure == ""function"") { onfailure({""Message"":""Failed.""}); } } }); "); sb.Append(clientNS).Append(" = new ").Append(clientNS).Append("_class();\r\n\r\n"); } public override void RenderMethods(MethodInfo[] methods) { for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; string methodName = GetClientMethodName(method); ParameterInfo[] pi = method.GetParameters(); sb.Append(methodName); sb.Append(" : function("); for (int p = 0; p < pi.Length; p++) { sb.Append(pi[p].Name); sb.Append(", "); } sb.Append("onsuccess, context, onfailure)\r\n{"); sb.Append(@" return new Json.AjaxPro(this.AjaxUrl, { headers: {""X-AjaxPro-Method"":""" + methodName + @"""}, onSuccess: function(response) { " + GetClientNamespace() + @".AjaxProCB(response, onsuccess, context, onfailure); } }).send({"); for (int p = 0; p < pi.Length; p++) { sb.Append("\""); sb.Append(pi[p].Name); sb.Append("\":"); sb.Append(pi[p].Name); if (p < pi.Length - 1) sb.Append(", "); } sb.Append("});\r\n},\r\n"); //TODO: Implement support for AjaxPro Tokens /* string AjaxToken = @"beforeSend: function(xhr) { if(typeof AjaxPro !== 'undefined' && AjaxPro.token !== null) xhr.setHeader(""X-AjaxPro-Token"", AjaxPro.token);}"; */ } } } }

Here is an example of a Mootools proxy class generated with 2 server-side functions:

if(typeof Ifw == "undefined") Ifw={}; if(typeof Ifw.Cgd == "undefined") Ifw.Cgd={}; if(typeof Ifw.Cgd.Video == "undefined") Ifw.Cgd.Video={}; Ifw.Cgd.Video.ProjectManager_class = new Class({ AjaxUrl : '/ajaxpro/Ifw.Cgd.Video.ProjectManager,App_Code.lonzioom.ashx', LoadProjects : function(onsuccess, context, onfailure) { return new Json.AjaxPro(this.AjaxUrl, { headers: {"X-AjaxPro-Method":"LoadProjects"}, onSuccess: function(response) { Ifw.Cgd.Video.ProjectManager.AjaxProCB(response, onsuccess, context, onfailure); } }).send({}); }, SaveProject : function(dto, onsuccess, context, onfailure) { return new Json.AjaxPro(this.AjaxUrl, { headers: {"X-AjaxPro-Method":"SaveProject"}, onSuccess: function(response) { Ifw.Cgd.Video.ProjectManager.AjaxProCB(response, onsuccess, context, onfailure); } }).send({"dto":dto}); } AjaxProCB : function(response, onsuccess, context, onfailure) { var o = null; eval("o = " + response + ";"); if(o != null) { if(typeof o.value != "undefined" && typeof onsuccess == "function") { o.context = context; onsuccess(o); return; } else if(typeof o.error != "undefined" && typeof onfailure == "function") { onfailure(o.error); return; } } if(typeof onfailure == "function") { onfailure({"Message":"Failed."}); } } }); Ifw.Cgd.Video.ProjectManager = new Ifw.Cgd.Video.ProjectManager_class();

That should do it… Hopefully someone finds this useful.