Posts Tagged ASP.Net MVC

App mediator for mobile photo upload with ASP.Net MVC 4

The emergence of social networking sites and mobile phone usage explosion has created a need for providing photo , video uploads via mobile devices . Up until now this was very difficult , because Safari did not allow uploading of photos from a mobile device into a website . However things are opening up with Safari allowing photo uploads to a website and HTML5 media capture facilities maturing in a manner where it’s possible to pick photo and video from a native directory and upload to the website. Then there is Phone Gap which allows tapping the native api via Javascript , another option that can be used to upload photos to a website.

However , with the both of these options yet , there is a learning curve as well as writing code to crop images , arrange them on the canvas or the UI before and after upload. If you have an immediate need to put something together with least amount of code without having to worry about cropping the images with code or a layout for tiling the images , an in between approach is available. A best user experience is always recommended , however it is subjective based on the context of usage.

Here the user installs an app only the first time there is a need to upload and following times just one click takes care of uploads to the websites for a seamless experience. There are pros and cons to this approach however . I will discuss both.

First let me demonstrate how the code looks like when we use ASP.Net MVC 4 for the web.

As a first step you will need to go to the AurigmaUp website and get a Free License Key for a domain you have registered .

Then in your html, here is how a link to AurigmaUp looks like  ( Razor and JQuery Mobile Syntax ).

@if(!String.IsNullOrEmpty( Model.AuthCookie) )
{            
    <a data-role="button" data-theme="a" data-iconpos="right" id="aurLink" href="aurup:?uploadUrl=http://yourdomain/upload/photo&redirectUrl=http://yourdomain/upload/gallery&redirectDelay=60&returnUrl=http://yourdomain/upload/gallery&uploadTimeOut=10000&licenseKey=licensekey&minimumVersion=1.4&multiSelection=true&imageMode=mode=thumbnail,autorotate=true,size=600,resizeQuality=high,jpegQuality=100;mode=thumbnail,size=50,resizeQuality=high,jpegQuality=100;mode=thumbnail,size=150,resizeQuality=high,jpegQuality=100&debugMode=true&minimumVersion=1.4&cookies=AuthCookie=@Model.AuthCookie"> Upload Photos</a>     
}
else
{
    <div>Authentication error: cannot upload photos , please contact administrator</div>
}

As you see above the code is simple enough to declare just a hyperlink , which sends a request to an AurigmaUp App .Everything is configured through this link ,the Upload URL , the image sizes , the URL to redirect to after upload , the license and authentication . AurigmaUp uses cookies to authenticate the request : so in this case , I am passing back my Forms authentication cookie via my Model . This works fine , error free. A Javascript code provides a mechanism to download the IPhone / Android app –

<script type="text/javascript">

(function() {
    var ua = navigator.userAgent;
    var link = document.getElementById("downloadAppLink");
    if (ua.indexOf("Android") > -1) {
        link.setAttribute("href", "https://play.google.com/store/apps/details?id=com.aurigma.aurigmauploader");
        link.style.display = "";
    } else if (ua.indexOf("iPhone") > -1 || ua.indexOf("iPad") > -1) {
        link.setAttribute("href", "http://itunes.apple.com/us/app/aurigma-up/id432611633");
        link.style.display = "";
    }
})();

</script>

Here is the server side controller code that demonstrates how cookie is passed via the Model:

 public ActionResult Photo()
 {
            _logMessages.Write("Into Get Aurigma Upload");

            UploadAlbum ua = new UploadAlbum();
            ua = SetUpAuthCookieForAurigma(ua);
            return View(ua);            
 }
private UploadAlbum SetUpAuthCookieForAurigma(UploadAlbum ua)
{
            HttpCookie authCookie = HttpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

            if (authCookie != null)
            {
                _logMessages.Write(authCookie.Value);
                ua.AuthCookie = authCookie.Value;
            }
            else
            {
                _logMessages.Write("cookie in post does not exist");
                //Redirect to error page
            }

            return ua;
}

The Uploads work error free , without any issues no matter how many photos you upload and they are reasonably fast.

For those of you ,  who are 100% bent on providing an integrated non clunky user experience ,  this is not the best solution . Although, this is very simple to configure with HTML code , the server side code will have some debugging challenges , because once the request is submitted to the AurigmaUp App, you lose control because there is no way to debug the App in development mode. You are going to have to survive by logging to persistence mediums.  However once you have a good logging mechanism in place , it works pretty smoothly.

In the end I would have to conclude with mixed feelings . If you have a site where the user activity is predominantly media uploads , then for the ultimate integrated experience  is better to go with HTML5 or PhoneGap type of API . However if you want to quickly provide the user also the capability to upload photos via mobile devices as an enhancement to the user experience , this is certainly worth considering because it is extremely easy to code and functions correctly , quickly for uploads.

I have not provided full source code – if any question feel free to contact directly or through comments.

, , ,

Leave a comment

Forms Authentication and Membership : Still going strong

ASP.net and .Net framework have come a long way.  Asp.net 1.0 went through a major change with the introduction of ASP.Net 2.0 having several boiler plate features which did not exist in the 1.0 version. Providers were a major component of these features with Membership and Roles added on top of Forms Authentication which was introduced with the 1.x version itself. Since then the combination of Forms authentication with Membership and Role Providers are a strong and proven mechanism that can be used to take care of Authentication as well as Authorization needs of a .Net web application. Together they can be used to Validate a User with Membership and then Create / Manage a Authentication ticket with Forms Authentication.

I just recently started an ASP.Net MVC3 project with .Net framework 4. The MVC3 project template gives you a choice to add all the basic code to implement your security via Forms Authentication / Membership . I have had 4 successful projects with Forms / Membership – 2 were even integrated with SSO. I had all the reason to go for it because I felt very comfortable with it. I must say it took me only at most an hour to configure everything the way I wanted it to work. I did not have to struggle with anything or learn any new technology tricks. I loved that feeling , because every step of the way otherwise you end up learning something new with every version that’s introduced. I don’t consider that a bad thing , however as much as changing technologies are good to have,  stable features give you the comfort and speed required to get the project going. ASP.Net MVC has kept all the goodness except that now the security functions are called via Controller / Action methods.

Forms Authentication and Membership Timeline


Together they can be used to Validate a User with Membership and Create / Manage a Authentication ticket with Forms Authentication.

ASP.Net MVC has kept all the goodness except that now the security functions are called via Controller / Action methods.


If you are using Single Sign On with some kind of federated database , it’s really easy to integrate the two together as well. Just make sure that the credentials which exist in the federated database also exist in the ASP.Net membership database. Once the credentials are authenticated in the SSO database , you take the same credentials and validate them against the Membership database and assign Roles accordingly if you have them. The only catch is if the SSO system creates an authentication ticket that has it’s own expiry , you need to make sure you are signed out of the SSO system when the user signs out of forms authentication system. Forms authentication system creates it’s own ticket – which has it’s own expiry.

Not that the Forms authentication / Membership system is suitable for all systems – several larger corporations have their own home grown authentication and authorization systems. Their custom needs may be complicated enough not be able to use Forms Authentication / Membership . However for all small and mid sized applications, where a reliable boiler plate security mechanism is required , the Forms Authentication / Membership works without any major issues. It is also comforting to see that it is stable enough for Microsoft to have kept it the same way without having the need to make many changes through version 4. Just thought I should discuss this via blog because good to see something stable and strong in an ever changing world of technology.

, ,

Leave a comment

ASP.Net MVC : coming up to speed

In my last blog post I talked about how I chanced upon ASP.Net  MVC at my last project and my thoughts on whether a development group should consider it as a design choice for their future projects. In fact few months have passed since I wrote the last blog post, and ASP.Net MVC has taken another leap with MVC 3. From Microsoft’s side there is big push of course and I do see a lot of adoption from development groups in different organizations. There is a learning curve that I see most groups are going through and it can be hard or easy depending on the background that you come from your previous development tasks.

The best way to get started with ASP.Net MVC is if you already are not familiar with MVC as a pattern, familiarize yourself with it.  There are several websites that discuss it as a pattern : in the pattern world, it’s more of a ‘framework pattern’ as opposed to a ‘basic pattern’ from the Gang of Four patterns. So based on your level of understanding of patterns, start with Basic patterns aka Gof4 and then understand it as an aggregate pattern of different basic patterns. MVC itself is acheived by different pattern proponents and architects as an aggregate of different types of patterns: like in Head First Design Patterns book, the authors acheive MVC by combining the Observer , Strategy and the Composite pattern.  You will observe after your readings that several implementations of MVC are a strong use case of Observer pattern where Views subscribe to changes in the Model – also of Composite patten for the View itself.  In the web model though , the use case of Observer pattern may not exist due to the stateless nature of the View. So ASP.Net MVC is one variation of the basic MVC pattern adapted to web paradigm.

It’s the most important step to get as clear an understanding of MVC under the hood from a patterns perspective: this gives a you a much clearer perception of Model, Controller and View , their interaction. You could jump start into it by creating a “Hello World” application in Visual Studio 2008 , 2010 – however it will become very difficult as you go further in accomplishing all your programming functions because the underlying concepts are not clear, especially for those who are used to ASP.Net web forms programming.

Another important start is to pick up a good book , by now there is MVC 3 , however while I am writing this , few good books are out on MVC 2. The ones I read are books by Steve Sanderson and Jeffery Palermo , famous authors. Both are great books in their own regard: Sandeson’s book covers all basics extensively – so read that as your first basic book and Jeffery Palermo’s book covers several advanced topics , like dependency injection , different unit testing methods in a lot more detail. Both will go a long way in getting your foot in the ground , and being well prepared with your project work. I have listed at the end of the blog all the books I read to get up to speed and they helped me a lot. It is good to get few copies of books like this for the whole team and everybody reads it. Of course , there is ton of websites and without a doubt you should follow Scott Gu, Scott Hanselman, Phil Haack and Stack Overflow. The books combined with the websites will give you an understanding of the ASP.Net MVC framework which is written on top of MVC design pattern.

Another new concept that may get thrown at you with ASP.Net MVC is Routing , the ‘RESTful’ way of doing things – it’s undoubtedly a strong concept and you must be very familiar with it from day one. ‘REST’ is meant to be the way Web programming is done – as you progress you will see how important it is for you to be very clear on some concepts like the HTTP methods of GET and POST . WIKIPEDIA itself has some great information on REST , HTTP Methods etc.  As far as Routing itself is concerned the the two books I mentioned above do cover it extensively as to how to achieve it with ASP.Net MVC framework.

Here is a list of all the links for References:

Gang Of Four Patterns Book

Head First Design Patterns

Steve Sanderson’s MVC Pro Book

Jeffery Palermo’s MVC Book

Scott Guthrie

Scott Hanselman

Phil Haack

WIKIPEDIA On REST

Good Luck With MVC !

, , , , ,

Leave a comment

ASP.Net : To MVC or not to MVC ?

I was recently faced with a situation at work to execute a ASP.Net MVC project to release. The design choice was not mine , however due to certain constraints I was asked to finish it to deployment. We have released a 1.0 version of the project now and in retrospect , if I had started the design from scratch , would I have picked the ASP.Net MVC as opposed to WebForms  which is well established and mature ?. I probably would not have considering the proven rapid time to productivity of WebForms especially when we had several deadlines looming over our heads . However, having already a project with MVC in production I realize the merits of it enough to say, the decision to do it in MVC was not a bad one at all, although we had several pitfalls on the way. Will I use MVC for my next ASP.Net project ? Most probably , yes.

I am sure several shops are faced with this dilemma lately as far as starting a new ASP.Net project….MVC or not? As usual  ‘it depends’ on the context of your organization and it’s development practices so far , however if I were to make a Utopian decision on this problem I would say Yes, MVC is the right choice to get started with the project. This clearly states that MVC is a superior design pattern and ASP.Net MVC has more to offer that can go a long way with your company’s ASP.Net / web development strategy.

Typically I noticed that MVC is a natural choice for developers coming from Java world having to do ASP.Net …so is with Ruby On Rails developers. Microsoft surely succeeded in wooing the Java and ROR folks with their ASP.Net MVC strategy. For those of you who have been hardcore ‘WebFormers’ it’s undoubtedly worth your time because we all know that a complex project developed in WebForms can become a debug nightmare with PostBack and WebForm event life cycle. And there are several other shortcomings…ViewState , Testability , not being able to separate the concerns. A high level of competency in architecture is required in design of moderate to complex WebForms projects  demanding solid upfront design effort that can cost time and money.

Asp.Net MVC manages to alleviate a lot of these due to it’s inherent clear Separation Of Concerns thanks to MVC itself , a known pattern in the Software Architecture world. The framework itself does a lot of groundwork for you as long as you adhere to some good  programming practices as you go along your development cycle. Basically , you  jump start into a good design without having to put in a lot of work upfront. Right there I think , you gained cost and time.

So, to sum it up – for medium to large sized projects it’s undoubtedly a better choice. For smaller projects or prototypes where time-to-market or quick overview could be  the primary concern , Webforms is a better choice since it offers greater productivity. For larger projects , time-to-market is normally one of the concerns , however other predominant concerns are  maintainability , extensibility , testability and performance. All of this , MVC will address and  improve for your projects across the board.

The current ASP.Net MVC 2.0 system has it’s demerits as well, biggest one at this point being , it’s lack of maturity. Version 2 is out there, however it lacks the Rapid development components of WebForms like the Server controls. This can make developers frustrated several times since it slows you down to a great degree. However the brighter side is once you get a hang of how to use HtmlHelpers and enhance them you will appreciate the degree of control and customization it offers as opposed to server controls which could end up becoming sometimes black boxes in difficult situations. The web world is making progress out there with MVCContrib which offers some controls for MVC and Microsoft soon will be coming out with Version 3 which has a lot of enhancements along with a new View Engine called Razor.

There sure is a learning curve for most WebFormers  trying this framework for the first time , more so if you are not familiar with MVC design pattern. So, how do you get your team ready for this new seemingly ‘Rewarding’ technology in a seamless and streamlined fashion? It’s a huge paradigm shift and you want to make sure the team does it step by step without feeling bogged down by it.

In the next blog , I will give you my two cents of how I think the development team can go about learning this framework and making a transition to this technology.

, , , , ,

1 Comment