Categories
.NET Tools and Utilities

SubSonic and Club Starter Kit

If you don't code generate your DAL or use OR/M or anything that would
make you worry less about DataAccess like LINQtoSQL, Entity Framework, NHibernate, Castle
ActiveRecord then you should definitely give SubSonic a shot.

On the side I'm currently working on a C# version of Extended Club Starter Kit Version 3 Beta 1 for one club that I was part of in college (and probably a few others) and one thing to note is that the project has opted to use SubSonic. It's an open source project developed by Rob Connery and a few other popular developers in the .NET. It simplifies generation of Data Access code and some utility functions common to development. And don't forget about the cool Scaffolding support. As I've heard this is one of the popular features of the Rails framework where pages are generated on the fly to serve as you're admin tool for add/edit operations against your database table. They could be considered your admin pages or at least help during development. Bottom line is, all these features will save your time (which is what SubSonic aims for). [more]

You can opt to have the DAL generated on the fly using ASP.NET build providers, generate them using command line or as of the current version a GUI tool called "SubStage" (it is also were I view the auto scaffolding).

You can also download the SubSonic Starter Kit and get a web site already configured to work with SubSonic, UrlRewriter.NET (which is also keeping me busy considering that IIS 7.0 now allows httpmodule to run for all requests simply by configuring web.config) and a built in Content Management System. Not as complicated (a good thing) as other full blown CMS but will probably integrate this with the Club Starter Kit (so the club won't need to know programming or get back to me if they need some new pages or the sort).

It would be a good practice for me to leave the ClubSK on VB.NET and make some modifications but since I'm new with SubSonic and intend to use it for other projects, will have to remove the language barrier first so C# it is 🙂

I will definitely post the code here (or some other open source hosting like CodePlex) and try my best to keep this version abreast with the original ClubSK once I'm done. So far I have the DAL (separate project), App_Code and some pages converted to C# already and using SubSonic 2.1. Hopefully I'll have enough time to finish sometime soon.

Categories
.NET Agile Tools and Utilities

Link: Sandcastle Source Code published in Codeplex

After some issues regarding the license and terms of SandCastle in CodePlex, the project is now again available at CodePlex; this time with source code and not just the executable and documentation.

You can read more on this at this SandCastle blog post : Sandcastle Source Code published in Codeplex

Or go directly to their site at CodePlex : http://www.codeplex.com/Sandcastle 

Categories
.NET

Free Foundations of Programming Book by Karl Seguin

Came across this Foundations of Programming Book by Karl Seguin (ebook actually) when I looked into CodeBetter.com

It contains articles that were previously posted on the site and I had the chance to scan/skim over it and wow, I’d have to say this is a must read for developers at any level (probably even the “guru”s need to have a look at it).

The book is 79 pages short. [more] Yes that is considering the the comprehensive content and not to mention that it includes cover, table of contents and other pages aside from the content itself.

I believe the samples are in C# but since it is really a foundation about programming don’t expect foundations of C# or any other language.

It covers very interesting topics like Agile Development (Test Driven, Domain Driven development/design, Continuous Integration) and other basic stuff like Memory, Exception Handling. Topics where the CodeBetter folks are really good at.

Honestly I haven’t read those articles/post yet but will definitely sit down with this ebook and hold on other readings I regularly do (My Journeyman to Master on Safari is not yet finished).

Thanks to Karl for the effort of putting this together. It’s one thing to write sporadic, uncoherent posts through blogs. It’s another thing to come with such a well written series of articles worthy of a full blown book.

Categories
.NET Data

Link: SQL Server 2008: new data types and .Net 2 with and without SP1

Here's an interesting I came across in the recent Simple Talk Newsletter (by Red Gate Software).

It talks about issues with new SQL 2008 data types (date/time related) and it's effect on .NET 2.0 datetime data types when SP1 is installed or not. Something to be aware of and one of those times that you're glad you have a web rather than a desktop application. (you only have to install SP1 on the server(s))

SQL Server 2008 has introduced a few new data types, among others the
new date types, like date, time, datatime2 and datetimespan. Because
.Net 2 was released before SQL Server 2008 has introduced these data
types, there are no classes that map to these new types in .Net 2.
But this has changed with .Net 2 SP1, which introduces the DateTimeOffset structure.

Read full article from the following link :SQL Server 2008: new data types and .Net 2 with and without SP1

Categories
.NET

Sys.ArgumentException: Value must not be null for Controls and Behaviors

I was going thru some pages for my current project today when I ran into the said error "Sys.ArgumentException: Value must not be null for Controls and Behaviors". It was the first time I've encountered it and since it was working the last time I browsed it I didn't have a clue what was causing it so had to dig around. [more]

I have tested the page though I have to admit that not thoroughly (yeah I know, don't check in not well tested code) and there was no automated UI tests for it, took me sometime to stop the cause. I had to consider what applications I installed on my machine recently or other changes.

After some digging it turns out that it is related to a modalPopupExtender (part of AJAXControlToolkit) in the page.

Moving on, the extender's TargetControlID was set to let's say "linkAddItem" control.

Now, the catch is that recently I added an inline condition (ok, not really sure what is the right term for this but something like the one below):

<% if(MyCondition) { %>

<asp:LinkButton ID="linkAddItem" (definition here…. plus some other text) 

<% } %> 

So as you might have guessed, the page was looking for "linkAddItem" but in case MyCondition is true, it would not be rendered thus causing the error. I had read somewhere that if you have the TargetControl's (eg. linkAddItem) Visible attribute equals to "false", the AJAX control toolkit code would be able to detect with no problems. But not this one. The "Valu" mentioned in the error is likely the TargetControlID or at least related to it. You could verify by debugging the client script if this wouldn't solve the problem but fortunately enough not to go that far.

To cut this short story even shorter, my work-around was to instead have that block wrapped inside a panel (<asp:Panel…) and on Page PreRender, set the Panel.Visible = MyCondition. To simplify you could set just the control (eg. linkAddItem) Visibility but since there are other controls in that block, in my case the panel would be good.

I believe you can also set Visible='<%= MyCondition %>' of the panel in the ASPX page rather than at runtime/code for as long as you have the Page databound. : this.DataBind(); (but be careful, this is recursive and would rebind all other controls in your page you have bound previously).

Next time you run into this error, it is likely that one of the possible suspect is control visibility.

Categories
.NET Data

Link: Testing SQL Stored Procedures Using LINQ

Just ran into this interesting article on MSDN Magazine about using LINQ to test stored procedures. It would be a bad idea to test stored procedures using other stored procedures too (eg. insert SP then verify presence of inserted value using select/load SP) so traditionally we do it using ADO.NET object (conn, commands) to build commands. But this LINQ approach seems very interesting. Easy of building commands, intellisense, compile time checking among others. That's another good use for LINQ which I'm really starting to like (hopefully even after trying it for n-tier projects)
The article also comes with a virtual lab for hands-on experience.

 

The need to test a program that accesses and manipulates a back-end SQL Server®
database is very common. In many such cases, the application interacts
with the back-end data through the use of SQL stored procedures.
In
this type of scenario, you can think of the stored procedures as
auxiliary methods of the system under test; and they must therefore be
tested just like any other module in the system.
 


Read full article here

Categories
.NET Tools and Utilities

Link: SandCastle removed from CodeProject (temporarily I hope)

Due to popular outcry against having a non-open source project on the site, Microsoft has pulled Sandcastle from CodePlex. According to Anand, Microsoft is considering either moving the project to MSDN Code gallery or republishing the project with the source code. In the mean time you can download the May CTP from Paulo Santos' mirror.

Read full article from InfoQ 

Categories
.NET

Replacing Recursion with a Stack

I've been wanting to write about this for a long time and googling didn't return popular hits back then but just had time to write this but sharing nevertheless.

In a number of programming interview guides (most notably that of Joel Spolsky) it has been mentioned that one of the ways (note: only one and not the be all and end of it) to find out whether someone is "smart and gets the job done" is to ask them about recursion. And I agree in the sense that YES someone who has a good idea on recursion probably has good logic and flows and thus could be a good programmer but someone who might not know how to approach one might not be that brilliant but could still do the job (this one is of course my opinion).

Then it came to me that one doesn't necessarily have to know recursions or recursive functions if they do know how to approach the problem using stacks. Now why would I do that? The answer would be performance (very significant especially if the operation involves millions of level in the hierarchy and heavy operations for each node). The drawback is it is a little more code and possibly more complicated. But for most applications, the performance gain is very much worth it. [more]

According to wikipedia

"Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. The term is also used more generally to describe a process of repeating objects in a self-similar way."

while stack is an abstract data type and data structure based on the principle of Last In First Out (LIFO). 

To illustrate better. Let's say we have a simple class named Node with properties Name and ChildNodes (a node can contain nodes in itself) and a method to generate a sample nodes with descendant nodes.

    1     class Node

    2     {

    3         public string Name;

    4         public List<Node> ChildNodes = new List<Node>();

    5 

    6         public static Node GenerateTestData()

    7         {

    8             Node retVal = new Node();

    9             retVal.Name = "Categories";

   10 

   11             Node a = new Node();

   12             a.Name = "Food";

   13 

   14             Node b = new Node();

   15             b.Name = "Electronics";

   16 

   17             Node c = new Node();

   18             c.Name = "Places";

   19 

   20             retVal.ChildNodes.Add(a);

   21             retVal.ChildNodes.Add(b);

   22             retVal.ChildNodes.Add(c);

   23 

   24             // Food level 1

   25             Node a1 = new Node();

   26             a1.Name = "Fruits";

   27 

   28             Node a2 = new Node();

   29             a2.Name = "Vegetables";

   30 

   31             Node a3 = new Node();

   32             a3.Name = "Meat";

   33 

   34             a.ChildNodes.Add(a1);

   35             a.ChildNodes.Add(a2);

   36             a.ChildNodes.Add(a3);

   37 

   38             // Fruits level 2

   39             Node a1a = new Node();

   40             a1a.Name = "Apple";

   41 

   42             Node a1b = new Node();

   43             a1b.Name = "Orange";

   44 

   45             a1.ChildNodes.Add(a1a);

   46             a1.ChildNodes.Add(a1b);

   47 

   48             // Meat level 2

   49             Node a3a = new Node();

   50             a3a.Name = "Beef";

   51 

   52             Node a3b = new Node();

   53             a3b.Name = "Pork";

   54 

   55             Node a3c = new Node();

   56             a3c.Name = "Chicken Meat";

   57 

   58             a3.ChildNodes.Add(a3a);

   59             a3.ChildNodes.Add(a3b);

   60             a3.ChildNodes.Add(a3c);

   61 

   62             // Electronics level 1

   63             Node b1 = new Node();

   64             b1.Name = "TV";

   65 

   66             Node b2 = new Node();

   67             b2.Name = "Phone";

   68 

   69             Node b3 = new Node();

   70             b3.Name = "Radio";

   71 

   72             b.ChildNodes.Add(b1);

   73             b.ChildNodes.Add(b2);

   74             b.ChildNodes.Add(b3);

   75 

   76             // Places level 1

   77             Node c1 = new Node();

   78             c1.Name = "Parks";

   79 

   80             Node c2 = new Node();

   81             c2.Name = "Hospitals";

   82 

   83             Node c3 = new Node();

   84             c3.Name = "Malls";

   85 

   86             c.ChildNodes.Add(c1);

   87             c.ChildNodes.Add(c2);

   88             c.ChildNodes.Add(c3);

   89 

   90             return retVal;

   91         }

   92     }

The node hierarchy is something like:

Categories
    Food
        Fruits
            Apple
            Orange
        Vegetables
        Meat
            Beef
            Pork
            Chicken Meat
    Electronics
        TV
        Phone
        Radio
    Places
        Parks
        Hospitals
        Malls

Now, let's say the requirement now is to display all the nodes inside the generated test node including itself (in a Console Application for example)

The common approach is to have a recursive function similar to this

    1         private static void PrintNodeNamesRecursive(Node n)

    2         {

    3             Console.WriteLine(n.Name);

    4             foreach (Node child in n.ChildNodes)

    5             {

    6                 PrintNodeNamesRecursive(child);

    7             }

    8         }

What it does is when you pass a node, it displays the node's name, then loops over the child nodes and calling the same function (itself) for each of the child node.

Running the function from the main method (like below)

    1         static void Main(string[] args)

    2         {

    3             Node c = Node.GenerateTestData();

    4             PrintNodeNamesRecursive(c);

    5             Console.ReadKey();

    6         }

should result to something like 

Now on the main topic. The same result can be produced with the following method making use of stack instead of calling itself.

    1         private static void PrintNodeNamesWithStack(Node p)

    2         {

    3             Stack<Node> s = new Stack<Node>();

    4             s.Push(p);

    5             while (s.Count > 0)

    6             {

    7                 Node current = s.Pop();

    8                 Console.WriteLine(current.Name);

    9 

   10                 // we can use foreach loop here and still go through every node but

   11                 // to come up with exactly the same output as the recursive function

   12                 // we push the last child node first so it is popped last and thus printed

   13                 // last, the same order as the recursive function

   14                 for (int a = current.ChildNodes.Count-1; a >= 0; a–)

   15                 {

   16                     s.Push(current.ChildNodes[a]);

   17                 }

   18             }

   19         }

Now see for yourself and you'd get the same results.

So what makes the performance difference?

If you will notice, when you debug the recursive approach, the function is called over and over again and the call stack is used to internally track which call to return to after one is finished. This is where using the explicit stack approach makes the difference. In the latter we loose the overhead of having the program remember which function call/line to return to; rather it just needs to loop until all the items in the stack is popped out and thus involves less work.

Again the alternative might/likely involve a little more code and honestly could be more complicated (depending on how you think) but if you understand the concept and you're particular about performance (which I would recommend you are) then have a look at it.

Before posting this post, I googled for "replacing recursion with stack" and I came across this post from Phil Haack on the same topic with a sample on finding controls inside an ASP.NET page which is one of the practical applications of this alternative so please go ahead and read it too : Replacing Recursion with a Stack (yeah same title I know but that's what it is really all about)

I'm not quite sure where I knew about this, probably some posts or code I've read some time ago but I do remember getting reminded and getting help on this while working with a former colleague. So special thanks to Joseph.

Hope you'd find the approach helpful too. 🙂

Categories
.NET

Considerations for AJAX UpdatePanel, Page Methods and Web Services

I would not even pretend to be all knowing here but I couldn't stop myself from sharing this chain of interesting links which should remind all of us of the dangers of abusing UpdatePanels thinking that using it in any way will make our old non asynchronous pages work like magic. [more]

My journey starting with this post : Why do ASP.NET AJAX page methods have to be static? which happened to be included in ScottGu's April 28th links.

I have known and heard page methods before but haven't really used it as much as I use UpdatePanel but you ought to read that link and from there you should view the link on Why ASP.NET AJAX UpdatePanels are dangerous (the text being linked in the article is actually "They are especially performant compared to the UpdatePanel’s partial postbacks.") but I find the real title more interesting. It might not be true as "danger" is indeed relatively. But to give you a short note, UpdatePanel is still posting back to the server (including ViewState et al), it just does that asynchronously but bottom line is that a lot of information is still being sent back and forth from server-client and in some cases that is a lot of unnecessary information. I would suggest going through the article including the comments as there really are cases where Page Methods or UpdatePanel is more appropriate but bottom line is we ought to know them and just because we use UpdatePanels it doesn't mean we have the best AJAX solution.

This reminded of a case where I had a calendar control inside an UpdatePanel and looks fast locally but when deployed to a test server was considerably slower. Turns out that the page itself has a large viewstate and async postback triggered by the UpdatePanel brings that large viewstate to the server. In addition, the page will also be reconstructed (control values/properties) thus an additional overhead.

The asynchronous processing is likely to help but think again as a pure Javascript solution might be better, or PageMethods (which is sort of a easier/or at least a close alternative to having ASMX (web services)).

Check out this link on Exposing Web Services to Client Script which includes a discussion, source and sample for Page Methods.

And also if you want to hook client side events of UpdatePanels (eg. Begin/End Requests) check out this link : Use the PageRequestManager to Get More Control of Your UpdatePanels

This stuff is also a good review for upcoming ASP.NET 3.5 MCTS as there were a lot of items involving Client Scripts (more than knowing what UpdatePanel's are and which property to set for which).

Categories
.NET

Updating ASP cookie from ASP.NET (vice versa)

You might encounter a case where updating an ASP (classic/3.0) cookie from ASP.NET code (or vice versa) doesn't work. That is despite updating the cookie value, the old value still remains. [more]

I was working on a having an ASP page communicate some information to an ASP.NET (2.0) page and vice versa and since the information was not that critical/confidential a cookie would do (** for critical information, it is usually done using a common datastore/database or session though that not secure. will not discuss here for now). I expect it to be seamless since they're accessing the same set of cookies after all. However to my surprise it was acting weird.

After a review of some code and I was certain that each of them updates the cookie correctly, it was time to bring up fiddler (or any cookie viewer) and it's when I started getting more clues.

To illustrate better I came up with the following simple ASP and ASP.NET pages

<!– start of ASP code (VBScript) –>

<html>
<body>
    <%

    Response.Write("Old Value = " & Request.Cookies("a"))
   
    dim newValue
    newValue = "Classic"
    Response.Cookies("a") = newValue
    Response.Write("<br/>")
    Response.Write("Attempted New Value = " & newValue)

    %>
    <br />
    <br />
    <a href="Default.aspx">ASP.NET Page</a>
</body>
</html>

<!– end of ASP code –>

<!– start of ASPX markup –>

<%@ Page AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="ASPCookieASPNETCookie._Default"
    Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <a href="Default.asp">Classic ASP Page</a>
    </form>
</body>
</html>

<!– end of ASPX markup –> 

And the codebehind (C#)

    1 using System;

    2 

    3 namespace ASPCookieASPNETCookie

    4 {

    5     public partial class _Default : System.Web.UI.Page

    6     {

    7         protected void Page_Load(object sender, EventArgs e)

    8         {

    9             Response.Write("Old Value = " + (Request.Cookies["a"] != null ? Request.Cookies["a"].Value : ""));

   10 

   11             string newValue = "DotNet";

   12             Response.Cookies["a"].Value = newValue;

   13             Response.Write("<br/>");

   14             Response.Write("Attempted New Value = " + newValue);

   15         }

   16     }

   17 }

 

So as you can see I'm trying to manipulate a cookie named "a". This is what appeared in Fiddler after loading the two pages one after the other.

Now that is two cookies with the same name. My initial reaction was it shouldn't have been possible but I trusted fiddler enough so I roamed around the web and finally got my answers especially from here

Despite belonging to the same domain, the uniqueness of the cookie is also affected by the cookie's Path property. That is two cookies with the same name and from the same domain (or subdomain) can exists if they belong to different paths (application path).

So to make the long story short if you want make the cookie updateable from both ASP and ASP.NET the path has to be identical (and reasonable ofcourse not just some random path)

Either:

1. Add this to the ASP code : Response.Cookies("a").Path = "/"

2. Or Add this to the ASP.NET code : Response.Cookies["a"].Path = "/<yourApplicationName>"; 

You can use Page.ResolveUrl("~") to determine application name but make sure to remove the trailing "/" in the resulting string (.NET 2.0 seems to add a trailing "/" but not .NET 1.1 if I remember well) 

or ofcourse the equivalents if you're not using VBScript/C#.

That's it and you're good.


Other Info:

1. Attached sample download project here : ASPCookieASPNETCookie.zip (5.33 kb) ** Note that this is a Web Application project that uses IIS as web server (right click on Project –> Properties –> Web tab and set accordingly and see attached screenshot too for more info UseIISWebServer.gif (20.06 kb). Also note that creating a virtual directory from the page would not automatically set Integrated Windows Authentication on for the created virtual directory (it inherits from the website properties) and running F5 from Visual Studio would throw a dialog saying such should be enabled. To enable, open IIS Manager –> site/virtual directory properties –> Directory Security tab –> Edit –> Check Integrated Windows Authentication.

2. Note that using IE7 and localhost will not register any traffic in Fiddler. Work around is to use machine name or add a "." after localhost (eg. http://localhost./AppName/TestPage.aspx)* note the dot "." after localhost. You can do this by manually editing the URL/address bar of the browser or setting it in the Web Properties page mentioned in item 1 above.