Monthly Archives: April 2013

Transaction in WCF

http://msdn.microsoft.com/en-us/library/ff384250(d=printer).aspx

http://www.c-sharpcorner.com/UploadFile/81a718/simple-steps-to-enable-transactions-in-wcf/

http://www.c-sharpcorner.com/uploadfile/shivprasadk/wcf-faq-part-5-transactions/

Leave a comment

Filed under WCF

Yield keyword in C#

What is the use of c# “Yield” keyword.

Leave a comment

Filed under C#

Calling Page_View jQuery function

1. Include utility.js which include below script:

$(document).ready(function () {
    var activePage = $("body");
    activePage.InitializeComponent({ Init: $("body").attr("id") });
});

(function () {
    var baseMethods = {
        InitializeComponent: function (options) {
            var defaults =
                {
                    Base: "Page_",
                    Init: "",
                    Data: "",
                    Date: ""
                };
            var opts = $.extend(defaults, options);
            var functionName = opts.Base + opts.Init;
            var C_Ref = null;
            C_Ref = $(this);
            var state = (C_Ref.data("IsBinded") === undefined || C_Ref.data("IsBinded") === null || !C_Ref.data("IsBinded")) ? false : true;

            if (typeof window[functionName] !== "undefined") {
                window[functionName]({ Handled: state, Reference: C_Ref, Data: opts.Data, Date: opts.Date });
                C_Ref.data("IsBinded", true);
            }
        }
                      
    };

    jQuery.each(baseMethods, function (i) {
        jQuery.fn[i] = this;
    });
})(jQuery);

2. Now add a Common js file all views which has js function Page_ for all view pages. Like

 function Page_HelloJQueryTest(e) {
	alert('hi Demo');
 }

here ‘HelloJQueryTest’ is the name of my view.

3. Add both above js file reference layout view. And in html body tag of layout add id attribute i.e. . So your layout will look like:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/utility.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Demo.js")" type="text/javascript"></script>
</head>

<body id="@ViewBag.PageID">
    @RenderBody()
</body>
</html>

4. Add ViewBag.PageID = “HelloJQueryTest” to each view which include above layout. Like:
For View HelloJQueryTest.cshtml

	@{
		ViewBag.Title = "HelloJQueryTest";
		ViewBag.PageId = "HelloJQueryTest";
		Layout = "~/Views/Shared/_Layout.cshtml";
	}

	<h2>HelloJQueryTest</h2>
   

5. Above view will have controller action defined. Like:

	public class DemoController : Controller
        {
             public ActionResult HelloJQueryTest()
             {
                return View();
             }
        }
       

6. Now when you run your MVC application then for “HelloJQueryTest” all script user function Page_HelloJQueryTest(e) will be called.
Happy coding

Leave a comment

Filed under jQuery

Garbage Collector

When space is not available on heap, new keyword triggers GC for heap cleanup and then reclaims the space

Leave a comment

Filed under C#

Sessionless Controller

With Sessionless Controller you can easily control your session behavior for controllers.
Before going further better to understand Concurrent Requests in MVC & what are the limitation with the same. And how it is resolved with Sessionless Controller

Leave a comment

Filed under MVC

ASP.Net MVC 3 – New Features

1. New Razor View Engine
Razor view are speedy, smaller & lighter in size. They are easy to learn.
For more detail: Introduction RAZOR

2. Granular Request Validation

3. Sessionless Controller Support

http://weblogs.asp.net/imranbaloch/archive/2011/01/16/asp-net-mvc-3-new-features.aspx

Leave a comment

Filed under MVC

Granular Request Validation MVC 3

This is a new feature provided in MVC 3. We will discuss what is request validation & why it is great to make it granular
Request Validation is a feature of ASP.Net that analyzes the data that a browser send to server when a user interact with your site (such as form or query string data) and reject the request that contain suspicious input that looks like html code (basically anything with a ‘<‘). This protects you from HTML injection such as cross site scripting (XSS). It is enabled by default.
However in previous version it was an all-on-or-off feature, meaning that if you want to be able to accept HTML-formatted input from your users in just one field you had to completely turn this protection off. This in turn meant that you now had to validate every bit of data that came from the client.

AllowHtmlAttribute SkipRequestValidationAttribute
In MVC 3 we have introduced a new attribute called AllowHtmlAttribute. You can You can use this attribute to annotate your model properties to indicate that values corresponding to them should not be validated. Let’s take this User model and UserController as an example:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    [AllowHtml]
    public string Description { get; set; }
    [AllowHtml]
    public string Bio { get; set; }
}
 
public class UserController {
    [HttpPost]
    public ActionResult Update(User user) {
        // update user database
    }
}

I have annotated the Description and Bio properties to indicate they should not be request-validated. Now when the Update action method gets invoked these two properties on the User object will not be validated and any HTML they might contain will be passed straight through to the action method. However, everything else will still go through request validation and requests that contain suspicious content in the Name or Email fields will get rejected.

ValidateInputAttribute
AllowHtmlAttribute can only be applied to properties of a model class. For other request validation scenarios the existing ValidateInputAttribute is still helpful. For example, you can use it to disable request validation for action methods that bind to a loose collection of parameters:

[ValidateInput(false)]
public ActionResult Update(int userId, string description)
{
           // Do something
}

Now when the parameters of the Update method get bound request validation will not be performed. You can apply ValidateInput to action methods as shown above or to the entire controller to affect all of its action methods.

ValidateInput is also more usable in MVC 3. In MVC 2 running on .NET 4 you had to set requestValidationMode=”2.0″ in order to turn request validation off. In MVC 3 this is no longer necessary.

Reference: Granular Request Validation in ASP.NET MVC 3

Leave a comment

Filed under MVC

what is lock?

lock marks a statement block as critical section and ensures one thread doesn’t enter critical section with another thread.
lock can be applied on an object. Avoid lock on public type. Below lock should be avoided:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define private object or private static object variable to protect data common to all instance.

class Account
    {
        decimal balance;
        private Object thisLock = new Object();

        public void Withdraw(decimal amount)
        {
            lock (thisLock)
            {
                if (amount &gt; balance)
                {
                    throw new Exception("Insufficient funds");
                }
                balance -= amount;
            }
        }
    }

for more explanation refer:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

Leave a comment

Filed under C#

What makes thread-safe?

  • struct & immutable are thread safe. so string is also thread safe as all you can do is read them.
  • Reading is safe, if all the threads are reading.
  • If a method only access variable scoped within the method then it is thread safe beacuse each thread has it’s own stack.
  • Also if method calls other method which only use local scoped variables.
public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

 

  • but if a method use any properties or fields then you need to use lock to ensure the values are not modified by a different thread.
public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class,
        // a separate thread could have changed its value.
        number = this.someValue.Length;
        return number;
    }
}

To ensure proper concurrency you need to use lock.

Leave a comment

Filed under C#