Tuesday, June 14, 2011

Asp.net MVC 3 Nested Grid view with Webgrid



Introduction: In some cases we need to display data in form of parent child i.e. Order and product scenario for shopping cart web site.I have used Web Grid to display records for my asp net MVC 3 application. 

Model classes: I have created two model classes Order and Product

 public class Order
    {
        public int OrderId { get; set; }
        public DateTime OrderDate { get; set; }

        public List<Product> ProductList { get; set; }
    }

    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
    }


Controller:
 public class HomeController : Controller
    {

public ActionResult NestedGrid()
        {
            var Orders = new List<Order>();
            var products1 = new List<Product>();
            products1.Add(new Product { ProductId = 1, Name = "laptop" });
            products1.Add(new Product { ProductId = 5, Name = "pen drive" });
            Orders.Add(new Order { OrderId = 1, ProductList = products1, OrderDate = DateTime.Now });
            var products2 = new List<Product>();
            products2.Add(new Product { ProductId = 3, Name = "Hard disk" });
            products2.Add(new Product { ProductId = 4, Name = "Mouse" });
            Orders.Add(new Order { OrderId = 2, ProductList = products2, OrderDate = DateTime.Now });

            return View(Orders);
        }
}

View: I have used Razor view engine.

@model IEnumerable<MvcApplication1.Data.Order>
@{
    ViewBag.Title = "NestedGrid";
}
@{
        WebGrid topGrid = new WebGrid(source: Model);
}
<h2>NestedGrid</h2>
<div id="grid">
@topGrid.GetHtml(columns:
    topGrid.Columns(
        topGrid.Column("OrderId"),
            topGrid.Column("ProductList", format: (item) =>
        {
            WebGrid subGrid = new WebGrid(item.ProductList);
            return subGrid.GetHtml(
                    columns: subGrid.Columns(
                        subGrid.Column("ProductId"),
                        subGrid.Column("Name")
                    )
                );
        })
         ,topGrid.Column("OrderDate")
    )
)
</div> 

Result:


Conclusion: So we can easily create nested grid with the help of WebGrid in asp.net MVC 3 application.Hope this will be useful to you.

Thanks
Rajendra



Sunday, December 26, 2010

Javascript books for web developers

Web developers should know about following Javascript books -

1.Professional JavaScript for Web Developers - Almost 1,000 pages of VERY detailed JavaScript information. Written by Nicholas Zakas, Yahoo!
 Principal Front-end Engineer for Yahoo!’s home page and recommended by the 
YUI team as well.

2. JavaScript: The Definitive Guide - Considered the Bible of JavaScript for its thorough coverage of JavaScript. You need to have this in your library, even as a reference.

3. DOM Scripting: Web Design with JavaScript and the Document Object Model - This is a good book to get you familiar with the DOM.

4. AdvancED DOM Scripting: Dynamic Web Design Techniques - This book is for intermediate to advanced web designers and developers who already have a reasonable to good knowledge of HTML, CSS, and JavaScript.

5. Beginning JavaScript with DOM Scripting and Ajax: From Novice to Professional (Beginning: from Novice to Professional) - Beginning JavaScript with DOM Scripting and Ajax is an essential guide for modern JavaScript programming; its practical but comprehensive. It covers everything you need to know to get up to speed with JavaScript development to add dynamic enhancements to web pages and program Ajax-style applications.

6. Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries - his book treats JavaScript as a serious object-oriented language, showing you how to build robust, maintainable, and powerful libraries and applications. Along the way, we cover many of the recent innovations such as AJAX, JSON, and interesting design and coding patterns. After reading this book, you'll be prepared to ace your JavaScript job interview and even impress with some bits that the interviewer maybe didn't know. You should read this book if you want to be able to take your JavaScript skills to a new level of sophistication.

7. JavaScript: The Good Parts - With JavaScript: The Good Parts, you'll discover a beautiful, elegant, lightweight and highly expressive language that lets you create effective code, whether you're managing object libraries or just trying to get Ajax to run fast. If you develop sites or applications for the Web, this book is an absolute must.

8. Learning jQuery 1.3 - This book will give you the tools you need to be on the cutting edge of the web development community.While covering jQuery v1.3, the techniques discussed are still useful and I still recommend the book highly.

9. Pro JavaScript Techniques - John Resig’s famous book on advanced JS techniques.Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesnt waste any time looking at things you already know, like basic syntax and structures.

10. Secrets of the JavaScript Ninja - JavaScript expert John Resig reveals the inside know-how of the elite JavaScript programmers. Written to be accessible to JavaScript developers with intermediate-level skills.

11. Ajax Security - Ajax Security systematically debunks today’s most dangerous myths about Ajax security, illustrating key points with detailed case studies of actual exploited Ajax vulnerabilities, ranging from MySpace’s Samy worm to MacWorld’s conference code validator. Even more important, it delivers specific, up-to-the-minute recommendations for securing Ajax applications in each major Web programming language and environment, including .NET, Java, PHP, and even Ruby on Rails.

12. jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide) - Tips & techniques from the jQuery team rolled up in a cookbook style. You can’t go wrong.

13. jQuery in Action, Second Edition - It shows you how to traverse HTML documents, handle events, perform animations, and add Ajax to your web pages. The book's unique "lab pages" anchor the explanation of each new concept in a practical example. You'll learn how jQuery interacts with other tools and frameworks and how to build jQuery plugins.This is now updated for jQuery v1.4.x as well as jQuery UI 1.8.x. Definitely a must-have for jQuery developers.

14. jQuery: Novice to Ninja - Query: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most challenging JavaScript problems. In this question-and-answer book on jQuery, you'll find a cookbook of ready-to-go solutions to help breathe life into your web page.

15. MooTools 1.2 Beginner's Guide - MooTools is a simple-to-use JavaScript library, ideal for people with basic JavaScript skills who want to elevate their web applications to a superior level. If you're a newcomer to MooTools looking to build dynamic, rich, and user-interactive web site applications this beginner's guide with its easy-to-follow step-by-step instructions is all you need to rapidly get to grips with MooTools.

16. MooTools Essentials: The Official MooTools Reference for JavaScript™ and Ajax Development - Complete reference to the Mootools library.

17. Practical Dojo Projects (Practical Projects) - Dojo is a library like few others: written by some of the best JavaScript coders around today, providing nearly everything you’ll need to write modern Rich Internet Applications, all in one place. From Ajax to widgets, to client–side persistence and language extensions, and many points in between, Dojo has it all.

In Practical Dojo Projects, you’ll learn all about what Dojo has to offer.

18. Mastering Dojo: JavaScript and Ajax Tools for Great Web Experiences (Pragmatic Programmers) - In Mastering Dojo, you'll get the whole story, from basic usage to advanced idioms. Mastering Dojo starts out with a fast moving tutorial that will give you techniques that you can start using right away. You'll learn all about Dojo Core--the foundation on which all things Dojo stand. See how you can modularize your project for development and automatically package your release for optimal download performance.

19. Professional JavaScript Frameworks: Prototype,YUI, ExtJS, Dojo and MooTools (Wrox Programmer to Programmer) - This book is for web developers who are eager to explore the benefits of JavaScript frameworks. A working knowledge of HTML, CSS, and JavaScript is required.

20. YUI 2.8 Learning the Library - The YUI Library is a set of utilities and controls written in JavaScript for building Rich Internet Applications, across all major browsers and independently of any server technology. There's a lot of functionality baked into YUI, but getting to and understanding that functionality is not for the faint of heart. This book gives you a clear picture of YUI through a step-by-step approach, packed with lots of examples.

YUI 2.8: Learning the Library covers all released (non-beta) components of the YUI 2.8 Library in detail with plenty of working examples, looking at the classes that make up each component and the properties and methods that can be used. It includes a series of practical examples to reinforce how each component should/can be used, showing its use to create complex, fully featured, cross-browser, Web 2.0 user interfaces. It has been updated from its first edition with the addition of several chapters covering several new controls and enriched with lots of experience of using them.

Saturday, September 25, 2010

Hosting WCF Service with netTcpBinding on IIS7

Web.Config should have following configuration settinggs to hosting WCF service on IIS7(WAS):

    <bindings>
      <netTcpBinding>
        <binding name="tcpbinding" portSharingEnabled="true">
          <security mode="None"></security>
          <!--<security mode="Transport">
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
            <message clientCredentialType="Windows"/>
          </security>-->
        </binding>

       </netTcpBinding>
    </bindings>



Trouble Shooting on IIS7.*
If following exception thrown while adding service reference-
Error: Cannot obtain Metadata from net.tcp://win-2008.cspl:9002/Multibinding/Service1.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.  For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error    URI: net.tcp://win-2008.cspl:9002/Multibinding/Service1.svc    Metadata contains a reference that cannot be resolved: 'net.tcp://win-2008.cspl:9002/Multibinding/Service1.svc'.    Could not connect to net.tcp://win-2008.cspl:9002/Multibinding/Service1.svc. The connection attempt lasted for a time span of 00:00:02.0374439. TCP error code 10061: No connection could be made because the target machine actively refused it .     No connection could be made because the target machine actively refused it

Step1: Make sure following services is enable for net.tcp

a.                Net.Tcp Listener Adapter
b.               Net.Tcp Port Sharing Service

     If not then enable and start both services.

Step2: IIS Manager -> Select Hosted service -> Action pane -> Advance setting ->
           See Enable Protocol, by default http protocol there, need to specify net.tcp with comma separated

Step3: Make sure your application pool is running in classic mode




Step4: Right click on Default Website -> Edit bindings
            Make sure net.tcp protocol information there



Step5: Check firewall, Create Inbound and out bound rule for port which we are using.



Friday, September 24, 2010

WCF Service Throttling Behavior

WCF Service Throttling is a way for you to limit (“throttle”) the throughput of your service so that resources (memory, CPU, network, etc.) are kept at healthy levels.

While it is not a direct instance management technique, throttling enables you to restrain client connections and the load they place on your service. Throttling enables you to avoid maxing out your service and the underlying resources it allocates and uses. When throttling is engaged, if the settings you configure are exceeded, WCF will automatically place the pending callers in a queue and serve them out of the queue in order. If the client's call timeout expires while pending in the queue, the client will get a TimeoutException.

Using the behaviorConfiguration tag, you add to your service a custom behavior that sets throttled values.
<system.serviceModel>
   <services>
      <service name = "MyService" behaviorConfiguration = "ThrottledBehavior">
         ...
      </service>
   </services>
   <behaviors>
      <serviceBehaviors>
         <behavior name = "ThrottledBehavior">
            <serviceThrottling
               maxConcurrentCalls     = "12"
               maxConcurrentSessions  = "34"
               maxConcurrentInstances = "56"
            />
         </behavior>
      </serviceBehaviors>
   </behaviors>
</system.serviceModel>




 I have done following test on wcf service for service throttling in different scenarios:
1.        
If maxConcurrentCalls =2 then I made 3 calls to service it will execute only two calls at a time remaining call put into the queue execute after first two calls. See following program

<serviceThrottling
               maxConcurrentCalls="2"
               maxConcurrentSessions="34"
               maxConcurrentInstances="56"
            />


static void Main(string[] args)
        {
            System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(test1));
            th.Start();
            System.Threading.Thread th1 = new System.Threading.Thread(new System.Threading.ThreadStart(test2));
            th1.Start();
            System.Threading.Thread th2 = new System.Threading.Thread(new System.Threading.ThreadStart(test3));
            th2.Start();

            Console.ReadLine();
        }
        static void test1()
        {
            ServiceReference1.Service1Client o = newConsoleApplication1.ServiceReference1.Service1Client();
           Console.WriteLine("Istance1  " + o.GetData(1));
       }
       static void test2()
        {
            ServiceReference1.Service1Client o = new ConsoleApplication1.ServiceReference1.Service1Client();
            Console.WriteLine("Istance2  " + o.GetData(2));
        }
      static void test3()
        {
            ServiceReference1.Service1Client o = new ConsoleApplication1.ServiceReference1.Service1Client();
            Console.WriteLine("Istance3  " + o.GetData(3));
        }

Result is:




 Each call is taking 5 second to complete.In this sample first two calls execute simaultiniiously and remaining one call executes after 5 seconds.

1. Iif maxConcurrentCalls =3 then I made 3 calls to service it will execute simultaneously
<serviceThrottling
               maxConcurrentCalls="3"
               maxConcurrentSessions="34"
               maxConcurrentInstances="56"
            />
Result is:




3. If maxConcurrentCalls =3 and maxConcurrentSessions="2" then only two calls will be executed rest one call is discarded and any exception will not be raised

<serviceThrottling
               maxConcurrentCalls="3"
               maxConcurrentSessions="2"
               maxConcurrentInstances="56"
            />
Result is:

 
4. If maxConcurrentInstances="2" then same result found
<serviceThrottling
               maxConcurrentCalls="3"
               maxConcurrentSessions="12"
               maxConcurrentInstances="2"
            />
Result is:



Note: Above result is found with default InstanceContextMode and ConcurrencyMode
That is [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall,ConcurrencyMode=ConcurrencyMode.Single)]