ASP.NET UserControls that are AWESOME: Using Events, properties, and methods.

UserControls are underused
I am always shocked to see how little UserControls are used by some ASP.NET developers. To me, the UserControl is where a bulk of the real power in ASP.NET is. It took me a long time to get really used to using them, coming from a Classic ASP background, the loss of Server Side Includes was not easy to get used to. Thankfully, UserControls gave me back a commanding portion of the functionality I needed.

A Better Model / View / Controller
It’s really difficult to implement an MVC pattern in ASP.NET that I can look at and be proud of. Most of the implementations I have seen are very restrictive frameworks that require a lot of adherence to naming conventions, use of ISAPI filters, XML documents that have to be manually maintained as db or class structure changes, problems with Medium / Low Trust environments, and big performance losses.

ASP.NET, I think, had MVC in mind when they developed the paradigm in which they expect pages to operate, but they sure put a boatload of tools in to derail that. Your .aspx page is your view, unfortunately, they tightly coupled a controller (aspx.cs, code-behind) to every view, to the point they are almost synonymous. Then the model, ugh.. you SHOULD be writing a model and a controller to be changing the views, but with WONDERFUL tools like the SqlDataSource, and XmlDataSource they promote bypassing the use of a model or data-layer, and promote addition of business logic in the code-behind. I’m not going to go on about this...

While what you see in my example is certainly not an MVC solution, but it will get you closer to a good and flexible pattern that you can rely on.

UserControls vs. ServerControl

UserControls are not ServerControls and vice-versa. A UserControl is a .ascx(.cs) file and for all shapes and purposes functions very similar to a .aspx(.cs) page. It has a similar life-cycle, and similar properties. The difference is that a ServerControl is typically a small, contained, piece of functionality ... think of a TextBox, or a Button control. ServerControls are usually an element made for a narrowed purpose. A UserControl on the other hand is typically a collection of controls for a specific business purpose. In short, if you extended a TextBox to use specifically for a first name you could put built-in usage and length rules, etc. Great example of a ServerControl. Comparatively, if you wanted a reusable login form for your website, that is something that you would want as a UserControl. UserControls are typically specific to the project or solution, and are very flexible. This is what we will focus on.

Explaining The Code
This would be a good time to download the .ZIP file and get into the code:

The web-app is a basic phonebook, there is no database, all of the entries are stored in a hashtable in Session.

Default.aspx - This is the main view. The UserControls are registered at the top of the .aspx file. In the CodeBehind you will see one method, and that is the EventHandler for one of the UserControls.

/controls - Folder for UserControls

/controls/ViewDataControl.ascx - This control is used for just SHOWING the data, really just contains a gridview. The CodeBehind contains several methods, the public “Refresh” method is the important one because that is exposed in order for the data in the control to be reloaded.

/controls/AddControl.ascx - This is the big one. This UserControl is the form where a person will add a new name to the phonebook. There are a few very important key points to note:
This control contains two properties. They allow abstracted access to the TextBox’s .Text properties. This allows the .ASPX page to read values from the form directly whenever it needs to.
This control contains a public DELEGATE and a public EVENT. This event is fired when the “add” button is pressed. This is how we are able to notify the .ASPX page that something has happened

/App_Code/PhoneBookDataHandler.cs - This class is what actually interacts with the Session data (the hashtable). We break logic like this out from the .ascx.cs and .aspx.cs  files because these functions are universal to the application. the aspx.cs and ascs.cs files SHOULD NOT (not just in this app, either) contain business logic. Those files are there to control the rendering of the page. I said above that I believe these files were also intended to be “controllers” for some perversion of an MVC pattern.

Back to the Default.aspx(.cs) files. - You can probably now see how the Default.aspx page is just the glue that holds the whole thing together. It’s nothing more than a conductor for the UserControls. The UserControls are put on the .aspx page, we then tell the .aspx page that when AddControl.ascx’s “OnEntryAdded” event fires, run the .Refresh() method on ViewDataControl.ascx. ViewDataControl.ascx then grabs the data from Session and puts it in the GridView.

WTF is Business Logic?
Many applications are written for a certain purpose, industry, or business. For this reason the “entities” (like a customer number) adhere universally to certain rules, and those rules have to be validated throughout the application. You do not want that type of logic repeated every time you have to do that, you just want to call a method that does it for you.

You will need to view the code to understand this, most likely. I recommend viewing in this order:

  • Default.aspx
    • Look at the UserControls being registered at the top of the page
    • Look at Line 16 where we tell the OnEntryAdded event to be handled by the method ucAddControl_EntryAdded
  • Default.aspx.cs
    • Look at the ucAddControl_EntryAdded method. All it does is run the .Refresh() method on the ViewData UserControl
  • ViewDataControl.ascx.cs
    • Notice the methods to get data simply ask the PhoneBookDataHandler class for the data.
    • View PhoneBookDataHandler.cs if you want to see the interaction with Session and the HashTable, but it’s not critical to understanding the UserControls.
  • AddControl.ascx
    • Just take a look at what controls are on the page, the text-boxes and buttons. The RequiredFieldsValidators are irrelevant to the tutorial.
  • AddControl.ascx.cs
    • This is the most important file of the entire tutorial.
    • Lines 19 & 20
      • Public properties that allow read-only access to the TextBox’s .Text property
    • Line 26
      • The delegate that defines the signature of the event
    • Line 32
      • The Event that broadcasts when an entry is added
    • Line 43
      • VERY IMPORTANT: This method is what actually fires the event.
    • Line 56
      • Just the button-click event handler. Calls methods that add the data, then fires the event.


I hope this helps you write awesome apps!

-Mike

AwesomeUserControls.zip (7.31 kb)


Posted by: Jerzakie
Posted on: 9/27/2009 at 10:21 PM
Tags: , , , , , ,
Categories: .NET | How To | Techie | UserControl
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (2) | Post RSSRSS comment feed

Learning and Understanding OOP (Object Oriented Programming)

OOP is difficult to understand because it’s an abstract concept that doesn’t really apply to anything within the bounds of reality. That may sound really out there, but it’s software, it’s a bunch of jibberish that a computer uses to take input and do something with it.
I have taught several people OOP and it always comes back to The Rocking Chair. I don’t remember where I picked this up, or if I made it up, but read on and you shall understand the basic concept and use of OOP.

“Everything in [c#, Java, etc] is an object…” you’ve heard it a million times. What does that even mean? Well try to visualize it in reality, what is an object.. well , everything is. A ball, a cow, a rocking chair. Let’s stick with a rocking chair.

Classes,  Objects, and Properties
Let start first with a regular chair. We need to look at what makes a chair a chair, what are the properties of the chair. Color, material, height, width, weight, capacity, does it have armrests, a back?  I will use C# to code all this because I think in C#.
To create an object we need something that defines what that object actually is, we use a class or a struct (structure) to define this. So let’s create a chair.
A quick word on properties and methods.. properties are the adjectives, methods are the verbs. Properties hold the information about an object, methods (or functions, routines, messages) do things, they make things happen.

[Chair.cs]


using System;
using System.Collections.Generic;
using System.Text;

namespace UnderstandingOOP
{
    public class Chair
    {
    }
}

Wow, that was exciting.

Now, let’s add the properties of the chair that we recognized above.

[Chair.cs]

using System;
using System.Collections.Generic;
using System.Text;

namespace UnderstandingOOP
{
    public class Chair
    {
        // these are the private members
        // don't worry about these right now
        // these are used so that we can save values
        // and use them in our code.
        private string _color;
        private string _material;
        private int _height;
        private int _width;
        private double _weight;
        private double _capacity;
        private bool _hasArmrests;
        private bool _hasBackrest;

        // these are properties. This is how we will access/set
        // the information about a Chair when we create it
        // these just protect the private members
        // they restrict and enforce the way that a user
        // can interact with the private members
        public string Color
        {
            get { return this._color; }
            set { this._color = value; }
        }
        public string Material
        {
            get { return this._material; }
            set { this._material = value; }
        }
        public int Height
        {
            get { return this._height; }
            set { this._height = value; }
        }
        public int Width
        {
            get { return this._width; }
            set { this._width = value; }
        }
        public double Weight
        {
            get { return this._weight; }
            set { this._weight = value; }
        }
        public double Capacity
        {
            get { return this._capacity; }
            set { this._capactity = value; }
        }
        public bool HasArmrests
        {
            get { return this._hasArmrests; }
            set { this._hasArmrests = value; }
        }
        public bool HasBackrest
        {
            get { return this._hasBackrest; }
            set { this._hasBackrest = value; }
        }

        // this is a constructor, we need it, don’t worry about it.
        public Chair() { }  

    }
}

Alright. So now we have something that defines what a chair is. So let’s create an object from that definition.

[myAwesomeClass.cs]

using System;
using System.Collections.Generic;
using System.Text;

namespace UnderstandingOOP
{
    public class myAwesomeClass
    {
        // lets pretend this is the entry point of
        // our application... where the application
        // starts executing from.
        public static void Main(string[] args)
        {
            Chair myChair = new Chair();

            // lets assume height and width are in feet,
            // weight is in lbs, and capacity is people
            // that can sit in it.
            myChair.Color = "green";
            myChair.Material = "nerf";
            myChair.Height = 5;
            myChair.Width = 7;
            myChair.Weight = 100;
            myChair.Capacity = 3;
            myChair.HasArmrests = true;
            myChair.HasBackrest = true;
        }
    }
}

Awesome.. so we defined what a chair was, in our class, then we created an object based on that definition. We then set all the properties of that object to what we wanted so that we came out with a big green nerf chair.

Inheritance and Polymorphism (don’t be scared, that word means less than it sounds like)
Now that we have a chair, we can create a derivative of that chair. By using the basic OOP concept of Inheritance we can create another type of chair without having to redefine the underlying structure.. which is a basic chair. Rocking Chair needs to inherit everything that a Chair is and does.

public class RockingChair : Chair {}

TADA. We now have defined that a Rocking Chair is exactly the same as a chair. Using the above example you could now do RockingChair myChair = new RockingChair(); . But that’s not quite accurate is it.. a rocking chair does a lot more than a regular chair … plus is HAS TO have a back.
So we can extend the functionality of a Rocking Chair.

[RockingChair.cs]

using System;
using System.Collections.Generic;
using System.Text;

namespace UnderstandingOOP
{
    public class RockingChair : Chair
    {
        // again.. private members
        // they are here to keep things in sync between the methods
        private bool _isRocking = false;
        private int _rockingSpeed = 0;

        // These are public methods. A method is a verb,
        // it’s an action that your object is going to perform
        // A property is a noun, they don’t DO anything,
        public void BeingRocking()
        { 
            // whatever code would make a chair rock
        }

        public void StopRocking()
        { 
            // whatever code would make a chair stop rocking
        }

        public void RockFaster()
        { 
            if(this._isRocking && this._rockingSpeed <= 10){this._rockingSpeed++;}
        }

        public void RockSlower() {  if(this._isRocking && this._rockingSpeed >= 1){this._rockingSpeed--;} }

 // property is now read only.. so it can’t be changed;
        public bool HasBackrest{get{ return true;}} }
}

So using the example above…
[myAwesomeClass.cs]

using System;
using System.Collections.Generic;
using System.Text;

namespace UnderstandingOOP
{
    public class myAwesomeClass
    {
        // lets pretend this is the entry point of
        // our application... where the application
        // starts executing from.
        public static void Main(string[] args)
        {
            RockingChair myChair = new RockingChair();
            // sweet now we have a RockingChair object!
            // lets make our chair look cool by setting the properties

            // lets assume height and width are in feet,
            // weight is in lbs, and capacity is people
            // that can sit in it.
            myChair.Color = "green";
            myChair.Material = "nerf";
            myChair.Height = 5;
            myChair.Width = 7;
            myChair.Weight = 100;
            myChair.Capacity = 3;
            myChair.HasArmrests = true;
            // myChair.hasBackrest =true; we can’t set this anymore, it’s always true.

            // ok make it rock…
            myChair.BeingRocking();
            myChair.RockFaster();
            // loop it to rock SUPER FAST!
            for (int i = 0; i < 10; i++) { myChair.RockFaster(); }
            //ok.. stop the rocking!
            myChair.RockSlower();
            myChair.StopRocking();

            // methods always have to have () after them, sometimes
            // you will pass parameters in the () like (“myName”, 1,2,3)
            // etc.. but for methods like ours with no parameters, the ()
            // is still required.  Properties DO NOT require () as they
            // are not methods and do not have parameters.
        }
    }
}


Awesome! So.. now you understand… difference in a class and an object, difference in a property and a method, and what they do, and the basic concept of inheritance!
Let’s look at polymorphism. Polymorphism is a complicated way of saying that you can create an instance of a class (object) and assign it to the base object. Weird… yeah.. here’s an example…

Chair myChair = new RockingChair()  ….   Spectacular. Not really. That’s polymorphism…

You could conceivably create an array of Chairs and add all kinds of different chairs to it (Rocking Chairs, bar stools, office chairs, etc) and it would be fine. That’s a really basic use of polymorphism.  Wikipedia has a really good description of it.

Getting good at OOP will help you to write code quickly and reuse code as much as possible, even use code between applications. This was a very basic overview to help you understand what an object is, how it relates to a class, what a method and property is, and what inheritance and polymorphism are.
I hope it helped, email me or comment if you have questions!

All the code for this example is attached and downloadable, it's a VS 2005 project. Enjoy!

OOPChair.zip (21.92 kb)


Posted by: Jerzakie
Posted on: 12/11/2008 at 9:31 AM
Tags: ,
Categories: Development | How To | OOP
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (3) | Post RSSRSS comment feed

Removing a MAC OS Extended Journaled case sensitive (HFS+ Journaled case-sensitive) filesystem without destroying your data.

When I installed Leopard, being a geek, I chose the most complicated FS I had to choose from, the Mac OS Journaled, Case-Sensitive FS. While this seemed like a cool idea at the time, I quickly learned that this is not a preferred option and you should only use it if you have a reason why you need it. Why that would be… no clue. Perhaps it’s that you don’t want Photoshop to work, or that you vehemently despise the THQ children’s game series like Cars or The Incredibles.

On Thursday evening I took it apon myself to go back to a non case sensitive FS. Here is how I did it without destroying all my data.

Things you will need:

•    Clean up your HD so that you have about 55%-60% free space. You can also use an external drive but I am not going to cover that route as I did not have one.
•    Ubuntu Live CD (I used v.8.10 but any version will probably work)
•    Mac OS X CD/DVD (I am using OS 10.5)
•    Boot Camp or DiskUtility.
•    Carbon Copy Cloner
•    Something to do while data is moving. I recommend Mortal Kombat vs. DC or Call of Duty 4, or Call of Duty: World At War
** DISCLAIMER: This worked for me, hopefully it will for you. Back up your data before doing this. We’ll be moving and resizing partitions, that goes south… you’re screwed. **


Preparation:
    Boot with the OS X disk (put it in the drive, hold down C when the screen turns gray), go into Disc Utility (at the top) and run a verify / repair on the physical disk that you need to modify. Reboot.

Creating a usable partition:
First thing to do is create a non case sensitive partition. Open up Disk Utility (DU), click on the PHYSICAL DISK you want to modify. You will know you have clicked a physical disk because you will get the “Partition” option on the right.
Click the partition button. Now you see all of your partitions. The blue part is your data, the white is empty space. Grab the corner of the partition and drag it up until the partition is a little UNDER 50% of the total drive capacity.
Apply and reboot when it’s finished. DU should finish within a couple of minutes, see note below.
NOTE: if you don’t reboot after every partition change DiskUtility will freeze while updating the partition table. I safely killed DU during that freeze many times, but it is a dangerous operation.
Once rebooted, open up DU again, select the physical drive and select the open space you created. Create a new partition under there, you will have to create a case-sensitive, but we’ll fix that in a minute.
    Apply. No need to reboot yet.
Once the partition is created, click on the NEW PARTITION in DU, click on ERARE on the right, select the MAC OS Extended Journaled FS (NOT CASE SENSITIVE) then click on ERASE.
TADA! We have a new partition!

Cloning the Data:
Open up Carbon Copy Cloner, select the source drive as your original partition and the target as the new partition. In the Target box, you should see an indicator that this volume will be bootable. Hooray.
Clone it… now is a good time to go play those videogames! 40Gb of data took my machine about 1:20:00 to copy.

Data done copying …. Ok play more games…

Done now? GOOD!

Open up System Preference and select STARTUP DISK. Click on your NEW PARTITION and close System Preferences.
Open Finder , browse to your new partition go to the Users/[your profile name]/Desktop folder and create a new folder called “HEY IM NEW” or something. I used “WANG” but that’s me. We’re doing this so that we know instantly on reboot that we are booting from the correct volume.
Reboot.

Removing the old partition:
You may have seen a folder with a “?” (missing folder) flash on the screen before the Apple logo, and the system may be booting slowly, that’s ok, we will fix that later, nothing critical.
If you’re booting from the new partition and you see your new folder on your desktop then verify all your data exists on the new partition and blow the old case-sensitive crap away. Open DU, click on the PHYSICAL DISK, click on the ORIGINAL partition (probably at the top) and click the (-) button. GONE!. Apply and close DU.
Don’t start jumping for joy yet. Now it gets weird. For some reason DU and boot camp won’t let you resize a disk unless the free space comes AFTER the resizable partition… see our dilemma now?

Reclaiming your disk space:
Reboot with the Ubuntu CD (do the hold-down C thing again). In Ubuntu, at the top go to System > Administration > Partition Editor.
Click the Move/Resize button. Drag your partition to the beginning of the disk. Hit Apply… go play videogames for another… however long. Mine took another 1:20:00.
Ok, all is done. Notice you can’t resize the partition… sucks. Now we have to set up the drive so that OS X will let us resize the partition. Click on the unpartitioned space and create a new partition, close the LAST OPTION in the filesystem dropdown, which is UNFORMATTED. Apply.
Reboot with the OS X DVD. Once In the OS X DVD, do the VERIFY/REPAIR again on the PHYSICAL DISK. Reboot.
Still getting that weird “?” folder.. no problem, promise we’ll fix it.

Ok back in OS X. I used Boot Camp for this but DU will work too. I RECOMMED USING BOOT CAMP ASSISTANT.
Boot Camp: open Boot Camp Assistant from the Application > Utilities folder. Once you’re in hit continue, you will need to select the option to add/remove Windows partitions. Your next option will be to remove the “Windows “ partition (haha. .we tricked it). Apply the change. TADA!
Disk Utility: You can open DU, click on the physical drive, select your good partition, and drag it to use the full drive.
From the command line you can use “diskutil list” to show your partitions, then use “diskutil resizeVolume [your good partition] 96G “(or however big the drive is).

Fixing the “?” on bootup, the missing folder… whatever it is:
Finally… fixing the stupid “?” folder and slow bootup. Open System Preferences and go into Startup Disk. Click on ANY OTHER VOLUME, close Startup Disk, reopen Startup Disk and select your new, awesome, non-case sensitive volume. Reboot. Tada.

Hope you found the success I did.. my kid can now play Cars and we all know.. when the 3 year old is happy… everyone is happy.

I would like to thank David, Apple, Ubuntu, and the many other who wrote articles on parts of this.


Posted by: Jerzakie
Posted on: 11/22/2008 at 9:08 AM
Tags: , ,
Categories: Apple | How To | Techie
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (6) | Post RSSRSS comment feed