Thursday, May 30, 2013

Getting column value - Bad vs. Good Linq to Sql

Bad
int mainDepID = db.Departments.SingleOrDefault(y => y.ID == depID).MainDepartmentID;

Good
int mainDepID = 0;

Web.Model.Department currentDepartment = db.Departments.SingleOrDefault(y => y.ID == depID);

if (currentDepartment != null)
{
   mainDepID = currentDepartment.MainDepartmentID;
}

Friday, May 24, 2013

Cool Stuff: Use array to query values using Linq to Sql

You can use an array to query for records using linq to sql...

 int[] myList = new int[] { 2625, 2666 };
 
 var myResult = from st in db.SomeTable          
               where myList.Contains(st.ID)      
               select st;
 
 
Might be useful sometimes?

Thursday, May 23, 2013

ValidateAntiForgeryToken with postback and json in MVC

ValidateAntiForgeryToken as explained here from Stack Overflow
"MVC's Anti-Forgery Token support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form.
The feature doesn't prevent any other type of data forgery or tampering based attacks." 
To use this feature in MVC, you need to add the [HttpPostAuthorizeValidateAntiForgeryToken] attribute to your HttpPost methods.
Example:

[HttpPostAuthorizeValidateAntiForgeryToken]
public ActionResult MyPostBackMethod(string MyTextInputstring MyDropDown){
   //Do some stuff
}

In your view, you also need to add the following, if we are speaking Razor 
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @*Some HTML*@
}

Now, if we have some client side scripts, this will not work as the HttpPost method is expecting to use the ValidateAntiForgeryToken attribute.

What we need to do is simply add the following value to our json response

__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()

Example:
<script type="text/javascript">
        var data = {
            MyTextInput: $('#txbMyTextInput' + id).val(),
            MyDropDown: $('#cbMyDropDown' + id).is(':checked'),
            __RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
        };
 
        $.post('MyPostBackMethod', data,
        function (result) {
           //do something with result
        }, 'json');
<script />
There is no need to add any parameters on our method on the server side.