Thursday, September 27, 2012

Calling ASP.NET Page Methods with jQuery (Revealing Module Pattern)


This section describes an brief overview of "Revealing Module Pattern" and how can be call a Page Method using Ajax with jQuery (Revealing Module Pattern) without polluting global namespace (window).

What is Revealing Module Pattern ?

The Revealing Module Pattern actually uses the concept of the Self-Executing Anonymous Function as well, but in this case we save the result into a variable. This pattern introduces the concept of a Closure. A closure is a way to keep variables alive after a function has returned. The Mozilla Developer Network has a great page explaining closures. In it they provide a core definition:

“A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.”

Example:

(function (Alerts, $) {
    var test = " My first pattern";
    function Func() {
        alert(test);
    }
    Alerts.publicFun = function () {
        alert("My public Function");
    }
    Alerts.FirstPublicProp = "1233444";

    Alerts.PageMethodCall = function () {

        PageMethods.TestCall(OnRequestComplete, OnRequestError);
    }

    OnRequestComplete = function (result, userContext, methodName) {

        alert(result);
   }

    OnRequestError = function (error, userContext, methodName) {

        if (error != null) {
            alert(error.get_message());
        }
    }
    //return myobj;
} (window.Alerts = window.Alerts || {}, jQuery));

Here, you will surprise following terms :

1. What is meant by window.Alerts=window.Alerts || {}

The code checks to see if Alerts exists in the global namespace i.e. window. If it does not exist, then windows.Alerts is assigned an empty object literal. Using this approach we can build a library across JavaScript files. If another script uses the same technique, then it will pass in the existing instance and append logic to it. Inside the Anonymous Function, if we want something to be public, then we append it to the skillet object. Any other properties or methods will be considered private.

2.The second argument passed in jQuery. The benefit of this is that the named parameter is referenced as $, which allows us to refer to jQuery as $ within the Anonymous Function without having to worry that it will conflict with the $ declared in other JavaScript libraries. This is a common practice that you will most likely run across when looking at well written jQuery code. 

Page Methods :

Page Methods is a new mechanism in ASP.NET applications where the server code can be bound to ASP.NET pages. It is an easy way to communicate asynchronously with the server using ASP.NET AJAX technologies. It is an alternate to calling the page which is reliable and carries a low risk. It is basically used to expose the web methods to the client script.

This tutorial assumes you have some familiarity with Page Method concept of ASP.NET and basic knowledge of jQuery.

Lets take a case, on click of Button of ASPX page, we need to invoke "PageMethodCall" of Alerts module defined above. Lets see, How to do that.

1. Create an .aspx page:


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form runat="server">
    <asp:ScriptManager runat="server" EnablePageMethods="true" AsyncPostBackTimeout="5000">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/jquery-1.4.1.min.js" />
            <asp:ScriptReference Path="~/Scripts/Module.js" />
        </Scripts>
    </asp:ScriptManager>
    <input type="button" title="click here" onclick="Alerts.PageMethodCall()" />
    <div class="main">
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />
    </div>
    <div class="footer">
    </div>
    </form>
</body>
</html>


1. Please note ScriptManager tag. It has two properties assigned:
 a) EnablePageMethods = "true" which means, it allows to call "web page" method directly from JS.
 b) AsyncPostBackTimeout property is set to specify timeout limit to get results.

2. We added ScriptReference tag to assign scripts referenced for same. Please note, we have created a new file called "Module.js" and copied jQuery method defined on top.

3. See the below line carefully : 

<input type="button" title="click here" onclick="Alerts.PageMethodCall()" />

onclick of button, we are calling Page Method of Alert Module. Here we need to add "Module Name" just before "Page Method" to be invoked as Page Methods are defined in scope of "Alerts" module only.

Using same, we are avoiding to pollute global namespace of JavaScript which is one of the best practice of defining JS methods.Page methods are much more openly accessible than it may seem at first. The relative unimportance of EnablePageMethods is a nice surprise.To demonstrate the mechanism with minimal complications, this example has purposely been a minimal one. 

-Thanks!
Tarun

Found a good link: Good and Bad habits of Javascript




Wednesday, September 5, 2012

Task Parallel Library (TPL) in .NET 3.5


What is TPL ?



The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading1 and System.Threading.Tasks2 namespaces in the .NET Framework version 4. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to
applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool3, cancellation support, state management, and other low-level details. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Starting with the .NET Framework 4, the TPL is the preferred way to write multithreaded and parallel code. However, not all code is suitable for parallelization; for example, if a loop performs only a small amount of work on each iteration, or it doesn't run for many iterations, then the overhead of
parallelization can cause the code to run more slowly. Furthermore, parallelization like any multithreaded code adds complexity to your program execution. Although the TPL simplifies multithreaded scenarios, we recommend that you have a basic understanding of threading concepts, for example, locks, deadlocks, and race conditions, so that you can use the TPL effectively. 

For more information about basic parallel computing concepts, see the Parallel Computer Developer Center4 on MSDN. [http://msdn.microsoft.com/en-us/library/dd460717.aspx]

Task Parallel Library for .NET 3.5
To install Task Parallel Library for .NET 3.5, run the following command in the Package Manager Console
and Run
PM> Install-Package TaskParallelLibrary





Why can't create object of an abstract class?



An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.

An abstract class has a protected constructor (by default) allowing derived types to initialize it.

Further, if we go with object creation process by CLR, an object of class can only be created if its FULL memory requirement is known as compilation time. considering anstract class is a "Template" or "Incomplete" class, compiler is not able to get its full memory requirement hence you can't proceed.

Abstract classes have the following features:

  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Why struct can not have parameterless constructor


Although the CLR allows it, C# does not allow structs to have a default parameterless constructor. The reason is that, for a value type, compilers by default neither generate a default constructor, nor do they generate a call to the default constructor. So, even if you happened to define a default constructor, it will not be called and that will only confuse you. To avoid such problems, the C# compiler disallows definition of a default constructor by the user. And because it doesn't generate a default constructor, you can't initialize fields when defining them.


For instance, an array of value types will be initialized to the initial values of its members—i.e., zero for number type primitive members, null for reference types, and so forth—and not to the values provided in a default constructor. This feature makes structs perform better; because, constructor code need not be called.
So, requiring that a constructor contain a minimum of one parameter reduces the possibility that a constructor will be defined which is expected to be called every time the struct type is built.

For more information about Struct: Please visit http://msdn.microsoft.com/en-us/library/ah19swz4(v=vs.71).aspx