Blog Views


Showing posts with label asp.net versus mvc. Show all posts
Showing posts with label asp.net versus mvc. Show all posts

Thursday, October 13, 2011

Silverlight AutoComplete box (The real deal!!)

Silverlight Introduction

So I have spent quite a bit of time with Silverlight and one thing I really like about it is that if you don't come from a lot of .NET experience, you get a taste of every aspect of the framework. You may not be able to do "everything" WPF or Windows Forms can do, but you get a lot of experience in it all. Th reason for this is although Silverlight is rich and a great patform, it is client side only. NO SERVER END. Web Services are used as the way to communicate with either the web project or any other tool outside of Silverlight (database for example)


Purpose for the Autocomplete boxes??

In my articles I like to explain somewhere a real world explaination of what a particular tool would be used for. In this case, the Autocomplete tool is most often used in two scenarios

The first use case is when your application has a fixed set of things you wish to have the user choose from and don't wish to use a dropdown either because you have too many options for a user to sift through or your users really like the keyboard and want to utilize it to be more efficient. Using AutoComplete boxes allows you to do just that by popping up data values based on what you type in the box (such as looking up someones name).

The second use case for using a AutoComplete box (remember I'm sure there are tons more, these are just 2 common ones) is for search engines. Notice how Google has had for a long time now, the ability to autocomplete your question before you finish? In it's simplest form, this is an autocomplete box that uses a list of words and phrases to match what you are typing on the fly. This is possible using AJAX web methods.

AJAX ( Asynchronous JavaScript and XML)

There is a very special group of web methods called AJAX which allow for a better user experience by making asynchronous calls to the server and instead of the browser waiting for a response from the server before allowing the user to continue interacting with it, the browser continues on it's merry way with the user until it gets a returned CallBack from the Event that was origionally created. I will go into AJAX more in future blogs, but it has definetly matured quite a but since the late 90's.


No more Background.. Lets get the show on the Road

So now that you have some background in what AutoComplete boxes are, what AJAX is, what limits Silverlight etc... Lets get coding. So first lets create a simple person class in the Silverlight Application. If you want to seperate concerns, you can easily do this by placing it in an Entities folder. The Person class should look similar to this:

 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Department { get; set; }

        public override string ToString()
        {
            return FirstName;
        }
    }

}


Overriding the ToString method allows you to instead of getting the object type, get the First name popup in the autocomplete control

Now lets build ourselves a little repository database (really just a list)

 public class PersonRepository
    {
        Person _person = new Person();
        

        #region DUMMY DATABASE

        public List<Person> GetPersonList()
        {
            List<Person> personList = new List<Person>();

            personList.Add(new Person
            {
                FirstName = "Joe",
                LastName = "Shmo",
                Department = "IT"
            });

            personList.Add(new Person
            {
                FirstName = "Gregg",
                LastName = "Tyler",
                Department = "Software Engineer"
            });

            personList.Add(new Person
            {
                FirstName = "Gary",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Geoff",
                LastName = "Style",
                Department = "Accounting"
            });


            personList.Add(new Person
            {
                FirstName = "Michael",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Matthew",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Mark",
                LastName = "Style",
                Department = "Accounting"
            });


            personList.Add(new Person
            {
                FirstName = "Rebeccca",
                LastName = "Smith",
                Department = "Human Resources"
            });

            personList.Add(new Person
            {
                FirstName = "Richard",
                LastName = "Style",
                Department = "Accounting"
            });

            personList.Add(new Person
            {
                FirstName = "Robert",
                LastName = "Style",
                Department = "Accounting"
            });

            return personList;
        }


        #endregion
    }

Now lets go into the MainPage.xaml file and add a AutoComplete Box from the ToolBox. This will add the proper references and should create a sdk tag type via this line of code at the top of the screen under the UserControl tag sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk". The below code does several things, first, I create two Stack Panels that enacpsulate the AutoComplete box as well as the textbox that will populate with the selected Item.

 <StackPanel Background="LightGray">

            <StackPanel x:Name="AutoRoot"  Orientation="Horizontal">

                <sdk:AutoCompleteBox  x:Name="AutoBox" Width="200">
                    <sdk:AutoCompleteBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Path=FirstName}"/>
                            </StackPanel>

                        </DataTemplate>
                    </sdk:AutoCompleteBox.ItemTemplate>
                </sdk:AutoCompleteBox>
               </StackPanel>
        </StackPanel>


You will notice that the TextBlock that corresponds to the AutocompleteBox has it's Text property being bound to the FirstName of the Person object. This is important because we are going to do outr autocompltion based on first name. This is all encapsulated in what is known as a Datatemplate.

The final part is the code behind for the MainPage.

 public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            // Create repository and get DB list
            PersonRepository personRepository = new PersonRepository();
            List personList = personRepository.GetPersonList();

            // Bind list to AutoComplete box
            this.AutoBox.ItemsSource = personList;

            #region Set Filters for Autocomplete Direct Reports

            this.AutoBox.ItemFilter = ((search, item) =>
            {

                Person person = item as Person;

                if (personList.Count() != 0)
                {
                    string filter = search;
                    return (person.FirstName.Contains(filter));
                }
                return false;
            });

        }
            #endregion

    }

The first part acesses the repository and gets the list from our database and binds it to the AutoComplete controls ItemSourcw. Then using the AutoCompletes ItemFilter property and lambda expression, You are able to filter inside the list by using the Contains property in the string object as shown below.

return (person.FirstName.Contains(filter));

Hope everyone enjoyed this tutorial. There have been very few tutorials on this and i thought it was important to get this out there.

References

  • http://en.wikipedia.org/wiki/AJAX

Tuesday, October 11, 2011

ASP.NET versus MVC Compare the Big Web Guns

Introduction


So I have seen a lot of ASP.NET Web Forms versus MVC blogs out there and I thought I'd put my two sense in as well. I used to be a big PHP and MySQL programmer, mainly out of lack of funds in other jobs and I have to say, when I first went to Web Forms, it was interesting to say the least. I can understand that the Web Forms concept came out of a need to allow Windows Forms programmers the ability to quickly adapt themselves into web world. Unfortunately, this came at many prices such as speed and browser compatibility. This post will try to explain both from a theoretical and practical side instead of learning each.

ASP.NET Web Forms


What is this Web Forms and where did it come from?

Web Forms has been around since January 2001 and was a replacement for ASP Classic by Microsoft programmers who needed a way to design web sites without much HTML or JavaScript knowledge. This new approach also allowed any back-end code (also know as code behind) to be written in .NET C# or VB. This and the dragging and dropping of controls helped in the transition from application to web platforms. Although a nice thought, there have been quite a few major pitfalls that have caused ASP.NET to be hard to work with.

Microsoft go wrong?? Never!!

ASP.NET has had some hard times through the years, but even now have some major issues that have kept it on the back burner when it comes to very serious Web Developers who need cross browser compatibility and fast performance. Where this comes out the most is when trying to do things such as pull client side code into the aspx file or styling your code. Master files were created to make template files that all other web application files within a project can use. Using Master files cause odd ID tags for controls to populate into the scrambled characters such as ct10034343. This makes it very difficult in JavaScript to access the DOM for things such as validation and CSS styling. Now you might be thinking, well just do the validation in the code behind. This will work, but it will cause performance lag. Depending on the calculation required to validate the form, there may be major lag times!

The other major thing that was introduced with ASP.NET is stateful applications inside a stateless protocol (HTTP). What does this all mean? It means that ASP.NET has the ability via ViewState to keep the state of the various .NET Controls as well as states of various strings and objects you may need to retain (such as paging or sorting). Although again a great idea, the ViewState has been used improperly by the majority of the developers whom use it. Most developers use that to store massive amounts of data or objects and this is sent to the Client EACH REFRESH! As you can obviously tell, this can bring performance down in a hurry...

What does this mean? No more Web Forms?

In my opinion. No. I think Web Forms is here to stay for a bit if not indefinite. This is for several reasons. One of those reasons is that it is still a fantastic tool for RAD applications (Rapid Application Development). When you need a simple form or newsletter tool, Web Forms is still great. This is true especially for the application programmer unfamiliar with web technologies such as HTML, CSS and the XHTML a stricter version of HTML.

Another reason is that Web Forms have been around for a long time and not everyone will just one day say "Lets migrate to MVC, screw Web Forms!". This will not happen for many reasons, some of which are resources and knowledge-base. For the application programmers who wrote the Web Forms, there will be a larger learning curve that will have to be addressed.


ASP.NET MVC


What is an MVC??

MVC (aka Model-View-Control) is a design model / architecture that was originally developed in the late 70's to create a separation of concerns. In it's simplest form, this means that all the different aspects of an application (Meaning Data Access layer - Calling Code - UI) are logically separated into different folders and classes according to the MVC architecture. The architecture has since been migrated into the .NET Framework and labeled ASP.NET MVC. It's ideas have taken the web world by storm as it is very hard to implement this architecture ( if even possible, I have never tried myself) in the Web Form model. MVC also allows for excellent Unit testing. i will not go into detail here, but thought it should be mentioned.

MVC is also a stateless as apposed to stateful like Web Forms. Stateless means that each time you refresh the page or POST (not POSTBACK), you loose the state of the page and anything that relates to it. There are things to help with this like ViewData which unlike ViewState lives on the server, not the client computer.

Model aka Data Access Layer aka prince (just kidding)

In this case the DAL is the Model (somewhat.. I'll explain better in other posts where we are discussing more technical aspects of MVC ). The Model is used to handle interfaces and repositories that hold all the "code behind" and data calls whether it be database, lists, server files etc. This separates data access layer logic and business logic ( validation for example) from UI logic via the controller.


View (User Interface or HTML)

Through the View MVC displays W3C compliant (assuming you code it that way) HTML formatted code. This makes it much more browser compliant (even IPad and IPhone). There is no hidden HTML characters in the ID's or extra gibberish that only IE understands. MVC also does a lot of object binding between the View, Model Controller making it very easy to use strongly data typed objects throughout your code. This allows you to easily utilize Visual Studio's awesome Intellisense.


Controllers (The BabbleFish)

The Calling Code or the translator (babble fish if you like Douglas Adams :) ) is known as the Controller. This handles the requests between the view and the model. This allows you to "almost" completely remove any Business or Data logic from the View logic. This allows you to not only focus on one section at a time, but also guarantee what your HTML and styles will output like and in turn better browser compatibility.


So what does it all mean?

So whats this all mean? Is MVC the god among men of web development? Will Web Forms fizzle out and never grace our presence ever again? Not likely. As i mentioned above, Web Forms are still widely used and is still an excellent RAD development web application framework. It is also a great alternative for windows application programmers who know nothing about web development and don't really wish to know the specifics in detail.

If on the other hand, you are looking to have a fast growing enriched site with web applications that provides clear HTML standard output, better performance / faster load times and separation of concerns, you may want to take a closer look at MVC. Its core is still .NET, so a lot of the code is the same which is great, but there are some newer syntax in the MVC 2 and 3 releases that you will need to learn and understand, but if you develop in .NET currently it should be too bad. The bigger learning curve to overcome will be understanding how things like POST and Refreshing works.

I hope this has been informative and you view my other posts.