May 2008 - Posts

In my last post, I have mentioned of creating Flickr app with Asp.net MVC. In recent update I have modified it with Asp.net MVC Preview 3.

You can find a general reference about the project here. But in this post, I will say, what are the changes due to the new release and where to start especially.

In previous release of ASP.net MVC you had RenderView, which lets you render your UI right from the controller and controller classes are with void return type, now with new release this is slightly changed. In case of the FLickrViewer app, I have a PhotoController, where I did the following changes.

public ActionResult Tags(string name, int? page)
{
    ViewData["Title"] = name;

    PhotoData photoData = new PhotoData();
    
    // ........ more code here  ......

    return View(photoData);
}

As you can see, the data is passed as ActionResult by a View routine, in this way it becomes more TDD friendly, where I don't need to mock HttpContext to compare results from Test class. From UI layer. Also, it lets you have different sets of results in ViewData. For example, i want to populate View's Title property from ViewDataDictionary and get the tags from its Model.

Therefore, I can do the following to have dynamic browser title

<title> Photos for tag - <%= ViewData["Title"] %> </title>

And, then access the Model property to get PhotoData.

<% 
    if (ViewData.Model != null)
    {
        foreach (FlickrViewer.Web.Objects.PopularTag tag in ViewData.Model)
        {
            // .. actual code
        }
    }%>

Pretty cool, in terms of separating result and UI data. :-).  Another good update is the routing helpers. We can now ignore particular URL extensions to be sent to controllers by IgnoreRoutes and can use the new easy construct called MapRoute for mappping URLs to controllers.

In global.asax, we can register and ignore routes like

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute("Detail", "Photo.mvc/Detail/{photoId}", 
                     new { controller = "Photo", action = "Detail" });
}

These are few of loads of new additions to MVC Preview 3. In coming posts, I will tell more about how to use Ajax with MVC to construct master-detail UI, but you can check it out easily by digging into the source.

The source can be divided into four parts

    1. UI - that uses Asp.net Ajax and JS and Html to render things out.
    2. PhotoController - prepares the data for rendering.
    3. PhotoModel -> talks with Flickr using LINQ.Flickr.
    4. A separate test project that uses NUNIT and Rhino mock to test controller.

All together it makes out a MVC project :-). Again, get the copy of the source from www.codeplex.com/flickrviewer and live URL is http://flickrmvc.net.

Thanks

kick it on DotNetKicks.com

I have flushed out a little project at Codeplex called "Flickr Xplorer". Its a Flickr mesh up that lets you search(user, tag, text), jump into user photos, see popular and latest stream and moreover lets you browse the whole Flickr in hacked url way (url routing easy and rocking). The application is made on Asp.net MVC preview 3  and I have used my LINQ.Flickr to communicate with Flickr. The project is an early stage, I will update with new features when possible and how you ask. You can use it as you like , host it to your server to make it a personal dashboard for your taken photos or use it for fast hand on for Asp.net MVC , mocking and of course how to use LINQ.Flickr API :-)

image

you can try out the demo here http://www.flickrXplorer.net/ (sometimes service may be unavailable due to update pardon me for that). Currently, App is tested under IE 6 & 7, Firefox 2.0+, will update for other browsers as well.

The location for the project  : www.codeplex.com/flickrXplorer.

Finally, have fun the new open source Flickr app and ping me if you have any suggestion to make it more interesting.

Enjoy!!

Updated on 29th May 2008 - Asp.net MVC preview 3

Updated on 28th June 2008 - Restructured, renamed and added social features.

Updated on Sep 29 2008 - Update to MVC 5, Please check for the newest updates in source tab and all are pushed to live.

kick it on DotNetKicks.com

In this post, I will show how you can use Typemock to fake out complex HTTP POST like uploading photo in Flickr server. The example which will be shown here, gives a pretty much generic idea of faking out HTTP calls and gain access to the response stream for comparing result with original content.I have used, N-Unit along with Typemock which run thorough TMockRunner.exe to perform the mock test.

To get started, let's see what is really cooking in PhotoRepository.Upload in LINQ.Flickr which we are going to mock.

image

To focus strictly on mocking,  I have removed non-mockable parts and blocked out sections to be mocked. These include the following

1. Mock calls to Authenticate.

2. Get a mocked signature.

3. Mock the HttpRequest object

4. Get reference of the Stream so that Stream.Write  writes to our desired media rather to the original request stream.

5. Create a Fake WebResponse object and marry it with Request.GetResponse

6. Get reference of the response stream  that will be filled with data from local resource.

Staring off every mock should have a MockManager.init(). we can further check if it is initialized or not by MockManager.Isinitialized.I have moved the common mock statements to a separate class for LINQ.Flickr which I call FakeFlickrReposity. It takes in the type of repository and the returned object and it can be constructed by a simple using block as it implements IDisposable.

using (FakeFlickrRepository<PhotoRepository, Photo> photoAddMock = 
new FakeFlickrRepository<PhotoRepository, Photo>()) 
{ 
   ... 
   ... 
}

Inside it creates a Mock in its constructor of type PhotoRepository, the method of which(Also, its base) to be mocked.

public FakeFlickrRepository()
{
    _mockRepository = MockManager.Mock<T>(Constructor.NotMocked);
}

The Constructor.NotMocked, means that the initialization codes for PhotoRepository wont be skipped. In this case creating the interface mapping to endpoint, getting keys, paths, etc.Now, going into the test class of LINQ.Flickr for uploading photo, I have first created the Photo object that has stream reference of a file from local resource.

//[Following block used in the full codeview at the bottom]
Stream photoRes = 
GetResourceStream("Linq.Flickr.Test.blank.gif"); 
Photo photo = 
new Photo { Title = "Flickr logo", FileName = "Test.Mock",
File = photoRes, ViewMode = ViewMode.Public };

Next, called the following

photoAddMock.MockAuthenticateCall(true, Permission.Delete);
photoAddMock.MockSignatureCall();

Inside of MockAuthenticateCalls looks like

_mockRepository.
ExpectAndReturn("Authenticate", authToken)
.Args(validate, permission.ToString());

And inside of MockSignatureCall

_mockRepository.ExpectAndReturn("GetSignature", signature);

ExpectAndReturn , as it looks like, traps a method call and returns the result right away rather going to the original flow.

 

photoAddMock.FakeHttpRequestObject(fileStream);

The above line is for faking HTTPWebRequest and get a stream reference out of it. Stepping in which we can see

_httpRequestMock = MockManager.Mock(typeof(HttpWebRequest)); A 
_httpRequestMock.ExpectSet("ContentType"); B
_httpRequestMock.ExpectAndReturn("GetRequestStream", stream); C

A => Creates a mock of Type HttpWebRequest, B=> Sets an expectation of ContentType set, setting ContentType with mocked request will give a null reference as it depends on internal dictionary to do processing. C=> Sets an expection of GetRequestStream  and returns the reference to the stream provided from outside.

photoAddMock.FakeWebResponse_GetResponse();

 

This will create a MockObject of type WebResponse class and will return a dummy instance of it when HttpRequest.GetResponse will be invoked.

_webResponseMock = MockManager.MockObject<WebResponse>();
_httpRequestMock.ExpectAndReturn("GetResponse", _webResponseMock.Object);

_httpRequestMock  is the private Mock variable that we created earlier. We also need to fill up the Response stream with proper Flickr response to be parsed by the LINQ.Flcikr system properly , in case of successful upload. To archive that, we need to marry our local resource stream to the WebResponse.GetResponStream

_webResponseMock.
ExpectAndReturn("GetResponseStream", GetResourceStream(resource));
_webResponseMock.ExpectCall("Close");

Finally, we need to make sure that response stream is closed properly. This is pretty much all which is to be mocked, the rest part of the code is to read the stream where the uploaded content is saved (pointed by us) and compare it with original photo binary.

The part of the code is pasted here for more info of what I just said.

image

This whole implementation can be found at LINQ.Flickr.Test under PhotoMockTest :: DoPhotoUploadAndDeleteTest, which can be downloaded from www.codeplex.com/linqflickr. Have a nice day!!

kick it on DotNetKicks.com

Just released another version of LINQ.Flickr. The release is out with several bug fixes, code optimization, new feature and overall mocking support. I have used Typemock for the unit test of the product. In coming posts, I will show how powerful mock can be in faking routine like upload photo. But, you can dig it right away, if you go by the release page and download a copy of the product. Truly speaking, testing was never fun for serviced API till mock engine is at my hand.

The release is not all about re-factoring and mocking , but now you can query, add , delete photo comment , query people and popular tags and do more that are mentioned in the release page.

Now, doing complex query is even more fun. lets take this.

var query = from photo in _context.Photos
where photo.Id == photoId && photo.PhotoSize == PhotoSize.Medium
select new FlickrPhoto
{
    Id = photo.Id,
    Description = photo.Description,
    Title = photo.Title,
    Url = photo.Url,
    User = photo.User,
    Comments = ((from comment in _context.Photos.Comments
                 where comment.PhotoId == photoId
                 select new PhotoComment
                 {
                     Author = comment.Author,
                     AuthorName = comment.AuthorName,
                     PermaLink = comment.PermaLink,
                     PhotoId = comment.PhotoId,
                     Text = comment.Text,
                 }).ToList<PhotoComment>()),
    Tags = photo.PhotoTags.Select(tag => tag.Title).ToArray<string>()
};
FlickrPhoto newPhoto = query.Single();

The query is about getting the photo info for a specific photo id and I have now combined it with tags, comments to make it more useful. Also, few posts back, I have mentioned about using a RestToCollecitonBuilder  to build an object on REST response,  it is in action in this release as well.

Finally, don't forget the link and it's www.codeplex.com/linqflickr . In the end, this project is not about querying Flickr and getting photo out of it, but it could be a great learning tool for Mocking, for building custom LINQ provider (with LinqExtender) and other things that you might need to know like, how to define a service endpoint by interface.

Enjoy :-)

kick it on DotNetKicks.com
More Posts