Infragistics ASP.NET controls

ASP.NET MVC Basics: How to create a HtmlHelper

 ASP.NET MVC Basics: How to create a HtmlHelper Hello! And welcome to another tutorial on  This is the first tutorial in a series on ASP.NET MVC development.  This first installment will cover how to create an HtmlHelper.   What is ASP.NET MVC? I apologize if I'm stating the obvious, however, this is a tutorial on the basics so I'm approaching the tutorial with the assumption that the reader has no knowledge of ASP.NET, MVC, or ASP.NET MVC.  I'm sure you noticed that I made three references to the technology.  That's because ASP.NET MVC is more than one technology.  First we have ASP.NET, which is a server side web development technology created by Microsoft that utilizes the .NET framework.  Simply put, ASP.NET allows you to write dynamic web pages in .NET language of your choice (C#, VB.NET, etc..).  ASP.NET is an open source technology and it can be developed using the .NET framework or the Mono runtime.  You can find all sorts of wonderful information at . ASP.NET comes in two "flavors".  ASP.NET WebForms which is the original flavor, and ASP.NET MVC.  ASP.NET MVC is made up of two concepts.  First and foremost there is the MVC design pattern.  The MVC or Model-View-Controller design pattern was introduced by Trygve Reenskaug in the 1970's.  The design pattern has also be explained by Martin Fowler in his wonderful book on design patterns called Patterns of Enterprise Application Architecture . The idea behind the MVC pattern is that you have data that you wish to display (Model), you have a presentation layer in which you wish to display your Model (View), and you have a class that handles the interaction between the View and the Model (controller).  The MVC design pattern is an excellent example of a design with proper separation of concerns.  Applications that implement the MVC design pattern are generally loosely coupled, and easy to test (unit testing).  In ASP.NET MVC, the View is a web page, the model can be any class that holds data that you want to display in the View, and a controller class. Now that I've explained ASP.NET and MVC, I'll now explain ASP.NET MVC.  You see, not only is ASP.NET MVC an implementation of the Model-View-Controller design pattern, it's also a framework built by Microsoft to support the implementation of the MVC design pattern.  You will see as you begin working with MVC that the framework is a large part of what makes ASP.NET MVC what it is.  You could implement ASP.NET MVC without the framwork, however, I don't recommend it.  The framework will create controller's for you, create Views that are bound to a strongly typed model of your choice, and much more.  Using the ASP.NET MVC framework, you can create a basic CRUD web application in a very short amount of time. I hope that this gives you a nice overview of the ASP.NET MVC framework and design pattern. HtmlHelper: What they are and how to create them I'll explain HtmlHelpers by taking you through implementing one..  We'll start by firing up Visual Studio and create a new ASP.NET MVC 4 project (note: I'm using VS 2012, however, if you have an earlier version installed, simply choose whichever ASP.NET MVC version that you have available to you.  If you don't have any ASP.NET MVC templates, you can use the Web platform installer to install ASP.NET MVC on your system.       The next dialog allows you to choose which type of ASP.NET MVC application that you'd like to create.  We will pick an Internet Application, with the Razor View engine and a unit testing project as shown below.     Now click OK and your project will be created for you.  The ASP.NET MVC Framework will create a lot of boiler plate code behind the scenes.  This includes "Forms based Authentication" in the web.config file as well as an AccountController which is a controller to handle authentication to the site.  There is also a default controller called HomeController. We are going to create an html helper that creates an HTML table.  This is merely an example and is not particularly useful, however, it will show you how to create and use an HTML Helper.  An HTML helper is nothing more than an extension method which returns a string of HTML.  Here is the official definition of an extension method from MSDN: Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. Creating the HtmlHelper  Create a folder called "Helpers" in your solution.  In the folder, create a static class called TableExtensions.cs .  The class will look like this: TableExtensions.cs using System; using System.Text; using System.Web.Mvc; namespace HtmlHelpers.Helpers { public static class TableExtensions { public static MvcHtmlString Table(this HtmlHelper helper, string id, string name, int rows, int columns) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); if(string.IsNullOrEmpty("name")) throw new ArgumentNullException("name"); if (rows <= 0) throw new IndexOutOfRangeException(); if (columns <= 0) throw new IndexOutOfRangeException(); StringBuilder tableBuilder = new StringBuilder(); tableBuilder.Append(string.Format("<table id=\"{0}\" name=\"{1}\">", id, name)); for (int rowCounter = 0; rowCounter < rows; rowCounter++) { tableBuilder.Append("<tr>"); for (int columnCounter = 0; columnCounter < columns; columnCounter++) { tableBuilder.Append("<td>"); tableBuilder.Append(rowCounter.ToString()); tableBuilder.Append("</td>"); } tableBuilder.Append("</tr>"); } tableBuilder.Append("</table>"); return new MvcHtmlString(tableBuilder.ToString()); } } } As you can see, we've created a static class and a static method. The the first method parameter is  this HtmlHelper helperThis is where the magic happens. This allows us to use the method from the View like all other HTML helpers.The other methods specify the number of rows and columns that should be built in the HTML table.Here is an example of how to use the helper: @using HtmlHelpers.Helpers; @{ ViewBag.Title = "Index"; } <h2>Index</h2> @Html.Table("myTable", "myTableName", 4, 4)The output looks like this: And there you have it folks.  I hope you enjoyed this tutorial.  If you have any questions please don't hesitate to leave a comment. Thanks for reading.

RapidMiner tutorial: How to explore correlations in your data to discover the relevance of attributes

What is correlation? From wikipedia In statistics, dependence refers to any statistical relationship between two random variables or two sets of data. Correlation refers to any of a broad class of statistical relationships involving dependence. In laymans terms, correlation is a relationships between data attributes.  For a quick refresher, in data mining, a dataset is made up of different attributes.  We use these attributes to classify or predict a label.  Some attributes have more "meaning" or influence over the label's value.  As you can imagine, if you can determine the influence that specific attributes have over your data, you are in a better position to build a classification model because you will know which attributes you should focus on when building your model.   In this example, I will use the Titanic datamining challenge dataset.  This post will not uncover any information that is not readily available in the tutorial posted on Here are two screenshots.  The first screenshot will show you some statistics about the dataset.  The second screenshot will show a sample of the data. Meta data view of the Titanic data mining challenge Training dataset A data view of the dataset The correlation matrix First start by importing the Titanic training dataset into RapidMiner.  You can use Read From CSV, Read From Excel, or Read from Database to achieve this step.  Next, search for the "Correlation Matrix" operator and drag it onto the process surface.  Connect the Titanic training dataset output port to the Correlation Matrix operator's input example port.  Your process should look like this.   Now run the process and observe the output. You are presented with several different result views.  The first view will be the Correlation Matrix Attribute Weights view.  The Attribute weights view displays the "weight" of each attribute.  The purpose of this tutorial is to explain a different view of the Correlation matrix.  Click on the Correlation Matrix view.  This is a matrix that shows the Correlation Coefficients which is a measure of the strength of the relationship between our attributes.  An easy way to get started with the Correlation matrix is to notice that when an attribute intersects with itself, you have a dark blue cell with the value of 1 which represents the strongest possible value.  This is because any attribute matched with itself is a perfect correlation.  A correlation coefficient value can be positive or negative.  A negative value does not necessarily mean there is less of a relationship between the values represented.  The larger the coefficient in either direction represents a strong relationship between those two attributes.  If we look at the matrix and follow along the top row (survived) we will see the attributes that have the strongest correlation with the label in which we are trying to predict. Just as the tutorial specifies, the attributes with the strongest correlation with the label (survived) are sex(0.295), pclass(0.115), and fare(0.66)  Remember that the value as well as the color will help you to visually identify the stronger correlation between attributes. If you are working with a classification problem, I'm sure you can see how valuable the correlation matrix can be in showing you the relationships between your label and attributes.  Such insights let can provide a great start on where to focus your attention when building your classification model. Thanks for reading and keep your eyes open for my next tutorial! 

Machine Learning tutorial: How to create a decision tree in RapidMiner using the Titanic passenger data set

    Greetings! And welcome to another wam bam, thank you ma'am, mind blowing, flex showing, machine learning tutorial here at! This tutorial is based on a machine learning toolkit called RapidMiner by RapidI.  RapidMiner is a full featured Java based open source machine learning toolkit with support for all of the popular machine learning algorithms used in data analytics today.  The library supports supports the following machine learning algorithms (to name a few): k-NN Naive Bayes (kernel) Decision Tree (Weight-based, Multiway) Decision Stump Random Tree Random Forest Neural Networks Perception Linear Regression Polynomial Regression Vector Linear Regression Gaussian Process Support Vector Machine (Linear, Evolutionary, PSO) Additive Regression Relative Regression k-Means (kernel, fast) And much much more!! Excited yet?  I thought so! How to create a decision tree using RapidMiner When I first ran across screen shots of RapidMiner online, I thought to myself, "Oh boy.. I wonder how much this is going to cost...".  The UI looked so amazing.  It's like Visual Studio for Data Mining and Machine learning!  Much to my surprise, I found out that the application is open source and free! Here is a quote from the RapidMiner site: RapidMiner is unquestionably the world-leading open-source system for data mining. It is available as a stand-alone application for data analysis and as a data mining engine for the integration into own products. Thousands of applications of RapidMiner in more than 40 countries give their users a competitive edge. I've been trying some machine learning "challenges" recently to sharpen my skills as a data scientist, and I decided to use RapidMiner to tackle the machine learning challenge called "Titanic: Machine Learning from Disaster" .  The data set is a CSV file that contains information on many of the passengers of the infamous Titanic voyage.  The goal of the challenge is to take one CSV file containing training data (the training data contains all attributes as well as the label Survived) and a testing data file containing only the attributes (no Survived label) and to predict the Survived label of the testing set based on the training set. Warning: Although I'm not going to provide the complete solution to this challenge, I warn you, if you are working on this challenge, then you should probably stop reading this tutorial.  I do provide some insights into the survival data found in the training data set.  It's best to try to work the challenge out on your own.  After all, we learn by TRYING, FAILING, TRYING AGAIN, THEN SUCCEEDING.  I'd also like to say that I'm going to do my very best to go easy on the THEORY of this post..  I know that some of my readers like to get straight to the action :)  You have been warned..   Why a decision tree? A decision tree model is a great way to visualize a data set to determine which attributes of a data set influenced a particular classification (label).  A decision tree looks like a tree with branches, flipped upside down..  Perhaps a (cheesy) image will illustrate..   After you are finished laughing at my drawing, we may proceed.......  OK In my example, imagine that we have a data set that has data that is related to lifestyle and heart disease.  Each row has a person, their sex, age, Smoker (y/n), Diet (good/poor), and a label Risk (Less Risk/More Risk).  The data indicates that the biggest influence on Risk turns out to be the Smoker attribute.  Smoker becomes the first branch in our tree.  For Smokers, the next influencial attribute happens to be Age, however, for non smokers, the data indicates that their diet has a bigger influence on the risk.  The tree will branch into two different nodes until the classification os reached or the maximum "depth" that we establish is reached.  So as you can see, a decision tree can be a great way to visualize how a decision is derived based on the attributes in your data. RapidMiner and data modeling Ready to see how easy it is to create a prediction model using RapidMiner?  I thought so! Create a new process When you are working in RapidMiner, your project is known as a process.  So we will start by running RapidMiner and creating a new process.     The version of RapidMiner used in this tutorial is version 5.3.  Once the application is open, you will be presented with the following start screen.  From this screen you will click on New Process  You are presented with the main user interface for RapidMiner.  One of the most compelling aspects of Rapidminer is it's ease of use and intuitive user interface.  The basic flow of this process is as follows: Import your test and training data from CSV files into your RapidMiner repository.  This can be found in the repository menu under Import CSV file Once your data has been imported into your repository, the datasets can be dragged onto your process surface for you to apply operators You will add your training data to the process Next, you will add your testing data to the process Search the operators for Decision Tree and add the operator In order to use your training data to generate a prediction on your testing data using the Decision Tree model, we will add an "Apply Model" operator to the process.  This operator has an input that you will associate with the output model of your Decision Tree operator.  There is also an input that takes "unlearned" data from the output of your testing dataset. You will attach the outputs of Apply Model to the results connectors on the right side of the process surface. Once you have designed your model, RapidMiner will show you any problems with your process and will offer "Quick fixes" if they exists that you can double click to resolve.   Once all problems have been resolved, you can run your process and you will see the results that you wired up to the results side of the process surface. Here are screenshots of the entire process for your review  Empty Process   Add the training data from the repository by dragging and dropping the dataset that you imported from your CSV file   Repeat the process and add the testing data underneath the training data Now you can search in the operators window for Decision Tree operator.  Add it to your process. The way that you associate the inputs and outputs of operators and data sets is by clicking on the output of one item and connecting it by clicking on the input of another item.  Here we are connecting the output of the training dataset to the input of the Decision Tree operator.   Next we will add the Apply model operator Then we will create the appropriate connections for the model Observe the quick fixes in the problems window at the bottom.. you can double click the quick fixes to resolve the issues. You will be prompted to make a simple decision regarding the problem that was detected.  Once you resolve one problem, other problems may appear.  be sure to resolve all problems so that you can run your process. Here is the process after resolving all problems.   Next, I select the decision tree operator and I adjust the following parameters: Maximum Depth: change from 20 to 5. check both boxes to make sure that the tree is not "pruned". Once this has been done, you can Run your process and observe the results.  Since we connected both the model as well as the labeled result to the output connectors of the process, we are presented with a visual display of our Decision Tree (model) as well as the Test data set with the prediction applied. (Decision Tree Model)   (The example test result set with the predictions applied)   As you can see, RapidMiner makes complex data analysis and machine learning tasks extremely easy with very little effort. This concludes my tutorial on creating Decision Trees in RapidMiner. Until next time,   Buddy James  

WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.

    WPF Validation for mere mortals I've recently jumped on the WPF bandwagon and I've fallen in love with this technology.  XAML is a fascinating animal indeed.  The declarative nature of the language leaves much to be explored.  There are many ways to solve the same problem.  On my quest for knowledge, I've been researching the intrinsic validation functionality of WPF.  Unfortunately, most every example I've ran across on blog posts and have been a bit too complex for my blood.  I find often that you need learn other subjects before you can begin to understand how the validation works.  Don't get me wrong, the examples are really nice.  However, when I'm learning something, I want a straight to the point example of the topic at hand.  It's with this idea in mind that I bring you a simple tutorial on WPF validation. I will be illustrating this example using the MVVM (Model-View-ViewModel) Pattern.   Click here to download the entire source (74.08 kb)  Consider the following code  The view MainWindow.xaml <Window x:Class="ExceptionValidation.MainWindow" xmlns="" xmlns:x="" xmlns:viewModel="clr-namespace:ExceptionValidation" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> <TextBlock>Enter total amount</TextBlock> <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> <Binding.ValidationRules> <ExceptionValidationRule></ExceptionValidationRule> </Binding.ValidationRules> </Binding> </TextBox> <Button Content="Button" Height="28" Name="button1" Width="84" /> </StackPanel> </Window>     The viewmodel MainWindowViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { class MainWindowViewModel : ObservableCollection<Product> { public MainWindowViewModel() { Add(new Product { TotalAmount = 3 }); } } }   The model Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace ExceptionValidation { public class Product : INotifyPropertyChanged , IDataErrorInfo { public event PropertyChangedEventHandler PropertyChanged; private int _totalAmount = 5; public int TotalAmount { get { return _totalAmount; } set { _totalAmount = value; OnPropertyChanged("TotalAmount"); } } public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } } } A brief introduction to MVVM  As you can see, we have a XAML view, a viewmodel class, and a model.  The Model is a representation of an object's data.  In this instance, we are modeling a Product.  The viewmodel is an object that handles the change notification between properties in the model and elements on the view.  XAML properties, events, and bindings have the ability to tunnel (down the tree) as well as bubble (up the tree).   Binding the ViewModel to the view. In order to bind the ViewModel to the view, we must make it accessible to the view via XAML.  To accomplish this, we first have to import the namespace in which the viewmodel exists.  Examine the following code. xmlns:viewModel="clr-namespace:ExceptionValidation" Here is the equivalent in c# using ExceptionValidation; Once we've imported the namespace for use, we then need to define our MainWindowViewModel as a Resource of the current window. <Window.Resources> <viewModel:MainWindowViewModel x:Key="mainViewModel"/> </Window.Resources> This allows us to declare an instance of the MainWindowViewModel class by using the associated Key "mainViewModel". Binding the ViewModel As stated before the ViewModel acts as a "go between" for the View and the Model.  In order for the view model to communicate with our XAML view, we will bind the ViewModel to the StackPanel's DataContext. <StackPanel DataContext="{Binding Source={StaticResource mainViewModel }}"> XAML's ability to tunnel properties down from parent to child will allow each element inside the stack panel to make use of the DataContext binding that we've just setup using the Window resource's key mainViewModel. ObservableCollection<T> The viewmodel inherits from ObservableCollection<Product>.  The ObservableCollection<T> generic class represents a collection that can be utilized by WPF databinding.  This is possible because the ObservableCollection<T> class raises an event when items are added and removed from the collection. INotifyPropertyChanged The model implements the INotifyPropertyChanged interface.  This interface provides an event in which to fire any time a model property is changed.  This event notifies the bound element in the view that the property has changed. public event PropertyChangedEventHandler PropertyChanged;   public void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (PropertyChanged != null) { handler(this, new PropertyChangedEventArgs(info)); } }   IDataErrorInfo The magic behind WPF validation comes from the implementation of the IDataErrrorInfo interface.  The interface implements the following members.  The this[columnName] indexer implements the logic of the validation rule. //Not used by WPF public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { if (columnName == "TotalAmount") { bool valid = true; if (_totalAmount > 10) { valid = false; } if (!valid) { return "The total amount cannot exceed 10!"; } } return null; } } The following XAML code binds the TotalAmount property of the first Product in the viewmodel's internal collection to the Text property of the TextBox element.  The ValidatesOnDataErrors attribute tells the textbox binding to raise an event when there is a valadation error.  When the event is raised, the bound element's template is changed to a new visual style that places a Red rectangle around the border of the TextBox.  When the error is corrected, the original template is restored.  Binding.ValidatesOnDataErrors <TextBox Width="200" Name="txtTotalAmount" > <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True"> </Binding> </TextBox> In the provided example, if you enter a value greater than 10 into the text box and tab out of the textbox, you will see that an error is raised causing the red outline around the textbox.  If you correct the error by replacing the value with a number less than 10, the red outline will disappear. This concludes my tutorial on WPF validation.  This is the very basic of validation methods.  There are many other advanced tutorials on the subject.  My next tutorial will involve utilizing custom validation attributes from the System.ComponentModel namespace to handle WPF view validation. Thanks for reading! ~/Buddy James kick it on  

About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (, a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List