image
If you listen to podcast, you will find that Internet is full of it. I do enjoy listening how people talk about things in podcast. I generally listen to hanselminutes , dotnetrocks (Carl Franklin) and few obscure ones.  All the episodes of hanselminutes  are available in Itunes. Generally I download the latest episode sync into my ipod touch then as my wife busy cooking, I put in the phones in my ear and try to give out some hand, though I remember only to comment and watch but often help preparing salads :-).  So, last February  before coming from Kuala Lumpur , I bought an IPod touch. Me and my wife both enjoy  listening to it, I watched  all the Mix 08 videos on it, I do use it to update my twitter status when I am at a coffee shop using the WIFI. Finally, browsing Internet with it a real fun,  usually with the tap and zoom feature.

Anyway, its nice to listen to podcasts and talk shows which has become a part of daily lives. Starting from nowhere it is now a source for good knowledge.  As recently, I have come to know a cool xaml tool named Kaxaml and Git source control from Linus Torvalds himself. Also, it is nice hear from dotnetrocks about how Phill Hack get into Microsoft or the great Scott Guthrie wrote MVC framework while flying on an airplane. 

While I have busy time at work through out the day. I do enjoy listening to all these and more , when I need a thoughtful relax and looking out to ideas for implementing or enhancing my own personal projects.

Now coming back to Ipod, its really a cool device starting from browsing while you are at starbucks , listening to music or watching TV shows when you are on the go. But, one thing for sure it has Itunes bundled with it, so beware of your wallet. One good thing about Zune (Yes the only Zune) that you can sync contents wirelessly and sometimes listen to FM radio , that this great device is not able to provide yet. Also, to be honest I didn't like costly money oriented (or object oriented you say) upgrades that apple offers, it really gives me pain. Yes, this is good device but the dark tails with it goes directly to your wallet. It could have been a more popular device if there were some generosity shown by apple for its content management, DRM rules and pricing.  But still with BOSE accessories (sound-dock) , its a fun device you don't want to miss :-).

That's it that came to my mind for now. Also, I want to draw the finish line before the post becomes a soap opera :-) . As it sounds it is a non-technical post , here I haven't talked about LINQ, using LinqExtender toolkit, MVC or anything like it. But do throw me your opinion.

When you are planning to host your asp.net MVC application under IIS7 integrated mode environment. There are few easy tweaks that can make your application or starter kit work right out of the box but also can save a lot of your time finding things out.

You might see a Http 404 page if default document is not configured properly. One way of getting this around by using the following in global.asax during the App_BeginRequest

if (Context.Request.FilePath == "/") Context.RewritePath("Default.aspx");

But rater doing code changes, another easy way of achieving it by adding the following snippet in your web.config

<defaultDocument enabled="true">
  <files>
    <clear />
    <add value="Default.aspx" />
  </files>
</defaultDocument>

Relative urls like one that is shown below

<img alt="Flickr Logo" src="/Views/Shared/images/flickr_logo.gif"" />

This will result in invalid output when the app is hosted under IIS7 and if it is hosted under a virtual directory  for example, http://localhost/flickrweb. It will produce url  http://localhost/Views/Shared/images/flickr_logo.gif rather the original http://localhost/ flickrweb/Views/Shared/images/flickr_logo.gif. To overcome this we would need to use Page.ResolveClientUrl  which makes the above snippet look like

<img alt="Flickr Logo"
src="<%= Page.ResolveClientUrl("~/Views/Shared/images/flickr_logo.gif") %>"/>

Now, while hosting our MVC app to a shared hosting server whether or not they provide us a wwwlogs folder, we can easily write down a custom HttpLog module for IIS7 integrated mode (blessing of integrated pipeline). On the Init method of the HttpModule we can add the following event mapping under which we can write our custom logging logic.

context.LogRequest +=new EventHandler(context_LogRequest);

For, each http request this will be fired for IIS7 integrated mode and  we need to add the mapping for it in the following way.

<add name="<ModuleName>" preCondition="integratedMode" 
type="<namespace>, <assembly>"/>

We might be using CSS handlers  that will be compressing the contents and combine cross browser CSS intelligently, like one I have posted few months back

http://weblogs.asp.net/mehfuzh/archive/2008/01/25/keep-your-css-files-clean-with-a-tiny-httphandler.aspx

Make sure you have added the mapping for this as well properly under system.webserver node for integrated mode

<add name="<handlerName>" path="<path>.axd" verb="*"
 type="<namespace>" 
 requireAccess="Script" preCondition="integratedMode" />

And of course add it with Page.ResolveClient url to make it an absolute work.

<link rel="Stylesheet"
 href="<%= Page.ResolveClientUrl("~/CSSHander.axd") %>" type="text/css" />

Now, hosting extension less web app is all beauty but how if someone tries to overload your server by manually hitting /Views/Controller/SomePage.aspx. We can make sure of it that no .aspx file is ever processed by manual hits, by putting an extra web.config file under /Views folder of you ASP.NET MVC application and adding this tiny line inside it

<add name="InvalidAspxHandler" path="*.aspx" verb="*" preCondition="integratedMode" 
type="System.Web.HttpNotFoundHandler, System.Web, Version=2.0.0.0, Culture=neutral
, PublicKeyToken=b03f5f7f11d50a3a"/>

Now, all the config changes I have shown here are to be added under system.webserver node to work with IIS7 integrated mode. The typical webserver node for IIS7 integrated mode looks like

<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules runAllManagedModulesForAllRequests="true" />
  <handlers/>
</system.webServer>

Enjoy!!

kick it on DotNetKicks.com

This is the first of posts that I am making to show out the things you can do with ASP.NET MVC. Also, it shows what I have done while building FlickrXplorer. I am bit lazy to write one article for it, so I thought rather to start it here.

In this post, I will show how you can implement a master-detail layout that invokes MVC controller to process its data and uses Ajax to do it in a non postback manner.

If you have looked though FlickrXplorer, you must have noticed that every list of images is tied with a detail view in a way that if user performs any action on the list ("click") , the detail view is updated accordingly.

Let's see the action flow below

image

It is almost clear that when you select an image it calls a Controller method or an Action method to be more precise. In this case, let's say that it is /Photo/Detail/112233. To map this a simple line in global.asax follows

routes.MapRoute("Detail", "Photo/Detail/{photoId}",
 new { controller = "Photo", action = "Detail" });

 

This will result in the call of PhotoController.Detail, when user hits the above url. Inside detail view its pretty simple.

[FilterResponse]
public ActionResult Detail(string photoId)
{
    try
    {
        PhotoDetail detail = model.GetPhoto(photoId); 
        return View(detail);
    }
    catch (Exception ex)
    {
        return View("Error", 
                    new ControllerException
      { ErrorUrl = HttpContext.Request.RawUrl, Message = ex.Message });
    }
}

As, expected it calls the model to get the photo and returns the ViewResult. Here, I haven't done any content related processing rather made a ViewPage named Detail.aspx which the MVC framework calls. By default, MVC framework looks for the ViewPage or ViewControl with name equals to the Action name, but View has other overrides that let me call other ViewPage/ViewControl as well. This is what done above when any error occurs, which calls Shared/Error.aspx. It is to be noted that if you have multiple controller and you want to access the same view from different controller, then you need to place it in the Shared folder, which will make it accessible by all controllers.

In the snippet, we also see that there is a FilterResponse attribute that will cache the response for same parameter set once the first call is made. FlickrResponse is inherited from MVC.ActionFilterAttribute attribute that provides a way to do some custom actions like caching and compression of http content.

So far, I have mapped the url and added the action method. Now, its time to get the result and show them in UI but I don't want any postbacks or redirects for it. So, I have used a callback model that did the work for me.

function renderContent(elementId, loadElementId, url, callback) {
    var element = $get(elementId);
    $get(loadElementId).style.display = "block";

    // Create the WebRequest object.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(url);
    // Set the request verb.
    wRequest.set_httpVerb("GET");
    // Set the Completed event handler, 
    // for processing return data
    wRequest.add_completed(function(sender, eventArgs) 
    {
        if (sender.get_responseAvailable()) 
        {
            element.innerHTML = sender.get_responseData();
            $get(loadElementId).style.display = "none";
            
            if (typeof callback != 'undefined')
                callback();
            
        }
    });
    // Make the request.
    wRequest.invoke();
}

 

Here, we see that renderContent takes in the Id of the element that will contain the rendered content and loading element that will be visible while the content is being processed. Optionally, we can pass in a parameter-less void callback which can be invoked after the content is processed. In that case, we might like to start the loading of comments after we have rendered the detail page. This renderContent is invoked while a user selects a photo from the list, this is a bit generic method which can be used for any callback scenarios. Therefore, for rendering photo detail, I wrapped it around so that it takes only a photoId.

function renderDeail(photoId, ignoreHash) {
    if (ignoreHash == 0) {
        if (window.location.hash == '') {
            // take the default one 
            window.location.hash = photoId;
        }
        else {
            photoId = getPhotoIdFromHash();
        }
    }
    else {
        window.location.hash = photoId;
    }
    var url = '<%= Html.ActionUrl("Photo", "Detail", new { photoId = "{0}" }) %>';
    url = String.format(unescape(url), photoId);
    renderContent("detailView", "loadingView", url, loadComments);
}

renderDetail  takes a photoId and ignoreHash := true/false. Inside, it uses Html.ActionUrl to process the url and then formats it with photoId and finally calls the renderContent. Html.ActionUrl is an extension method which is coded by me, the original is Html.ActionLink. So please dont get confused :-). I could have passed the url by hand but using ActionUrl  it creates the url on basis of the route mapping in global.asax. Also, for Photo controller if I change the url from /photo/detail/id to /p/detail/id, then I don't have to go everywhere in order to change the references.

Finally, while loading photo from url, I use window.hash to navigate to the selected photo, which is updated when a photo is clicked to show and thus, I have the master-detail layout yet url copy-paste facility.

That's it for now, I leave it on to the reader to explore it more in Codeplex. Also, hope that the introduction helps. Please note that some of the features like 2nd step loading of comments will be supported from 1.2 release (please check it out), so the JS might slightly differ to what is shown here.

Check it live at flickrmvc.net - send me feedbacks and updates.

kick it on DotNetKicks.com

In my previous post, I have said that using LINQ query instead of SortedDictionary not only could be useful , elegant but also less processor intensive. In this post, I will show you a real comparison between the same the method but one with SortedDictionary and other with LINQ orderby query. I wrote a simple console application that mimics the action of GetSignature in LINQ.Flickr. Here, I will focus only on the sorting part that's why I removed the hashing and initialization of the method.

So, lets assume there are 10 url pairs that we need to sort for getting the signature. So, we need to create an array of 8 items and the processing method inserts another 2 (api_key and method name). Finally, when I run the two routines and took a snapshot from jetbrain's dottrace , I saw the following

comparisonInit 

Now, you can see that there are two methods TestSortedItemsWithSortedDic(SortedDictionary) and TestSortedItems (LINQ). The difference is almost 3 times the LINQ orderby query. Expanding the TestSortedItemsWithSortedDic will reveal the following

sorted

As you can see that adding items into sorted dictionary takes around 6.37% of the CPU cycle which is definitely because of the sort algorithm that it runs on each add. Also, there is another 1.39% during the initialization. Only these two items take up 7.76%, let alone the other SortedDictionary entries. Now, lets see how the processing with LINQ orderby looks like

LINQ 

LINQ iteration takes up 1.77%(where the original execution take place) , Dictionary.Add takes 0.54% comparing to 6.37% with sorted dictionary and additional orderby and select take 0.17 and 0.14% respectively. So, in total add and sorting takes up to (1.77 + 0.54 + 0.17 + 0.14) 3.39% of CPU cycles. Here to include that, highest CPU index may vary with current load, but the ratio remains almost the same.

Therefore, it is almost clear that we can replace SortedDictionary with LINQ and without it .stripped down version of .net in Silverlight is not a bad idea :-). Also, those who commented on my last post for live comparison thank you !!. You can also download the test code I have used here and run it in dottrace to see it live (I have used dottrace 3.1).

Have fun!!

kick it on DotNetKicks.com

With LINQ.Flickr it is quite necessary to get signature on parameters in order to do authenticated flickr photo get. As with the signature, it has to be sorted by parameter then to be hashed by MD5. Previously, I used to use SortedDictionary dictionary to do so, but thinking a little bit I learned that we actually don't need SortedDictionary anymore after we have LINQ. May be that's why the product team at Microsoft removed SortedDictionary from stripped down version of .net that comes with SilverLight.

Now, off to code, lets say I want 10 photos from my photo stream in flickr, to achieve that  I would simply write

var query = (from photo in context.Photos
            where photo.ViewMode == ViewMode.Owner
            select photo).Take(10);

Behind the scene, it will first try to authenticate me, if I am not already then it will try to do it and finally it will make an authenticated call to get my photos from my flickr account. Using SortedDictionary, the sorting of signature items used to be done on the fly but the overhead is that on every new item inserted in the dictionary due to each parameter of REST call, it runs the sort logic. This is of course a waste of processor speed. So, I replaced all the lines that look like

IDictionary<string, string> sortedSigItems 
= new SortedDictionary<string, string>();

with

IDictionary<string, string> sigItems = new Dictionary<string, string>();

Finally, inside my GetSignature method at BaseRepository of LINQ.Flickr I added the following lines, before final toString stuff.

var query = from sigItem in sigItems
            orderby sigItem .Key ascending
            select sigItem.Key + sigItem .Value;

// do the rest with sorted list.

The whole thing is much pleasing with LINQ query and less processor intensive.So next time when you think about sorting, think about LINQ first :-)

Have fun!!!

Continued with comparison in part 2 of this post.

kick it on DotNetKicks.com

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://flickrmvc.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.

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

Recently , we have added a new section at dotnetslackers by which you can share your code to public.  Now, code snippets are tiny piece of code that can work as a unit, can come handy and be a real time-saver when building up complex solution or can be some interesting piece of lines which in turn can make out someone's day.

To get started, lets go to  www.dotnetslackers.com 

image

Navigate to Community -> Code snippets. Here, either you can browse snippets posted by others and share your comments or hit on the "Add new" button to make one by yourself. It will firstly direct you to the login page, if you are not logged in already. Finally, you will get a clean form to add your snippet and give some title, detail and tags for it and its done.

image

Let us know, how do you feel about the new feature and what are the things you would love to see which will make it work for you. Anything you want to share, just write them down at

http://dotnetslackers.com/community/forums/t/1823.aspx

Enjoy!!

kick it on DotNetKicks.com

More Posts Next page »