Archive for category 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.

Advertisements

, , ,

Leave a comment

ASP.Net MVC : Diving a little more deep

As we further continue our journey of understanding the ASP.net MVC better , a great way to learn any framework is to examine the source code. Fortunately the source code is available for ASP.net MVC framework to download or browse over the web at CodePlex ( I have provided the link to Source code below) . Currently they have the latest Version 3 RTM code available to look at. In my case this part came much later because I had an aggressive timeline and there was not much time to learn. However giving the framework source code a thorough look will make you very comfortable with the use of the framework itself because you are able to analyse what happens behind the scenes very well. Not only that, having gone under the hood gives a lot more command over how to effectively achieve the required results without breaking into too much sweat and frustration. A huge productivity gain if you put in some upfront time diving deeper in understanding of design.

A question I have seen a lot in discussion forums being asked is how come ASP.Net MVC does not implement the Observer pattern with Models and Views? In my last post I have mentioned that MVC is a strong use case of Observer pattern in certain scenarios. MVC was conceived for Desktop applications and it is much simpler to have several instances of Views of the same Model and update all the Views when a Model state changes by either one of the Views or some other means. However in the web paradigm generally a View instance is not even available in real time after the View object finishes rendering the HTML. The Model is more passive in nature unlike in an Observer pattern where the Model notifies the Subscriber Views of changes. The Model simply supplies the data that View queries and presents. This does not in any way violate the MVC principle because the MVC pattern’s essential goal is to separate or loosely couple the Model from the Presentation or the View.

Hence to achieve MVC in web applications a variation of basic MVC was developed called Model 2. In Model 2 the request from the Client Browser is passed to a Controller. In case of ASP.Net MVC this is a central Controller called Front Controller which simply takes a Http request, parses it to create the right Controller instance to execute the right Action. To see this implementation you can look at the MvcHandler.cs in source which acts as the Front Controller –

1) ProcessRequest function of the handler parses the request to create the right controller instance.

2) The ControllerBase.cs has the definition for the Execute() function that in turn executes the request. The Controller.cs derives from ControllerBase implementing the IController interface which has the contract for Execute() method. All controllers derive from the Controller.cs.  This method gets called from the ProcessRequest of MvcHandler.

3 ) The actual invocation of action  is done by the InvokeAction method of the ControllerActionInvoker.cs class. The InvokeAction returns an ActionResult type which is an abstract representation of the type of the View that gets returned.

The intention of outlining above is to give you a way to trace the sequence of flow in the Source Code of how the Model 2 was achieved. This completes the understanding of how the request went through the pipeline and completed. I would not like include the actual code listings here: it is a good exercise to have a look at the code yourself and trace out the pipeline.

There are several references to get a better understanding of the Model 2 itself. I suggest to go though Model 2 on Page. 549 of the Head First Design Patterns book. There is a great article by Dino Esposito in MSDN Magazine, which illustrates Model 2 very well here.

ASP.NET MVC 3 RTM Source code on CodePlex .

 

2 Comments

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