Blog Views


Sunday, October 23, 2011

CSV double quotes

I just had a project that required us to download a file from a vendor and parse the CSV file and place it into an SQL database. Unfortunately, this is an issue in my case as the vendor is senting up the CSV file to have each row encased in double quotes. This is because their description has commas in it. To do this i had two options.


Option 1 was to code all of it by scratch and i found a very nice tutorial on how to do this here Parse CSV file with Double quotes

Option 2 is to use TextFieldParser in the Microsoft.VisualBasic namespace ( Yes you can implement this even in C#). Here is an example using TextFieldParser:

public void Parser()
{
string pathFile = @"C:\TestFolder\TestCatalog.txt";
string line = "";
TextFieldParser fieldParser = null;

try
{
fieldParser = new TextFieldParser(pathFile);
fieldParser.SetDelimiters(",");
string[] array = fieldParser.ReadFields();

while ((line = fieldParser.ReadLine()) != null)
{
MessageBox.Show("This line: " + line);
}

}

catch (Exception ex)
{
MessageBox.Show("Caught Exception: " + ex);
}
finally
{
if (fieldParser != null)
fieldParser.Close();
}

return stringStuff;
}


The above uses the comma as the delimiter because even though they are using the quotes, you still have the carriage return and the end of a line has no comma dictating end of row. For Example: "Gregg","Test","Software"
As you can see above, Software ends the row with no comma after the end double quote.

MVC – The dreaded "Multiple types were found that match the controller named"

So I have spent time on a project involving MVC and have this dreaded issue that many users seem to have with the routing once you change any of the defaults (for instance areas and namespaces). The error is "Multiple types were found that match the controller named"

After a lot of banging my head against the wall, crying and almost throwing my laptop out the window, i came across a web site by John Plummer which mentioned that VS likes to keep your origional executable
from when you first created the project and instead of renaming the exexecutable, it just creates another one. This is one of the usual major issues that this error can created.

Another issue that can cause this is the changing of namespaces and adding areas. If you add the new string to the end of your area registration page like below, it will route your area's to the correct controllers:

new { action = "Index", id = UrlParameter.Optional }, new string[] { "CISE.UserInterface.Controllers"}

Hope this helps others!!

Monday, October 17, 2011

MVC User.Identity.Name failure

So I wanted to make a quick post regarding MVC with new applications (Internet or empty) that got me a few times now, so I can only imagine how many others this has nailed.

Apparently there is a "Known issue" where some MVC applications are not able to get the User.Identity populated with just <authentication ="Windows"/>. The known issue was found under Known MVC issues
In some cases you are also required to add the following line to the <appSettings> section of the web.config:

< add key="autoFormsAuthentication" value="false" />

I hope this helps some folks in their MVC journey!

Reference:
Dan Lewis' Development and Technology Blog

Friday, October 14, 2011

Azure.. Love it or hate it's here

So what is Azure??

This post I thought I'd share what Azure is and what it is good for. Azure has become a new Windows buzz word that is all over the internet with little explanation, so here it goes.

Azure is Microsoft's attempt at taking hardware from the Data center and placing it into the cloud. So what does this mean? This means that the Software Engineer and IT team no longer have to worry about things like SQL server and Windows server set up. This is all done within the cloud. Obviously there are pros and like there is with everything else. It's kind of like when host providers started to host websites. Same thing. The process of building the web server ( memory, hard drive space and such), as well as getting upload bandwidth speeds to handle the amount of traffic you hope to get is placed in the hands of the hosting provider. Providers such as go daddy or network solutions. Azure takes the same hosting concepts and applies them to software / database development. An excellent place to start to discover the benefits to this new Microsoft platform is this website: Learn about Azure


Who is this good for and why?


Azure is good for a wide range of people for a variety of reasons. Even if you are a bigger company, you still can utilize the power of Azure with the power of lack of knowledge so to speak. You software development team can spend less time worrying about the set up of SQL or setting up Windows server and more time on the project at hand. On the downside this also gives the company less control and thus can cause issues where there are complicated scenarios with things like permissions and such.
A lot of this in the end will depend on how well Microsoft support is and how the handle companies needs. I'm sure it will no doubt be support based on a big fat monetary scale.

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

ASP versus PHP The Big Dog challenge

Introduction

So I get asked a lot what is better PHP or ASP.NET (oddly enough not as much about Java as I would think). I always find myself stopping and having to think to myself, how does one answer a question that is much more based on the business need and resources available (monetary and employee). For instance if you were to say that you were a start up company with $5,000 to your name 2 employees one of which has done some web design (mostly html). I would say PHP all the way. For several reasons that I will get into later.

Now if on the other hand, you were a medium sized company with some Windows machines, your own Domain etc... I would lean more towards ASP.NET. I'm not at all saying that a huge corporation cannot benefit from PHP by any means. I believe parts if not all of Amazon are PHP based. This article is much less a debate and more of a giving my own experiences and knowledge and putting it out there for everyone to make their own decisions because in the end, it soley depends on your particular scenario.


ASP.NET ( Bill Gates and beyond!)

So if there is one thing I can assure before going any further is that if you know ASP as ASP Classic, this is nowhere near what ASP.NET is. ASP.NET combines web techlogies such as AJAX, HTML, Javascript and CSS and attempts to make a nice platform within Visual Studio for .NET programmers to transition into designing robust Web applications. Notice how I said "attempted to". As you may have read in my other post about ASP.NET versus MVC For the love of MVC, Web Forms uses the drag and drop controls concept to add things like tables and text boxes to your web application.

While a great idea, the concept of compiling your code after every little change instead of using an interpreter like PHP where individual files can be uploaded without effecting anyone else can becomes problematic when multiple developers are maintaining a website. Another draw back to web controls is that they cause quite a bit of overhead as well as unexpected tag IDs especially when using Master files.


This by no stretch of the imagination means that ASP.NET is horrible never use it. It has it's uses and one of which is it is extremely good at RAD (Rapid Application Development). You don't have to spend months learning 3 languages (HTML, PHP, and CSS) in order to build a simple Website with a contact form. ASP.NET is also still great for development teams that comprise mostly of software engineers/developers. It is a very easy transition into the exciting world of Web within minimum previous knowledge.

Another part of ASP.NET that has taken off by storm is MVC which is actually a design model developed in the 70's, but has since been adopted by Microsoft as well as other languages such as Ruby on Rails. This adoption has allowed Microsoft to bring the HTML and JavaScript control back into the developers hands, but still allow .NET platform compatibility. For more information on MVC, see the above post.


So is it worth it?

ASP.NET in some cases is able to some things much better than PHP. One of which is it's interaction with the Windows machine, auto authentication via IE and easily create hooks into Active Directory. Again, not that PHP can't do some of these things, but it is easier with ASP.NET because it is made to handle. This also should set off a spark in your head that asks the question "Is our business a Microsoft house?" If the answer is yes, more often than not, ASP.NET is the way to go. If you are more of a Mac or Linux house, then PHP might be your better option.


Cost

Although ASP.NET itself does not cost anything, you really must run ASP.NET on a Windows server which cost money for licensing. PHP on the other hand is open sourced, so it's free for anyone to use.


PHP ( The way of the open source)

PHP has been around a long time now and has definitely come a long way, but I can't say that I would call it a RAD language. These days business want to see things out yesterday. The ways that you learn in school that everything needs to be done a certain way and takes time blah blah blah can be thrown out the window. RAD development is the way of the future and won't get any slower. PHP definitely takes someone with a certain mindset and C or C+ background wouldn't hurt. Although they are trying to add the OOB functionality and Systems such as CakePHP and Joomla try to create API's for it, it still isn't OOB and can get awkward trying to get it to be.

With that said though, you can make things pretty robust with PHP, it just takes time and experience (and patience). Another big negative I find with PHP is it really has no IDE that has the kind of IntelliSense and productivity tools that Visual Studio has. None that I have seen even comes close.


There you have it!

The above is based on my experiences with the 2 languages and please take it for what it is, an opinion. Nothing more, nothing less. I tried to make it as unbiased as I could although, I feel like I gave ASP.NET more props because it is what I currently use. I have spent many years on PHP though and have to say that if given the funds to spend on the hardware, the new MVC framework along with Visual Studio is what I would choose. I feel like productivity goes so much smoother and strongly typed is just awesomeness with whipped cream on top!

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.