Showing posts with label software development. Show all posts
Showing posts with label software development. Show all posts

Wednesday, August 26, 2009

Developer AutoLogin & Redirect

A large project I'm working on these days includes a Login page which each user must pass through before being able to access the rest of the site. There is code similar to this that prevents unauthorized entry onto every page:












For some time I would just comment out this code until the rest of the module was complete. The problem with that is that as the application became more & more sophisticated, there was assorted initialization code elsewhere that has to be executed each & every time.

For the Run-Debug cycle it became exceptionally time consuming (and annoying) to manually go through the entire login process every time. Here's an example of the steps involved:







































Oh sure, it's just a few keystrokes and mouse clicks each time but repeated dozens (or hundreds!) of times per day, one soon hopes for a way to automate the process. And I found it!



In Visual Studio's Solution Explorer, right-click on whatever page you're working on and choose "Set As Start Page" from the popup menu. Note: You've probably already done this!

Now in the Page_Init event handler of your Master Page (FYI all my projects use Master Pages) add this code:

protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
// If we're on a development machine then record the Start Page that Visual Studio is set to
string currPage = Page.ResolveUrl(Request.ServerVariables["URL"].ToString());
if (System.Diagnostics.Debugger.IsAttached && SessionData.GetCurrentUser() == "")
if (SessionData.GetSessionObject("CurrentDebugPage") == null)
SessionData.SaveSessionObject("CurrentDebugPage", currPage);
}
}

Then in the Page_Load event handler of your login page add this code:

// Note: This must be set above: using System.Web.Security;
protected void Page_Load(object sender, EventArgs e)
{
// This tests whether we're running on a development machine. If so, we'll automatically login.
if (System.Diagnostics.Debugger.IsAttached && SessionData.GetCurrentUser() == "")
{
string currUser = "your_username";

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(currUser, false, 5);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);

// If a specific page has been set as the Start Page then redirect to it; otherwise go to the Default page
string currDebugPage = SessionData.GetSessionObject("CurrentDebugPage").ToString();
HttpContext.Current.Response.Redirect((currDebugPage == null) ? "~/default.aspx" : currDebugPage, true);
}
}

Note: The various SessionData methods are just simple ones I've constructed to ease the process of storing & retrieving variables in the Session State. I will gladly provide them upon request.



The result is that now, every time I run my project in Visual Studio, it jumps right to the desired web page, logging me in automatically. And yet when run in non-Debug mode it works normally. So I don't have to alter any code whenever I release a new production version.

In case you're wondering how this works, the process is quite straightforward:
  1. The Master page's Page_Init event handler is run before every Content page's Page_Load event handler. It records the start page that the developer wanted to go to, placing this string into a Session variable.
  2. When that desired page's Page_Load event handler is initially entered, the security checks therein reject entry because the user is not logged in. They then redirect to the Login page.
  3. In the Login page the special test in Page_Load passes because the code is being run from Visual Studio and because the user is not yet logged in.
  4. A FormsAuthenticationTicket is instantiated and then placed in a Cookie. This allows one to artificially login through the ASP.Net Login mechanism.
  5. The desired start page, originally stored by the Master Page, is retrieved from the Session State and control is redirected to that page.
  6. This second time the security checks in the desired page's Page_Load event handler pass because the user is now officially logged in.
It actually works really well and will save you a lot of time! If you have any questions, please just leave a comment.

Thursday, November 27, 2008

Reverting Back to Visual Basic 6

Though I spend most of my life these days working with C#.net (and absolutely love it by the way!) occasionally I get a request from a long-standing client to update an old WinForms app. I built the first version in 1995 with Visual Basic 1.0 for DOS. I so wanted to write it in VB 3.0 for Windows but they insisted that they were more comfortable with DOS apps.

So build it I did. It was so primitive that I distinctly recall having to manually construct a ListBox!

The entire project will always be memorable to me. This was my first contract after going into business for myself for the first time on January 1, 1995. Just a few weeks before I had purchased a brand spanking new Pentium 1 / 90 MHz computer. With a monitor and printer the whole thing came to about $5,000. Yes, five THOUSAND dollars, not five hundred!

To start off the project I drove from Vancouver all the way up to Thompson, Manitoba, a distance of about 2500km.
I made this journey (and many subsequent ones like it) in my trusty 1987 VW Diesel Golf. I loved that car. On a tank of diesel fuel, which then cost about $25.00 I could drive 800km. I bought it in Ontario in 1992 with 60,000 km on it. It would last until 2001 with over 300,000 km. By then the driver's seat was literally ready to fall through the much decayed floor! So I donated it to a high school in Victoria, BC and received a tax credit for $100. Apparently they were going to cut it in half and weld it onto the other half of another VW.
Getting back to the original story . . . I spent a few weeks up in Thompson, gathering user requirements for the Survey System application (as in cartographic surveying) that I had been hired to build. I then drove back to Vancouver and started work on it. I got the entire thing built in about 2 months and returned to Thompson to install it, test it, tweak it, and train the users. This all went exceedingly well.

I recall that I was only charging them $35 per hour (which was even very cheap back then) for a grand total of less than $15,000. At the end of the project my sponsor, a wonderful English gentleman named Noel Laine, said to me, "I don't know how to tell you this, Rob, but you didn't charge us enough for this!" I asked him if I could retroactively raise the price. :-) He smiled and slowly shook his head.

It was a great start to my career as a consultant though and I have no regrets. And I believe my hard work and dedication laid the groundwork for a longstanding, positive relationship with this client. The fact is that in the summer of 1997 they paid me to upgrade it to work with Windows. I think I charged them $50 per hour for a total of $20,000; still cheap by today's standards! What was great, and a credit to Microsoft, was that the code for the core calculation module could be brought directly into Visual Basic 5.0, which was the standard at the time. It was very involved, intricate programming, involving a lot of math and geometry, which I hope I'll never have to write again!

Since that time, there have been periodic requirements every few years to add a feature and tweak something else. Just yesterday I received such a request. Switching my mind from the elegance and strongly typed language of C# to the much less strongly typed and error prone Visual Basic 6.0 took a few minutes but I quickly got the hang of it.

The IDE of Visual Studio .Net is so much more intelligent than the IDE of Visual Basic 6. I really missed not being immediately informed of coding mistakes I was making. To find the obvious ones, I had to compile the code into an EXE. Only then would it point out things like "If with no End If" and "Variable not declared". These are all things that a modern developer takes for granted.
When I finally got things working & tested, I uploaded a copy of the new version to an FTP server and informed my client of the same. He immediately downloaded it this morning and tested it. There was one minor tweak which I've already fixed and re-uploaded. No more driving 2,500 km or having to send a disc (or disks!) in the mail.

How the world has changed in such a short period of time. Yet it's always fun to walk down memory lane!

Monday, April 21, 2008

"Does not exist in the current context"

The fun & games with Visual Studio continue! I generally love the package but sometimes it frustrates me to no end.

So there I was testing a simple web page, adjusting this & that. Suddenly, when I tried to recompile it I got this message:

labelTagLine does not exist in the current context

This control resides in the header on the Master Page of my project. There's nothing fancy or special about it. I did a comprehensive search and found lots of others who had encountered similar problems with controls suddenly not being recognized. I tried all of their solutions but to no avail.

So eventually I copied main.Master and main.Master.cs outside of the project folder and deleted these two files within the project. Then I created a new, blank version of them. Slowly, I started copying the markup code and C# code back into their respective files, being sure to perform a "Rebuild Website" every so often. Lo and behold, when every last line of code was back, it worked! Something internally must have changed but nothing in my code files did. Another 2 hours wasted. :-(