<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;D04BSH86fip7ImA9WhRaFU0.&quot;"><id>tag:blogger.com,1999:blog-4819442698791214124</id><updated>2012-02-18T00:42:39.116+05:30</updated><category term="jQuery UI" /><category term="Uncategorized" /><category term="Autocomplete" /><category term="Ninject" /><category term="Webcam" /><category term="ASP.NET MVC" /><category term="Silverlight" /><title>Shahnawaz Khan's Blog</title><subtitle type="html">A Tech Geek on ASP.NET, MVC, WCF, WPF, Silverlight, WP7, jQuery and many more...</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.shahnawazk.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://www.shahnawazk.com/" /><author><name>Shahnawaz Khan</name><uri>https://profiles.google.com/106122281627139315122</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-u_U37o9yUHw/AAAAAAAAAAI/AAAAAAAAAAA/0S4qYaMolQk/s512-c/photo.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>4</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/shahnawazk" /><feedburner:info uri="shahnawazk" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;D0EMRns6eip7ImA9Wx9RF0w.&quot;"><id>tag:blogger.com,1999:blog-4819442698791214124.post-3636747239568500982</id><published>2010-12-19T05:07:00.000+05:30</published><updated>2010-12-19T05:11:27.512+05:30</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-12-19T05:11:27.512+05:30</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="Ninject" /><title>Dependency Injection in ASP.NET MVC 3 using Ninject</title><content type="html">&lt;p&gt;Since the release of ASP.NET MVC 2, I am learning Dependency Injection in ASP.NET MVC. I used Microsoft &lt;a title="Unity Application Block (Unity)" href="http://unity.codeplex.com/" rel="nofollow" target="_blank"&gt;Unity&lt;/a&gt; and realized the need for it to simplify ways to handle the dependencies between objects.&lt;/p&gt; &lt;p&gt;I have seen a lot of open source developers using &lt;a title="Open source dependency injector for .NET" href="http://www.ninject.org/" rel="nofollow" target="_blank"&gt;Ninject&lt;/a&gt; as a dependency injector and I think I’ll give it a try. In Rob Conery’s &lt;a title="ASP.NET MVC 2.0 Starter Site" href="http://mvcstarter.codeplex.com/" rel="nofollow" target="_blank"&gt;MVCStarter&lt;/a&gt;, I have seen good implementation of IoC setup using Ninject 2.0 it was good but I have too many works done in MVC application’s Global.asax.cs file. I didn’t like that configuration but I’ve no choice.&lt;/p&gt; &lt;p&gt;With the release of ASP.NET MVC 3 &lt;font color="#c0504d"&gt;&lt;strong&gt;BETA&lt;/strong&gt;&lt;/font&gt;&amp;nbsp;&lt;em&gt;[currently in RC 2]&lt;/em&gt; they have made significant changes to the IoC support, please look at &lt;a title="Brad Wilson's post" href="http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html" rel="nofollow" target="_blank"&gt;Brad Wilson's post&lt;/a&gt;, for service location/dependency resolution with MVC, they introduced new interface: &lt;strong&gt;&lt;em&gt;System.Web.Mvc.IDependencyResolver&lt;/em&gt;&lt;/strong&gt;. You have to implement this interface within your application and register it with &lt;strong&gt;&lt;em&gt;System.Web.Mvc.DependencyResolver&lt;/em&gt;&lt;/strong&gt;’s static method &lt;strong&gt;&lt;em&gt;SetResolver(IDependencyResolver resolver)&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;In &lt;a title="Introducing ASP.NET MVC 3 (Preview 1)" href="http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx" rel="nofollow" target="_blank"&gt;Scott Guthrie's post&lt;/a&gt;, I have &lt;a title="MVC 3 Ninject Demo" href="http://www.scottgu.com/blogposts/mvc3ninject.zip" rel="nofollow" target="_blank"&gt;downloaded&lt;/a&gt; and study the Ninject implementation of dependency injection and happy with the neat code he wrote. no use of Ninject MVC extension: &lt;strong&gt;&lt;em&gt;Ninject.Web.MVC&lt;/em&gt;&lt;/strong&gt;, it is due to the new IoC support in ASP.NET MVC 3.&lt;/p&gt; &lt;p&gt;There are some questions asked regarding it on stackoverflow, So I decided to write a brief post on how to use Ninject 2 in ASP.NET MVC 3.&lt;/p&gt; &lt;h3&gt;Prerequisites&lt;/h3&gt; &lt;p&gt;you will need to download the latest build of Ninject from &lt;a title="Ninject downloads" href="https://github.com/ninject/ninject/downloads" rel="nofollow" target="_blank"&gt;here&lt;/a&gt;. I download this &lt;font color="#a5a5a5"&gt;&lt;em&gt;Ninject-2.1.0.91-RC2-release-net-4.0.zip&lt;/em&gt;&lt;/font&gt;&lt;font color="#000000"&gt;. You also need the latest release of &lt;a title="ASP.NET MVC 3 RC 2 Release announcement" href="http://weblogs.asp.net/scottgu/archive/2010/12/10/announcing-asp-net-mvc-3-release-candidate-2.aspx" rel="nofollow" target="_blank"&gt;ASP.NET MVC 3 [RC 2]&lt;/a&gt;. If you download the project at the end of this post then you don’t need to download &lt;strong&gt;&lt;em&gt;Ninject&lt;/em&gt;&lt;/strong&gt; binaries it’s been provided in the project itself.&lt;/font&gt;&lt;/p&gt; &lt;h3&gt;Let’s start&lt;/h3&gt; &lt;p&gt;Create new project: &lt;strong&gt;File –&amp;gt; New –&amp;gt; Project&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;You can download the ready to run project at the end of this post.&lt;/p&gt; &lt;p&gt;Select ASP.NET MVC 3 Web Application as shown below:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GCTlTeDI/AAAAAAAAAO4/MrEpo5ce4zo/s1600-h/mvc3newwebapp%5B5%5D.jpg"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="New MVC 3 Web Application" border="0" alt="New MVC 3 Web Application" src="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GFb4zjOI/AAAAAAAAAO8/snabrIbce9g/mvc3newwebapp_thumb%5B3%5D.jpg?imgmax=800" width="640" height="407"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;After clicking OK you would see new ASP.NET MVC 3 Project dialog asking you to select Template, View Engine and you want Unit Test project or not.&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh5.ggpht.com/_vl2jKIcPbEs/TQ1GHjFR20I/AAAAAAAAAPA/Jlu1yjpRrHw/s1600-h/newprojectdialog%5B8%5D.jpg"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="New project dialog" border="0" alt="New project dialog" src="http://lh4.ggpht.com/_vl2jKIcPbEs/TQ1GKIUWiAI/AAAAAAAAAPE/hDl1Bh-AkUk/newprojectdialog_thumb%5B6%5D.jpg?imgmax=800" width="525" height="480"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now you have your new ASP.NET MVC 3 Web Application project ready.&lt;/p&gt; &lt;p&gt;For demonstrating dependency injection we need some sort of interfaces and their concrete implementations, so in that regard I will add a new interface named &lt;strong&gt;&lt;em&gt;IMessageService&lt;/em&gt;&lt;/strong&gt; and it’s implementation &lt;strong&gt;&lt;em&gt;MessageService &lt;/em&gt;&lt;/strong&gt;in the new &lt;strong&gt;&lt;em&gt;Services&lt;/em&gt;&lt;/strong&gt; folder to the project root.&lt;/p&gt; &lt;p&gt;Here is the interface &lt;strong&gt;&lt;em&gt;IMessageService&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh3.ggpht.com/_vl2jKIcPbEs/TQ1GNOMRJEI/AAAAAAAAAPI/ndldVQsUjhg/s1600-h/IMessageService%5B5%5D.jpg"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="IMessageService" alt="IMessageService" src="http://lh3.ggpht.com/_vl2jKIcPbEs/TQ1GPYNA0BI/AAAAAAAAAPM/_Vzzegoko9k/IMessageService_thumb%5B3%5D.jpg?imgmax=800" width="443" height="306"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;and &lt;strong&gt;&lt;em&gt;MessageService&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh4.ggpht.com/_vl2jKIcPbEs/TQ1GRiN0v3I/AAAAAAAAAPQ/oWrfwRcSFww/s1600-h/MessageService%5B5%5D.jpg"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="MessageService" alt="MessageService" src="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GU-RlMRI/AAAAAAAAAPU/dlr43hJyN5E/MessageService_thumb%5B3%5D.jpg?imgmax=800" width="621" height="383"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now setting up project to introduce dependency injection, this is the time to add a reference to &lt;em&gt;&lt;strong&gt;Ninject.dll&lt;/strong&gt;&lt;/em&gt; that you have downloaded as described earlier, if you are lazy like mine then download the project linked at the end of this post.&lt;/p&gt; &lt;p&gt;Now open up &lt;strong&gt;&lt;em&gt;Global.asax.cs&lt;/em&gt;&lt;/strong&gt; and add the &lt;strong&gt;&lt;em&gt;using Ninject;&lt;/em&gt;&lt;/strong&gt; statement to add a Ninject reference, from ASP.NET MVC 3 Beta and above we have to implement &lt;strong&gt;&lt;em&gt;IDependencyResolver&lt;/em&gt;&lt;/strong&gt; for DI work, so It can be implement like this:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh4.ggpht.com/_vl2jKIcPbEs/TQ1GXwjbPmI/AAAAAAAAAPY/Yc-QarOiTCs/s1600-h/IDependencyResolver%5B5%5D.jpg"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="IDependencyResolver" alt="IDependencyResolver" src="http://lh3.ggpht.com/_vl2jKIcPbEs/TQ1GbeOE0GI/AAAAAAAAAPc/dV-NB72HEe4/IDependencyResolver_thumb%5B3%5D.jpg?imgmax=800" width="495" height="481"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now in the &lt;strong&gt;&lt;em&gt;Application_Start(),&lt;/em&gt;&lt;/strong&gt; we want to hook our DI related stuff. for simplicity, like Scott Guthrie did, I’ll add a method which do it all like that:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GdFMYmlI/AAAAAAAAAPg/F5gzkOtxpbk/s1600-h/SetupDI%5B5%5D.jpg"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="SetupDI" alt="SetupDI" src="http://lh3.ggpht.com/_vl2jKIcPbEs/TQ1GfedE6VI/AAAAAAAAAPk/l0oPJKmDyUQ/SetupDI_thumb%5B3%5D.jpg?imgmax=800" width="602" height="183"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;ok, in the method above I created a standard kernel which is implemented in the &lt;strong&gt;&lt;em&gt;Ninject.dll&lt;/em&gt;&lt;/strong&gt; and bind our service to it’s concrete implementation, say whenever the application encounters the &lt;strong&gt;&lt;em&gt;IMessageService&lt;/em&gt;&lt;/strong&gt; then it will automatically creates a new instance of &lt;strong&gt;&lt;em&gt;MessageService&lt;/em&gt;&lt;/strong&gt; damn simple isn’t it, don’t forget to call above method in &lt;strong&gt;&lt;em&gt;Application_Start()&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;To test it, open up &lt;strong&gt;&lt;em&gt;HomeController&lt;/em&gt;&lt;/strong&gt; and change it like that:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1Ghg2uUEI/AAAAAAAAAPo/MPYiFdYIFuA/s1600-h/HomeController%5B5%5D.jpg"&gt;&lt;img style="margin: ; padding-left: ; padding-right: ; display: inline; padding-top: " title="HomeController" alt="HomeController" src="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GjxNVW5I/AAAAAAAAAPs/GKwWIkh8E1Y/HomeController_thumb%5B3%5D.jpg?imgmax=800" width="469" height="339"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;First, I add a private readonly field &lt;strong&gt;&lt;em&gt;_messageService&lt;/em&gt;&lt;/strong&gt; that holds our service instance on the fly. I also add a class constructor which takes single parameter of type &lt;strong&gt;&lt;em&gt;IMessageService&lt;/em&gt;&lt;/strong&gt; and then set it to our private field.&lt;/p&gt; &lt;p&gt;In &lt;strong&gt;&lt;em&gt;Index()&lt;/em&gt;&lt;/strong&gt; ActionResult method I called the &lt;strong&gt;&lt;em&gt;GetMessage()&lt;/em&gt;&lt;/strong&gt; and we are done, look I didn’t create a new instance of &lt;strong&gt;&lt;em&gt;MessageService&lt;/em&gt;&lt;/strong&gt; class anywhere it will automatically created by our DI container.&lt;/p&gt; &lt;p&gt;Now run your application by pressing &lt;strong&gt;&lt;em&gt;F5&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;Ctrl+F5&lt;/em&gt;&lt;/strong&gt; you will see:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh4.ggpht.com/_vl2jKIcPbEs/TQ1Gl7GfC9I/AAAAAAAAAPw/jjcThXchgfE/s1600-h/Run%5B6%5D.jpg"&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Run" border="0" alt="Run" src="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GoJ3kblI/AAAAAAAAAP0/hjyOv9ofFnY/Run_thumb%5B4%5D.jpg?imgmax=800" width="640" height="196"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;you see the message above it comes from our &lt;strong&gt;&lt;em&gt;MessageService&lt;/em&gt;&lt;/strong&gt; class’s &lt;strong&gt;&lt;em&gt;GetMessage()&lt;/em&gt;&lt;/strong&gt; method which I called in &lt;strong&gt;&lt;em&gt;HomeController&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Hope you understand how DI works in ASP.NET MVC 3 with &lt;strong&gt;&lt;em&gt;Ninject&lt;/em&gt;&lt;/strong&gt; without the need of &lt;strong&gt;Ninject.Web.Mvc&lt;/strong&gt; extension, thanks to the &lt;a title="Phil Haack" href="http://www.haacked.com" rel="nofollow" target="_blank"&gt;Phil Haack&lt;/a&gt; and team.&lt;/p&gt; &lt;p&gt;Now for your comfort, download the ready to run project right now.&lt;/p&gt; &lt;p&gt;&lt;iframe style="padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px" title="Preview" marginheight="0" src="http://cid-cadcf66306ccbdf8.office.live.com/embedicon.aspx/Public/Projects/Mvc3NinjectDemo.zip" frameborder="0" marginwidth="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;&lt;em&gt;Note&lt;/em&gt;&lt;/strong&gt;: I have been learning coding best practices since my early development years, so if you found that I made a mistake here and there then please express it in comments below, I appreciate that and will learn from you.&lt;/p&gt; &lt;p&gt;Enjoy!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4819442698791214124-3636747239568500982?l=www.shahnawazk.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/shahnawazk/~4/4kIik5Z6q7E" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.shahnawazk.com/feeds/3636747239568500982/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.shahnawazk.com/2010/12/dependency-injection-in-aspnet-mvc-3.html#comment-form" title="19 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/3636747239568500982?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/3636747239568500982?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/shahnawazk/~3/4kIik5Z6q7E/dependency-injection-in-aspnet-mvc-3.html" title="Dependency Injection in ASP.NET MVC 3 using Ninject" /><author><name>Shahnawaz Khan</name><uri>https://profiles.google.com/106122281627139315122</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-u_U37o9yUHw/AAAAAAAAAAI/AAAAAAAAAAA/0S4qYaMolQk/s512-c/photo.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/_vl2jKIcPbEs/TQ1GFb4zjOI/AAAAAAAAAO8/snabrIbce9g/s72-c/mvc3newwebapp_thumb%5B3%5D.jpg?imgmax=800" height="72" width="72" /><thr:total>19</thr:total><feedburner:origLink>http://www.shahnawazk.com/2010/12/dependency-injection-in-aspnet-mvc-3.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkUMQn4_eyp7ImA9WxFaFEQ.&quot;"><id>tag:blogger.com,1999:blog-4819442698791214124.post-78467323965433280</id><published>2010-07-19T02:47:00.000+05:30</published><updated>2010-07-19T03:28:03.043+05:30</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-07-19T03:28:03.043+05:30</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Webcam" /><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight" /><title>Take snapshot from webcam using Silverlight 4 Webcam API</title><content type="html">&lt;p&gt;I have Webcam attached to my Laptop, but I’m not able to capture still images from it on Windows 7. I tried Youcam from &lt;a title="http://www.cyberlink.com" href="http://www.cyberlink.com" rel="nofollow" target="_blank"&gt;Cyberlink&lt;/a&gt; it’s good but not freely available then I decide to build my own application for capturing images from my webcam.&lt;/p&gt; &lt;p&gt;As we know that Silverlight 4 has Webcam, Microphone and other good APIs built in so I decided to build my application with Silverlight 4, so in this post I’ll show you how you can capture images from your webcam and save it.&lt;/p&gt; &lt;p&gt;So let’s start by creating new Silverlight Application by opening Visual Studio 2010 or Visual Web Developer 2010 Express which is freely available, click File –&amp;gt; New Project&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh3.ggpht.com/_vl2jKIcPbEs/TENv2BXXhZI/AAAAAAAAAKw/5hAunz27B1c/s1600-h/slprojectnew%5B4%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="New Project" border="0" alt="New Project" src="http://lh3.ggpht.com/_vl2jKIcPbEs/TENv8ACj-zI/AAAAAAAAAK0/br0qbqM-zGU/slprojectnew_thumb%5B2%5D.png?imgmax=800" width="640" height="407"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In the New Project dialog, select &lt;strong&gt;Silverlight&lt;/strong&gt; in &lt;em&gt;Installed Templates&lt;/em&gt; section from the Left pane and select &lt;strong&gt;Silverlight Application&lt;/strong&gt;, as you hit ok button a new dialog appears asking you “if you want to create new ASP.NET Web application or ASP.NET MVC application”. See the screenshot below:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_vl2jKIcPbEs/TENv_erZpPI/AAAAAAAAAK4/2aHx0ZQM_QA/s1600-h/newslapp%5B4%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Ask for new ASP.NET Web Application" border="0" alt="Ask for new ASP.NET Web Application" src="http://lh4.ggpht.com/_vl2jKIcPbEs/TENwEUITENI/AAAAAAAAAK8/sh-a7qglAMs/newslapp_thumb%5B2%5D.png?imgmax=800" width="518" height="416"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;As shown above the dialog is straight forward and easy to understand, just have settings as shown and hit ok button, you now have Silverlight application ready to work with.&lt;/p&gt; &lt;p&gt;Our application will look like this when completed in the designer:&lt;/p&gt; &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_vl2jKIcPbEs/TENw66xTmiI/AAAAAAAAALA/KS6m3sFC70I/s1600-h/sldesigner%5B4%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Silverlight Designer" border="0" alt="Silverlight Designer" src="http://lh5.ggpht.com/_vl2jKIcPbEs/TENxB99GjUI/AAAAAAAAALE/8Wkke0PbZxI/sldesigner_thumb%5B2%5D.png?imgmax=800" width="640" height="384"&gt;&lt;/a&gt;  &lt;p&gt;What are we waiting for let design the application first in the xaml designer. The application UI is very simple you see in the screenshot I have two comboBox on top, one for holding VIDEO devices and second for AUDIO devices available in the machine, we can fill these two comboBox within our code, in the center of the UI you see white large box which is for displaying our Webcam live feed, I add three buttons for different purposes, “&lt;strong&gt;Start Camera&lt;/strong&gt;” is used to enable webcam, this same button is also used to disable webcam, “&lt;strong&gt;Capture Image&lt;/strong&gt;” is used to capture current frame from the live webcam feed which is in raw format as &lt;a title="WriteableBitmap" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx" rel="nofollow" target="_blank"&gt;WriteableBitmap&lt;/a&gt;, finally last button “&lt;strong&gt;Save Image&lt;/strong&gt;” is used to save captured frame in &lt;strong&gt;jpg&lt;/strong&gt; format. On the bottom of the application there is a &lt;em&gt;ListBox&lt;/em&gt; which holds our captured raw frames from the webcam, which is bind to &lt;a title="ObseravableCollection&amp;lt;WriteableBitmap&amp;gt;" href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" rel="nofollow" target="_blank"&gt;ObseravableCollection&amp;lt;WriteableBitmap&amp;gt;&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;To design exactly as shown above, just copy and paste the following xaml markup in your &lt;strong&gt;MainPage.xaml&lt;/strong&gt; file&lt;/p&gt;&lt;pre class="brush: xml"&gt;&amp;lt;UserControl x:Class="SilverlightDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="600" d:DesignWidth="600"&amp;gt;

    &amp;lt;Grid x:Name="LayoutRoot" Background="#FF333333"&amp;gt;
        &amp;lt;StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"&amp;gt;
            &amp;lt;TextBlock Foreground="White" FontSize="18" HorizontalAlignment="Center"&amp;gt;Silverlight 4 Webcam and Microphone Demo&amp;lt;/TextBlock&amp;gt;
            &amp;lt;Grid Width="500"&amp;gt;
                &amp;lt;Grid.RowDefinitions&amp;gt;
                    &amp;lt;RowDefinition /&amp;gt;
                    &amp;lt;RowDefinition /&amp;gt;
                    &amp;lt;RowDefinition /&amp;gt;
                    &amp;lt;RowDefinition /&amp;gt;
                &amp;lt;/Grid.RowDefinitions&amp;gt;
                &amp;lt;Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;ColumnDefinition Width="250" /&amp;gt;
                    &amp;lt;ColumnDefinition Width="250" /&amp;gt;
                &amp;lt;/Grid.ColumnDefinitions&amp;gt;
                &amp;lt;TextBlock Foreground="White" Margin="5" Text="Available VIDEO Sources" Grid.Column="0" Grid.Row="0"&amp;gt;&amp;lt;/TextBlock&amp;gt;
                &amp;lt;ComboBox x:Name="VideoSources" Grid.Column="0" Grid.Row="1" Margin="5"&amp;gt;
                    &amp;lt;ComboBox.ItemTemplate&amp;gt;
                        &amp;lt;DataTemplate&amp;gt;
                            &amp;lt;TextBlock Text="{Binding FriendlyName}"/&amp;gt;
                        &amp;lt;/DataTemplate&amp;gt;
                    &amp;lt;/ComboBox.ItemTemplate&amp;gt;
                &amp;lt;/ComboBox&amp;gt;
                &amp;lt;TextBlock Foreground="White" Margin="5" Text="Available AUDIO Sources" Grid.Column="1" Grid.Row="0"&amp;gt;&amp;lt;/TextBlock&amp;gt;
                &amp;lt;ComboBox x:Name="AudioSources" Grid.Column="1" Grid.Row="1" Margin="5"&amp;gt;
                    &amp;lt;ComboBox.ItemTemplate&amp;gt;
                        &amp;lt;DataTemplate&amp;gt;
                            &amp;lt;TextBlock Text="{Binding FriendlyName}"/&amp;gt;
                        &amp;lt;/DataTemplate&amp;gt;
                    &amp;lt;/ComboBox.ItemTemplate&amp;gt;
                &amp;lt;/ComboBox&amp;gt;
                &amp;lt;Border CornerRadius="8" Grid.ColumnSpan="2" Grid.Row="2" Width="500" Height="400"&amp;gt;
                    &amp;lt;Border.Effect&amp;gt;
                        &amp;lt;DropShadowEffect Color="White" Direction="0" ShadowDepth="0" BlurRadius="15"/&amp;gt;
                    &amp;lt;/Border.Effect&amp;gt;
                    &amp;lt;Rectangle x:Name="Webcam" Fill="White" Margin="5" Width="500" Height="400"/&amp;gt;
                &amp;lt;/Border&amp;gt;
                &amp;lt;StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.ColumnSpan="2" Grid.Row="3"&amp;gt;
                    &amp;lt;Button x:Name="StartStopWebcam" Content="Start Camera" Width="100" Height="35" Margin="5" Click="StartStopWebcam_Click"/&amp;gt;
                    &amp;lt;Button x:Name="CaptureWebcam" Content="Capture Image" Width="100" Height="35" Margin="5" Click="CaptureWebcam_Click" /&amp;gt;
                    &amp;lt;Button x:Name="SaveImage" Content="Save Image" Width="100" Height="35" Margin="5" Click="SaveImage_Click" /&amp;gt;
                &amp;lt;/StackPanel&amp;gt;
            &amp;lt;/Grid&amp;gt;
            &amp;lt;ScrollViewer Width="500" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Hidden"&amp;gt;
                &amp;lt;ListBox x:Name="Snapshots"&amp;gt;
                    &amp;lt;ListBox.ItemTemplate&amp;gt;
                        &amp;lt;DataTemplate&amp;gt;
                            &amp;lt;Image Source="{Binding}" Margin="5" Stretch="UniformToFill" Height="70"/&amp;gt;
                        &amp;lt;/DataTemplate&amp;gt;
                    &amp;lt;/ListBox.ItemTemplate&amp;gt;
                    &amp;lt;ListBox.ItemsPanel&amp;gt;
                        &amp;lt;ItemsPanelTemplate&amp;gt;
                            &amp;lt;StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"/&amp;gt;
                        &amp;lt;/ItemsPanelTemplate&amp;gt;
                    &amp;lt;/ListBox.ItemsPanel&amp;gt;
                &amp;lt;/ListBox&amp;gt;
            &amp;lt;/ScrollViewer&amp;gt;
        &amp;lt;/StackPanel&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;&lt;p&gt;Our UI is complete and we can move on to our code, open the &lt;strong&gt;MainPage.xaml.cs&lt;/strong&gt; file, we first start declaring two global variable like that:&lt;/p&gt;&lt;pre&gt;        CaptureSource _captureSource;
        ObservableCollection&lt;WriteableBitmap&gt; _images = new ObservableCollection&lt;WriteableBitmap&gt;();&lt;/pre&gt;&lt;p&gt;we define &lt;strong&gt;_captureSource&lt;/strong&gt; to hold the instance of &lt;a title="CaptureSource" href="http://msdn.microsoft.com/en-us/library/system.windows.media.capturesource(VS.95).aspx" rel="nofollow" target="_blank"&gt;CaptureSource&lt;/a&gt; which is used to interact with AUDIO/VIDEO devices. &lt;strong&gt;_images&lt;/strong&gt; variable is used to holds all captured frames from the webcam and will be the item source for the above said &lt;em&gt;ListBox&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;for declaring &lt;strong&gt;ObservableCollection&amp;lt;T&amp;gt;&lt;/strong&gt; type you need to have &lt;font color="#0000ff"&gt;using&lt;/font&gt; System.Collections.ObjectModel;&lt;/p&gt;&lt;p&gt;we also have to declare one public property named &lt;strong&gt;SelectedSnapshot&lt;/strong&gt;, which holds the current captured frame from the live webcam feed and used to save image as jpg:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;        private WriteableBitmap selectedSnapshot;
        public WriteableBitmap SelectedSnapshot
        {
            get { return selectedSnapshot; }
            set { selectedSnapshot = value; }
        }&lt;/pre&gt;&lt;p&gt;We then add &lt;strong&gt;Loaded&lt;/strong&gt; event handler in the default constructor, see the code below:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Get list of the VIDEO Sources and bind
            VideoSources.ItemsSource = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();

            // Get list of the AUDIO Sources and bind
            AudioSources.ItemsSource = CaptureDeviceConfiguration.GetAvailableAudioCaptureDevices();

            // Select the default devices
            if (VideoSources.Items.Count &gt; 0)
                VideoSources.SelectedIndex = 0;

            if (AudioSources.Items.Count &gt; 0)
                AudioSources.SelectedIndex = 0;

            // Creating CaptureSource
            _captureSource = new CaptureSource();

            // Handle CaptureImageAsync Completed event handler
            _captureSource.CaptureImageCompleted += (s, ev) =&gt;
            {
                ProcessImage(ev.Result);
            };

            // Bind snapshots
            Snapshots.ItemsSource = _images;

            // Disable the capture button, it'll be enabled when capture source is ready
            CaptureWebcam.IsEnabled = false;
            SaveImage.IsEnabled = false;
        }&lt;/pre&gt;&lt;p&gt;above method is very simple, which is used to initialize some of our application parts, we first set the item source of AUDIO/VIDEO &lt;em&gt;comboBox&lt;/em&gt;, which are filled by getting all the devices available in the user’s machine. I also create a new &lt;strong&gt;CaptureSource&lt;/strong&gt; instance, after that I handled &lt;a title="CaptureImageCompleted" href="http://msdn.microsoft.com/en-us/library/system.windows.media.capturesource.captureimagecompleted(VS.95).aspx" rel="nofollow" target="_blank"&gt;CaptureImageCompleted&lt;/a&gt; event handler which is fired after capturing raw image by calling &lt;strong&gt;CaptureSource&lt;/strong&gt;’s &lt;a title="CaptureImageAsync()" href="http://msdn.microsoft.com/en-us/library/system.windows.media.capturesource.captureimageasync(VS.95).aspx" rel="nofollow" target="_blank"&gt;CaptureImageAsync()&lt;/a&gt; method. Finally I bind the &lt;em&gt;ListBox&lt;/em&gt; to captured frames collection by setting it’s &lt;em&gt;ItemSource&lt;/em&gt; property to &lt;strong&gt;_images&lt;/strong&gt;.&lt;/p&gt;&lt;p&gt;In the above code you might think of &lt;strong&gt;ProcessImage(ev.Result)&lt;/strong&gt; method, I have this method for processing raw captured frame, the code in that method is simple and does nothing but add the captured frame to &lt;strong&gt;_images&lt;/strong&gt; collection and set the &lt;strong&gt;SelectedSnapshot&lt;/strong&gt; property to the current captured frame.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;        private void ProcessImage(WriteableBitmap bitmap)
        {
            _images.Add(bitmap);
            SelectedSnapshot = bitmap;
            SaveImage.IsEnabled = true;
        }&lt;/pre&gt;&lt;p&gt;Move on to the “&lt;strong&gt;Start Camera&lt;/strong&gt;” button click event, first I check the &lt;em&gt;State&lt;/em&gt; property of the &lt;strong&gt;CaptureSource&lt;/strong&gt; instance if it’s not started then I set the AUDIO/VIDEO Device to the &lt;strong&gt;CaptureSource&lt;/strong&gt; instance from the available devices then I declared a variable of type &lt;a title="VideoBrush" href="http://msdn.microsoft.com/en-us/library/system.windows.media.videobrush(VS.95).aspx" rel="nofollow" target="_blank"&gt;VideoBrush&lt;/a&gt; which is used to paint the video content and set it’s source to &lt;strong&gt;CaptureSource&lt;/strong&gt; instance and finally set it to the &lt;strong&gt;Fill&lt;/strong&gt; property of Rectangle which paints the live video feed from the webcam.&lt;/p&gt;&lt;p&gt;To access the AUDIO/VIDEO devices on the user’s machine we need to have permission, we can request the user’s permission by calling the following code:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;                        // Request user permission
                        if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
                        {
                            if (_captureSource.VideoCaptureDevice != null)
                            {
                                _captureSource.Start();
                                StartStopWebcam.Content = "Stop Camera";
                                CaptureWebcam.IsEnabled = true;
                            }
                        }&lt;/pre&gt;&lt;p&gt;When the above code is executed a dialog window is popup and asking for your permission to access the AUDIO/VIDEO devices, See screenshot below:&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_vl2jKIcPbEs/TENxFbBqw3I/AAAAAAAAALI/4fTjVUHQdfw/s1600-h/slpermission%5B4%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Permission Popup" border="0" alt="Permission Popup" src="http://lh4.ggpht.com/_vl2jKIcPbEs/TENxKJLIvFI/AAAAAAAAALM/YrcOygEq1tk/slpermission_thumb%5B2%5D.png?imgmax=800" width="554" height="207"&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;By clicking &lt;strong&gt;Yes&lt;/strong&gt; you allowed application to access AUDIO/VIDEO devices, just after having permission we can see the live webcam feed in the center of the UI, Let’s see how can I look?&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh4.ggpht.com/_vl2jKIcPbEs/TENxYF0IfrI/AAAAAAAAALQ/ogi21-y6Sk0/s1600-h/mysnap%5B9%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Running Application" border="0" alt="Running Application" src="http://lh3.ggpht.com/_vl2jKIcPbEs/TENxgVb-QbI/AAAAAAAAALU/6dtP73l9Q50/mysnap_thumb%5B5%5D.png?imgmax=800" width="640" height="384"&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Ok once we started capturing we can stop it with the same button which stops capturing from the webcam. you noticed that “&lt;strong&gt;Capture Image&lt;/strong&gt;” button is now activated after starting the webcam which takes snapshot from the current frame and displayed it in ListBox below, “&lt;strong&gt;Capture Image&lt;/strong&gt;” button click event has the following code:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;            // Verify the device is started
            if (_captureSource.VideoCaptureDevice != null &amp;&amp; _captureSource.State == CaptureState.Started)
            {
                // Capture the current frame
                _captureSource.CaptureImageAsync();
            }
        }&lt;/pre&gt;&lt;p&gt;In the code above I just checked the &lt;em&gt;State &lt;/em&gt;property of the &lt;strong&gt;CaptureSource&lt;/strong&gt; instance which must be &lt;strong&gt;Started&lt;/strong&gt; if so then I called the &lt;strong&gt;CaptureImageAsync()&lt;/strong&gt; method, which initiates an asynchronous image capture request. After taking snapshot “&lt;strong&gt;Save Image&lt;/strong&gt;” button is activated which is used to save captured raw bitmap in &lt;strong&gt;jpg&lt;/strong&gt; format on the local storage media, there is no built in function to do so that’s why I’m taking advantage of .NET &lt;a title="Image Tools" href="http://imagetools.codeplex.com/" rel="nofollow" target="_blank"&gt;Image Tools&lt;/a&gt; which have fine API for working with raw images. I have included the required binaries in the project itself so you don’t have to download it, but you can if you want complete set like documentation and other encoders [PNG, BMP, GIF].&lt;/p&gt;&lt;p&gt;To work with &lt;strong&gt;Image Tools&lt;/strong&gt; we first need to reference the required assemblies which are listed below:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;ICSharpCode.SharpZipLib.Silverlight.dll&lt;/li&gt;&lt;li&gt;ImageTools.dll&lt;/li&gt;&lt;li&gt;ImageTools.IO.Jpeg.dll&lt;/li&gt;&lt;li&gt;ImageTools.Utils.dll&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Above assemblies are included in the project within the &lt;strong&gt;Lib&lt;/strong&gt; folder which is available for download see the link below. Ok we now ready to save our webcam snapshots, first we need to have &lt;strong&gt;using&lt;/strong&gt; statements in the top of the code file like following:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;using ImageTools;
using ImageTools.IO.Jpeg;&lt;/pre&gt;&lt;p&gt;In “&lt;strong&gt;Save Image&lt;/strong&gt;” button click event I have following code which actually save the raw image in &lt;strong&gt;jpg&lt;/strong&gt; format:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;            // Gets the current captured raw bitmap
            var rawImage = SelectedSnapshot;

            // If image is selected in the Snapshots ListBox then set it as a save target
            if (Snapshots.SelectedItem != null)
                rawImage = (WriteableBitmap)Snapshots.SelectedItem;

            if (rawImage != null)
            {
                // Init the Save File Dialog
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "JPG Files (*.jpg, *.jpeg)|*.jpg;*.jpeg|All Files (*.*)|*.*";
                saveDialog.DefaultExt = ".jpg";
                saveDialog.FilterIndex = 1;

                // Show save dialog to the user
                if ((bool)saveDialog.ShowDialog())
                {
                    using (Stream stream = saveDialog.OpenFile())
                    {
                        // Convert raw captured bitmap to the image that Image Tools understand with the extension method
                        var image = rawImage.ToImage();
                        // Declare jpeg encoder
                        var encoder = new JpegEncoder();
                        // Set the image quality
                        encoder.Quality = 90;
                        // Finally encode raw bitmap and save it as a jpg image
                        encoder.Encode(image, stream);
                        // Close the stream
                        stream.Close();
                    }
                }
            }&lt;/pre&gt;&lt;p&gt;The code above again is very simple and I commented it well so I don’t think to described it for you, if you any problem then discuss it in the comments. I am done here, hope you like it.&lt;/p&gt;&lt;p&gt;Finally, you can download the full source code below:&lt;/p&gt;&lt;p&gt;&lt;iframe style="padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px" title="Preview" marginheight="0" src="http://cid-cadcf66306ccbdf8.office.live.com/embedicon.aspx/Public/Projects/SilverlightDemo.zip" frameborder="0" marginwidth="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4819442698791214124-78467323965433280?l=www.shahnawazk.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/shahnawazk/~4/0QoEFLJYV8w" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.shahnawazk.com/feeds/78467323965433280/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.shahnawazk.com/2010/07/take-snapshot-from-webcam-using.html#comment-form" title="14 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/78467323965433280?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/78467323965433280?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/shahnawazk/~3/0QoEFLJYV8w/take-snapshot-from-webcam-using.html" title="Take snapshot from webcam using Silverlight 4 Webcam API" /><author><name>Shahnawaz Khan</name><uri>https://profiles.google.com/106122281627139315122</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-u_U37o9yUHw/AAAAAAAAAAI/AAAAAAAAAAA/0S4qYaMolQk/s512-c/photo.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_vl2jKIcPbEs/TENv8ACj-zI/AAAAAAAAAK0/br0qbqM-zGU/s72-c/slprojectnew_thumb%5B2%5D.png?imgmax=800" height="72" width="72" /><thr:total>14</thr:total><feedburner:origLink>http://www.shahnawazk.com/2010/07/take-snapshot-from-webcam-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CE8GRH84eip7ImA9WxFbGUs.&quot;"><id>tag:blogger.com,1999:blog-4819442698791214124.post-8489760126748796356</id><published>2010-07-12T03:10:00.008+05:30</published><updated>2010-07-13T00:57:05.132+05:30</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-07-13T00:57:05.132+05:30</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Autocomplete" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC" /><category scheme="http://www.blogger.com/atom/ns#" term="jQuery UI" /><title>jQuery UI AutoComplete Widget with ASP.NET MVC</title><content type="html">&lt;p&gt;In this post I am showing you how to use jQuery UI Autocomplete widget with ASP.NET MVC. The Autocomplete widget provides suggestions when you type some text into the text field. This is very useful when you provide search box to find data, so lets start using it in Fresh ASP.NET MVC website.&lt;/p&gt; &lt;h3&gt;Overview&lt;/h3&gt; &lt;p&gt;&lt;span style="font-size: 19px; font-weight: bold" class="Apple-style-span"&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;From the jQuery UI website, Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.&lt;br&gt;&lt;br&gt;By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.&lt;br&gt;&lt;br&gt;Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;an Array with local data  &lt;li&gt;a String, specifying a URL which returns Json formatted data  &lt;li&gt;a Callback&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;&lt;br&gt;What you will need?&lt;/h3&gt; &lt;p&gt;To use jQuery UI widgets you will need jQuery UI library, you can download the latest version from &lt;a title="Download jQuery UI library" href="http://jqueryui.com/download" rel="nofollow" target="_blank"&gt;here&lt;/a&gt;. Please make sure that you select the Autocomplete checkbox in the widgets section while downloading.&lt;br&gt;After unzip, the library folder structure looks something like this:&lt;br&gt;&lt;br&gt;&lt;img style="display: inline" class="wlDisabledImage" title="jQuery UI files" alt="jQuery UI files" src="http://lh5.ggpht.com/_vl2jKIcPbEs/TDo2N4Pra3I/AAAAAAAAAKI/HjOsKUlZDYo/jqueryuifiles%5B7%5D.png?imgmax=800" width="584" height="96"&gt;&lt;br&gt;&lt;br&gt;From here we are interested in CSS and JS Folder. CSS folder contains the theme files [images and stylesheet] which you selected while downloading, in JS folder you will find JavaScript files which are required to work with jQuery UI.&lt;/p&gt; &lt;h3&gt;Setting up project&lt;/h3&gt; &lt;p&gt;I am assuming that you have Visual Studio 2010 Express or higher installed along with SQL Server 2008 Express or higher. I am using Visual Web Developer 2010 Express and SQL Server 2008 R2 Express on my machine both are freely available from Microsoft. I like Microsoft products very much.&lt;br&gt;&lt;br&gt;Open Visual Web Developer 2010 Express from start menu and create new ASP.NET MVC 2 Empty Web Application project from the installed templates, you now have a working project.&lt;br&gt;&lt;br&gt;Now add jQuery UI library to the newly created project.&lt;br&gt;&lt;br&gt;Add &lt;strong&gt;&lt;em&gt;images&lt;/em&gt;&lt;/strong&gt; folder and &lt;strong&gt;&lt;em&gt;jquery-ui-1.8.2.custom.css&lt;/em&gt;&lt;/strong&gt; file from the CSS folder to the &lt;strong&gt;Content&lt;/strong&gt; folder in the project then add both JavaScript files from JS folder to the &lt;strong&gt;Scripts&lt;/strong&gt; folder.&lt;br&gt;&lt;br&gt;Your solution explorer window may look like this:&lt;br&gt;&lt;br&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Solution Explorer" border="0" alt="Solution Explorer" src="http://lh6.ggpht.com/_vl2jKIcPbEs/TDo2UyjE_pI/AAAAAAAAAKQ/idW91bvO-Us/solutionexplorer%5B6%5D.png?imgmax=800" width="241" height="346"&gt;&lt;br&gt;&lt;br&gt;In this MVC application I’ll use AdventureWorks LT 2008 R2 database to show data in jQuery UI Autocomplete widget. To work with the database I’m also adding ADO.NET Entity Data Model [edmx] file in the Models folder, I am adding only Customer table from the AdventureWorks LT 2008 R2 database.&lt;/p&gt; &lt;p&gt;Lets add our Data Model in the project, right click on the &lt;strong&gt;Models&lt;/strong&gt; folder and select add new item, select &lt;strong&gt;ADO.NET Entity Data Model&lt;/strong&gt; from the list of items in the Add New Item dialog and name it &lt;strong&gt;AdventureWorksDB.edmx&lt;/strong&gt;. Follow the wizard and add connection to the AdventureWorks LT 2008 R2 Database or any other database that you have on your&amp;nbsp; machine and add table that you want to work with, but you have to change some code according what you have selected.&lt;/p&gt; &lt;p&gt;If you done exactly as described then we have our Data Model ready to work in the Models folder.&lt;br&gt;Now add Controller in the project, just right click on the &lt;strong&gt;Controller&lt;/strong&gt; folder and click Add Controller, name the controller as you want I name it HomeController:&lt;br&gt;&lt;br&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Add Controller" border="0" alt="Add Controller" src="http://lh4.ggpht.com/_vl2jKIcPbEs/TDo2cl4zBDI/AAAAAAAAAKU/cWbTXX8PWhU/addcontroller%5B5%5D.png?imgmax=800" width="493" height="200"&gt;&lt;br&gt;&lt;br&gt;Now we have to add HomeController’s Action method which returns Json formatted data of Customers Object from the AdventureWorks database.&lt;/p&gt; &lt;p&gt;Here is the Action Method which is called by the Autocomplete widget and returns Json formatted data.&lt;br&gt;&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class HomeController : Controller&lt;br&gt;{&lt;br&gt;    //&lt;br&gt;    // GET: /Home/&lt;br&gt;    public ActionResult Index()&lt;br&gt;    {&lt;br&gt;        return View();&lt;br&gt;    }&lt;br&gt; &lt;br&gt;    public JsonResult GetCustomers(string term)&lt;br&gt;    {&lt;br&gt;        AdventureWorksEntities db = new AdventureWorksEntities();&lt;br&gt;        var customers = from cust in db.Customers.Where(c =&amp;gt; c.LastName.StartsWith(term))&lt;br&gt;                        select cust.LastName;&lt;br&gt;        customers = customers.Distinct();&lt;br&gt;        return Json(customers, JsonRequestBehavior.AllowGet);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;p&gt;In the above code for the HomeController there are two Action methods, Index() which is created by default and GetCustomers(string term) which is used to get Json formatted data. In the GetCustomers(string term) you see we passed parameter “&lt;strong&gt;term&lt;/strong&gt;” of string type, which is passed as a Request variable from the Autocomplete widget and is used to get data based on it.&lt;br&gt;&lt;br&gt;Before working with the Entity Data Model we first need to add a &lt;strong&gt;using&lt;/strong&gt; C# statement in the &lt;strong&gt;HomeController&lt;/strong&gt; to get reference to the Models just like that:&lt;br&gt;&lt;br&gt;&lt;span style="color: blue"&gt;using&lt;/span&gt; YOURPROJECTNAME.Models;&lt;br&gt;&lt;br&gt;Move to the GetCustomers(string term) Action method, I declared a variable &lt;strong&gt;db&lt;/strong&gt; of type &lt;strong&gt;AdventureWorksEntities&lt;/strong&gt; which have all our Data Objects programmed in it by the Entity Framework, I then defined a variable &lt;strong&gt;customers &lt;/strong&gt;and shape the required data by using LINQ to Entities, remove duplicate entries by calling &lt;strong&gt;Distinct()&lt;/strong&gt; Extension method and finally return customers as a Json.&lt;br&gt;&lt;br&gt;Ok, we now have our Controller ready for the Autocomplete widget, finally we have to add a View for the Index() Action method, to add a view simply right click anywhere in the HomeController’s Index() Action method and click Add View context menu item this is the easiest way to add View. Follow the options as shown in the image below for Add View.&lt;br&gt;&lt;br&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Add View" border="0" alt="Add View" src="http://lh5.ggpht.com/_vl2jKIcPbEs/TDo2jiyEC7I/AAAAAAAAAKY/TtUFOOZaPC0/addview%5B5%5D.png?imgmax=800" width="443" height="437"&gt;&lt;br&gt;&lt;br&gt;I didn’t add any Master View page to the project yet that’s why I didn’t checked &lt;strong&gt;Select master page&lt;/strong&gt; checkbox, if you have one added already then you can check it.&lt;br&gt;&lt;br&gt;Visual Web Developer adds Index View as &lt;strong&gt;Index.aspx&lt;/strong&gt; in the &lt;strong&gt;Views/Home&lt;/strong&gt; folder and opened it for editing. In the &lt;strong&gt;Index.aspx&lt;/strong&gt; view page add the following code in the head section which are required to add Autocomplete suggestion feature to the text fields.&lt;br&gt;&lt;/p&gt;&lt;pre class="brush: xml"&gt;&amp;lt;link href="../../Content/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" /&amp;gt;&lt;br&gt;&amp;lt;script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;&lt;br&gt;&amp;lt;script src="../../Scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;&lt;br&gt;&lt;/pre&gt;After adding above references add the following HTML code in the body section which adds a label and text input control which acts as a Autocomplete widget.&lt;br&gt;&lt;pre class="brush: xml"&gt;&amp;lt;label for="customers"&amp;gt;Find:&amp;lt;/label&amp;gt;&lt;br&gt;&amp;lt;input type="text" id="customers" /&amp;gt;&lt;br&gt;&lt;/pre&gt;Finally add the following javascript code in the head section to bind the Autocomplete widget to the text input field.&lt;br&gt;&lt;pre class="brush: js"&gt;&amp;lt;script type="text/javascript"&amp;gt;&lt;br&gt;    $(function () {&lt;br&gt;        $('#customers').autocomplete({&lt;br&gt;            source: '&amp;lt;%= Url.Action("GetCustomers") %&amp;gt;',&lt;br&gt;            minLength: 2&lt;br&gt;        });&lt;br&gt;    });&lt;br&gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;
&lt;p&gt;We are done here with Autocomplete widget, now build and run the application by pressing &lt;strong&gt;F5&lt;/strong&gt;. If all goes well then you are presented with application running in the default internet browser, to test Autocomplete widget just type two or more letters in the input field and the results will show instantly. see the screenshot below:&lt;br&gt;&lt;br&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="Autocomplete Output" border="0" alt="Autocomplete Output" src="http://lh5.ggpht.com/_vl2jKIcPbEs/TDo2rq-QPSI/AAAAAAAAAKg/-EFOPSVE_s8/autocompleteoutput%5B5%5D.png?imgmax=800" width="610" height="356"&gt;&lt;br&gt;&lt;br&gt;I hope you have successfully implement Autocomplete widget as described above. jQuery UI Autocomplete widget has a few options to set as desired, you can have a look on it by going &lt;a title="Autocomplete learn more" href="http://jqueryui.com/demos/autocomplete/" rel="nofollow" target="_blank"&gt;here&lt;/a&gt;.&lt;br&gt;&lt;br&gt;Hope this works!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4819442698791214124-8489760126748796356?l=www.shahnawazk.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/shahnawazk/~4/7YZ-epvWiX0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.shahnawazk.com/feeds/8489760126748796356/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.shahnawazk.com/2010/07/jquery-ui-autocomplete-widget-with.html#comment-form" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/8489760126748796356?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/8489760126748796356?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/shahnawazk/~3/7YZ-epvWiX0/jquery-ui-autocomplete-widget-with.html" title="jQuery UI AutoComplete Widget with ASP.NET MVC" /><author><name>Shahnawaz Khan</name><uri>https://profiles.google.com/106122281627139315122</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-u_U37o9yUHw/AAAAAAAAAAI/AAAAAAAAAAA/0S4qYaMolQk/s512-c/photo.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/_vl2jKIcPbEs/TDo2N4Pra3I/AAAAAAAAAKI/HjOsKUlZDYo/s72-c/jqueryuifiles%5B7%5D.png?imgmax=800" height="72" width="72" /><thr:total>6</thr:total><feedburner:origLink>http://www.shahnawazk.com/2010/07/jquery-ui-autocomplete-widget-with.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0YBSXs5eyp7ImA9WxFbGUg.&quot;"><id>tag:blogger.com,1999:blog-4819442698791214124.post-798864311851236818</id><published>2010-06-17T00:21:00.001+05:30</published><updated>2010-07-12T22:49:18.523+05:30</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-07-12T22:49:18.523+05:30</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Uncategorized" /><title>Welcome to my blog</title><content type="html">Hi everybody, welcome to my new blog, I just moved my blog to new location but the address is still same &lt;a href="http://www.shahnawazk.com/"&gt;http://www.shahnawazk.com&lt;/a&gt;. I'll post all my previous entries again with updated features like &lt;b&gt;Visual Studio 2010 Express&lt;/b&gt;, &lt;b&gt;SQL Server 2008 R2&lt;/b&gt;, &lt;b&gt;ASP.NET 4&lt;/b&gt;, &lt;b&gt;ASP.NET MVC 2&lt;/b&gt;, &lt;b&gt;jQuery 1.4.*&lt;/b&gt;, &lt;b&gt;jQuery UI 1.8.*&lt;/b&gt;, &lt;b&gt;PHP&lt;/b&gt;, &lt;b&gt;MySQL&lt;/b&gt; and many more technologies I deal with.&lt;br /&gt;
&lt;br /&gt;
Happy Coding!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4819442698791214124-798864311851236818?l=www.shahnawazk.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/shahnawazk/~4/xCfBAivPbGk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.shahnawazk.com/feeds/798864311851236818/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.shahnawazk.com/2010/06/welcome-to-my-blog.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/798864311851236818?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4819442698791214124/posts/default/798864311851236818?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/shahnawazk/~3/xCfBAivPbGk/welcome-to-my-blog.html" title="Welcome to my blog" /><author><name>Shahnawaz Khan</name><uri>https://profiles.google.com/106122281627139315122</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-u_U37o9yUHw/AAAAAAAAAAI/AAAAAAAAAAA/0S4qYaMolQk/s512-c/photo.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://www.shahnawazk.com/2010/06/welcome-to-my-blog.html</feedburner:origLink></entry></feed>

